【问题标题】:cv2.imwrite changes color when saving from np.array to JPG从 np.array 保存到 JPG 时 cv2.imwrite 改变颜色
【发布时间】:2017-01-26 23:44:27
【问题描述】:

我目前正在为一个班级开发边缘检测程序(具体来说,我正在检测街道线)。

我读入图像并检测到一些边缘(通过霍夫)。然后将检测到的边缘放置在原始图像上。在此过程中,图像数据存储为 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

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

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)

这个函数调用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

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

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)

最后,我将图像保存到光盘。这个调用会产生奇怪的颜色:

cv2.imwrite(new_file_name, combined_images)

而这个工作正常:

scipy.misc.imsave('outfile.jpg', combined_images)

这是未经处理的图像: natural colors

还有一个处理过的: distorted colors

您的帮助将不胜感激!

【问题讨论】:

  • 你还能附加生成的输出吗?根据我的直觉,您尝试保存在磁盘上的图像的RGBBGR 格式一定有问题。 cv2.imwrite() 期望输入图像为BGR 格式,但我不确定scipy.misc.imsave 的输入格式
  • @Marcel 你能上传你正在使用的图片吗?
  • 你好,我附上一张前后图!
  • 顺便说一句,为什么这个问题被否决了?这个问题不存在,我尽量做到准确,并遵循如何提问的指导方针。有什么提示吗?

标签: python python-3.x opencv color-channel


【解决方案1】:

@ZdaR 你是对的,cv2.imwrite 需要 BGR。我刚刚包含以下行:

image_to_write = cv2.cvtColor(combined_images, cv2.COLOR_RGB2BGR)

现在输出图像就好了:

cv2.imwrite(new_file_name, image_to_write)

谢谢! 目前,我不会接受我自己的答案作为解决方案;也许有人想发布更全面的内容。

【讨论】:

  • 我想知道图像的 RGB 颜色通道是否是 code image = mpimg.imread(img) code 或图像处理步骤之一的结果。使用 draw_lines 和 describe_lines 函数,我正在从一个数组中创建一个新图像。根据 numpy.ndarray 的信息创建的图像的默认颜色通道是什么?
  • 您现在可以接受您的回答。如果您遇到更好的答案,您可以更改它。
  • @MarcelB:请接受您的回答。 Opencv 将图像作为 BGR 存储在内存中(不是硬盘)。只是确认。
猜你喜欢
  • 2017-11-17
  • 2017-07-13
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多