Change color of a pixel with OpenCV

故事扮演 提交于 2021-02-18 15:48:24

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/29125349/change-color-of-a-pixel-with-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!