简体   繁体   中英

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.

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. 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. 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. 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.

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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