python - 从 np.array 保存到 JPG 时,cv2.imwrite 改变颜色

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

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

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

如果我通过 scipy.misc.imsave 将图像写入光盘,一切正常。 如果我通过 cv2.imwrite 执行此操作,颜色会扭曲成一种热图像。

我已经阅读了几个关于不同颜色 channel 和必要的缩放/转换的主题,但我找不到从 numpy.ndarray 到 .jpg 的解决方案。 我知道 .jpg 可能只有 8 位或 16 位颜色 channel ,但不知道从那里去哪里。在任何情况下,我都盲目地尝试除以 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)

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

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

非常感谢您的帮助!

最佳答案

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

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

现在输出图像就好了:

cv2.imwrite(new_file_name, image_to_write)

谢谢! 现在,我不会接受我自己的答案作为解决方案;也许有人有更全面的她或他想发布。

关于python - 从 np.array 保存到 JPG 时,cv2.imwrite 改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884996/

相关文章:

python - 解析具有复杂分隔符的文本文件

python - 使用 image.merge 合并 tif 图像

python - 用 numpy 初始化的数组在带有 if 语句的循环中要慢得多

python - txt 文件的字数统计并输出到文件

循环示例中的 Python 变量范围

Python 为什么要导入内置函数

python - 将数组字符串格式化为逗号分隔文件

c++ - Boost thread_group 返回空矩阵(openCV)

c++ - 在 OpenCV 中为 BRISK 设置参数

Python opencv子进程写入返回损坏的管道