简体   繁体   English

使用Python将灰度图像转换为其原始颜色格式

[英]Converting a Grayscale image to its original color format using Python

Hi I am currently working on trying to convert a gray scale image to its original color format using Open CV in python. 嗨,我目前正在尝试使用python中的Open CV将灰度图像转换为其原始颜色格式。

import cv2

img = cv2.imread('bw.jpg')

img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)


cv2.imwrite('gray_image.png',gray_image)

executing this produces an error: 执行此操作将产生错误:

error: (-215) scn == 1 && (dcn == 3 || dcn == 4) in function cv::cvtColor

Code in Python Imaging Library are also welcome. 也欢迎使用Python Imaging Library中的代码。 Any help will be appreciated. 任何帮助将不胜感激。

Thank you 谢谢

I am assuming that you are trying to convert a single channel image to 3 channel grayscale image. 我假设您正在尝试将单通道图像转换为3通道灰度图像。 You are reading the image as img = cv2.imread('bw.jpg') , by default if you do not pass any param to cv2.imread() , then it reads a 3 channel image, irrespective of the original number of channels in the image. 您将图像读取为img = cv2.imread('bw.jpg') ,默认情况下,如果未将任何参数传递给cv2.imread() ,则它将读取3通道图像,而与原始通道数cv2.imread()在图像中。 You may simply remove the line cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) , as the img is already a 3 channel image with only grayscale information. 您可以简单地删除cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) ,因为img已经是一个3通道图像,仅包含灰度信息。

However if you are into this delusion that OpenCV has functionality of filling RGB colors to your grayscale image, then you are probably using wrong library. 但是,如果您认为OpenCV具有将RGB颜色填充到灰度图像中的功能,那么您可能使用了错误的库。 You can checkout other Open Source projects like this , which colorise your image using Deep Learning. 您可以签出其他像这样的开源项目,这些项目使用深度学习使图像着色。

See inline comment where mistake was made. 看到错误的地方,请查看内联注释。

import cv2

img = cv2.imread('bw.jpg')

x = img.shape

# check for color or gray-scale image type.
if x[3] == 3:

   print 'Got color image'
   # variable "gray_image" linked to result.
   gray_image = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)

   cv2.imwrite('gray_image.png',gray_image) # varname no longer img > gray_image.

else:
    print 'Got black/white, single channel image.'
    url = 'https://github.com//gustavla//autocolorize'
    print "Using ZdaR's posted solution from %s" % (url)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM