Home > Net >  How to replace color of image using opencv?
How to replace color of image using opencv?

Time:06-17

I'm trying to replace different colors in image using opencv.

Image is as below

I'm trying to replace border color and main object color which is shade of yellow into some other random different color say orange and red, first I tried to change border color as in below code

image = cv.imread(r'image.png')
hsv=cv.cvtColor(image,cv.COLOR_BGR2HSV)
yellow_lo=np.array([0,0,240])
yellow_hi=np.array([179,255,255])
mask=cv.inRange(hsv,yellow_lo,yellow_hi)

I get mask image as below

as you can see there's a gap between the lines in the border color , when I replace the color for this mask image I still can see the original color present in the image as below, line is not continously red in color

image[mask>0]=(0,0,255)

this is happening because pixel intensity of border varies its not constant as shown in below zoomed image

How can I solve this and replace the color of total border? I tried to erode and dilate mask image to complete broken line it didn't fix the issue. Any help suggestion to fix this will be highly appreciated.

CodePudding user response:

To replace the border you need a prominent mask. A mask that strongly represents the border.

Analyzing the third channel in HSV color space (value) gives the following:

enter image description here

Applying an appropriate threshold on this channel gives a well defined mask, which can later be used to replace the color:

mask = cv2.threshold(hsv[:,:,2], 150, 255, cv2.THRESH_BINARY)[1]
img[th==255]=(0,0,255)

enter image description here

  • Related