Search code examples
pythonopencvpython-imaging-librarygray-code

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


Solution

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