Reputation: 159
I have such image as below and I want to change the pixel colors which have a specific BGR value of [99,30,233] or [255,31,101] to gray, and the rest to green.
Here is my code at the moment
image = cv.imread("path")
def change_img_color(image, image_dummy):
image_dummy[np.logical_or(np.all(image==[99,30,233],axis=2), np.all(image==[255,31,101],axis=2))] = [95, 95, 95]
image_dummy[np.logical_or(np.all(image==[146,61,65],axis=2),np.all(image==[147,177,218],axis=2))] = [95, 95, 95]
image_dummy[np.logical_or(np.all(image==[54,67,244],axis=2),np.all(image==[180,187,42],axis=2))] = [0, 0, 0]
image_dummy[np.logical_and(np.all(image_dummy!=[95,95,95],axis=2), np.all(image_dummy!=[0,0,0],axis=2))] = [50, 130, 110]
return image_dummy
The problem is that when I want to transform the image to this form, logically it should be like this: but it ends up like this:
I can't figure out why that orange color does not change to green color, when I specified all the pixels that are not gray and are not black should be converted to green.
Upvotes: 0
Views: 841
Reputation: 586
I think there's a typo somewhere and the red regions are not identified by the logic of your definition. To avoid such errors, it can be helpful to avoid "magic numbers".
Here's another approach to your problem based on a previous SO thread: https://stackoverflow.com/a/50215020/9870343.
image = cv2.imread("path")
cimage = image.copy()
color1 = np.array([99,30,233])
color2 = np.array([255,31,101])
gray = np.array([95,95,95])
green = np.array([110, 130, 50])
gscale = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
mask1 = cv2.inRange(image, color1, color1)
mask2 = cv2.inRange(image, color2, color2)
mask = mask1 + mask2
image[gscale!=0] = green
image[mask!=0] = gray
The output image:
Upvotes: 2