从np.array保存为JPG时cv2.imwrite更改颜色

Cel*_* Y. 1 python opencv python-3.x color-channel

我是python的新手,目前正在为一个类开发边缘检测程序(具体来说,我正在检测街道线)。

我读入图像并检测到一些边缘(通过霍夫)。然后将检测到的边缘放置到原始图像上。在此过程中,图像数据存储为numpy.ndarry。最后,我想将图像保存到光盘(如jpg)。

如果我通过scipy.misc.imsave将映像写入光盘,则一切正常。如果我通过cv2.imwrite执行此操作,则颜色会失真为某种热图像。

我已经阅读了有关不同颜色通道和必要的缩放/转换的几个主题,但是找不到从numpy.ndarray到.jpg的解决方案。我知道.jpg可能只有8位或16位颜色通道,但不知道从那里开始。无论如何,我都盲目地试图除以255(->图像几乎为黑色)并乘以255(->发白的热图像:-))。

有任何想法吗?这些是代码的相关部分:

读取图像(稍后在循环中调用函数):

def read(img):
image = mpimg.imread(img)
return image

....
Run Code Online (Sandbox Code Playgroud)

在循环中调用绘制函数以绘制数组中定义的所有线

def draw_lines(img, line_coordinates, color=[255, 0, 0], thickness=4):
for line in line_coordinates:
    for x1,y1,x2,y2 in line:
        cv2.line(img, (x1, y1), (x2, y2), color, thickness)
Run Code Online (Sandbox Code Playgroud)

此函数调用draw函数并返回绘制了所有线条的图像

def depict_lines(img, array_of_coordinates): 
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, array_of_coordinates)
return line_img
Run Code Online (Sandbox Code Playgroud)

接下来,我结合原始图像和包含边缘的图像:

def weighted_img(line_img, initial_img, ?=0.95, ?=1., ?=0.):
return cv2.addWeighted(initial_img, ?, line_img, ?, ?)
combined_images = weighted_img(depicted_lines, original_image)
Run Code Online (Sandbox Code Playgroud)

最后,我将图像保存到光盘。此功能在这里产生奇怪的颜色:

cv2.imwrite(new_file_name, combined_images)
Run Code Online (Sandbox Code Playgroud)

而此功能可以正常工作:

scipy.misc.imsave('outfile.jpg', combined_images)
Run Code Online (Sandbox Code Playgroud)

这是未经处理的图像: 自然色

以及经过处理的一种: 扭曲的色彩

您的帮助将不胜感激!

Cel*_* Y. 5

@ZdaR您说得对,cv2.imwrite需要BGR。我只包括以下行:

image_to_write = cv2.cvtColor(combined_images, cv2.COLOR_RGB2BGR)
Run Code Online (Sandbox Code Playgroud)

现在,这可以输出图像了:

cv2.imwrite(new_file_name, image_to_write)
Run Code Online (Sandbox Code Playgroud)

谢谢!目前,我不会接受我自己的答案作为解决方案。也许某人想要发布更全面的信息。