Skip to content
Advertisement

How to convert color with OpenCV?

I am struggling with converting red color to another color, blue, yellow, green and so on.

I’ve already achieved to convert red color to gray scale color as bellow.

    img2 = cv2.imread('output2.jpg')
    img_hsv=cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)

    # lower mask (0-10)
    lower_red = np.array([0,50,50])
    upper_red = np.array([10,255,255])
    mask0 = cv2.inRange(img_hsv, lower_red, upper_red)

    # upper mask (170-180)                                                                                                                                                        
    lower_red = np.array([170,50,50])    
    upper_red = np.array([180,255,255])    
    mask1 = cv2.inRange(img_hsv, lower_red, upper_red)    

    # join my masks    
    mask = mask0+mask1    

    output_img = img2.copy()    
    output_img[np.where(mask!=0)] = 125

But what I really want to achieve is turn a color into another one but not gray scale. How should I change the code or any good reference? Thank you.

Advertisement

Answer

You are using the value 125 to all points in your mask with:

output_img[np.where(mask!=0)] = 125

If you want to change to a colored pixel, just assign a color array to that pixel such as:

output_img[np.where(mask!=0)] = [125, 50, 50] #RGB array

afterbefore

Complete code:

import numpy as np
import cv2
import matplotlib.pyplot as plt

img2 = cv2.imread('sample.png')
img_hsv=cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([50,50,0])
upper_red = np.array([255,255,50])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)

# upper mask (170-180)                                                                                                                                                        
lower_red = np.array([50,50,50])    
upper_red = np.array([255,255,180])    
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)    

# join my masks    
mask = mask0+mask1    

output_img = img2.copy()    
output_img[np.where(mask!=0)] = [125, 50, 50]


plt.imshow(img2)

plt.title('Original')
plt.show()

plt.imshow(output_img)

plt.title('After')
plt.show()
Advertisement