Search code examples
pythonopencvpixel

Change color of a pixel with OpenCV


Let say I have this rose (Do not care about the background, only the white leaves are important).

enter image description here

I transform it to a grayscale picture: grayscaled=cv2.imread('white_rose.png',cv2.IMREAD_GRAYSCALE)

How can I change every white pixel to a red one under the condition the red color (R=255) will have the same contrast as the white one has ? Meaning I want to see the white leaves in red color but with the same L value of every pixel that in grayscaled ?


Solution

  • You need to loop over your grey image and create a new coloured image by yourself.

    For each pixel, you can replace the R value of your coloured image with the remainder of dividing of 255 and relative grey value:

    import cv2
    import numpy as np
    
    img = cv2.imread('5585T.jpg')
    print type(img)
    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    new=[[[0,0,255%j] for j in i] for i in img_gray]
    dt = np.dtype('f8')
    new=np.array(new,dtype=dt)
    
    cv2.imwrite('img.jpg',new)
    

    enter image description here

    and with new=[[[255%j,255%j,j] for j in i] for i in img_gray] :

    enter image description here