How to recolor multiple pixels in image - Python

Viewed 788

I tried this script for replacing the single color of the image. I need to recolor similar colors in image. For example, I have a blue, slate blue. I want to recolor both of these colors with red. But as I mentioned below, I cannot do that. It can be in PIL or OpenCV library in python.

Source of this code: Change specific RGB color pixels to another color, in image file

import numpy as np
from PIL import Image

image = Image.open('wall.jpg')
data = np.array(im)

r1, g1, b1 = 81, 90, 103 # Original value
r2, g2, b2 = 255, 0, 0 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.show()
1 Answers

From what I understand by your ' similar color ' is that you need to convert the blue color and its variants to red. I will give you a solution to do this in OpenCV. It is easier to segment colors in the HSV colorspace instead of RGB to create a mask of where the colors are present in that range using cv2.inRange.

After creating a mask as its values are 255 and 0, I divide it by 255 to convert it 1s and 0s followed by converting it to boolean. Then like you showed in your question wherever the mask is true the new color is placed. The code:

import cv2
import numpy as np

img = cv2.imread('2.jpg')
res = img.copy()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_green = np.array([40,50,50])
upper_green = np.array([80,255,255])
r2, g2, b2 = 255, 0, 0

mask = cv2.inRange(hsv, lower_green, upper_green)

mask = mask/255
mask = mask.astype(np.bool)
res[:,:,:3][mask] = [b2, g2, r2] # opencv uses BGR

cv2.imshow('image', img)
cv2.imshow('Result', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result

I converted the green color as blue was very less in this image. You can use [100, 50, 50] as your lower range and [130, 255, 255] as your upper range.

Related