how to set all pixels of a range of HSV values to another value in openCV with python?

Viewed 1493

i am using OpenCV with python. i want to replace the range of color by "white" color.

color range:

HMin = 130
SMin = 65
VMin = 135
HMax = 200
SMax = 160
VMax = 255

i know how to replace specific pixel value to another value:

im[np.where((im == [20,78,90]).all(axis = 2))] = [0,0,100]
cv2.imwrite('output.png', im)

so, do you know how could i use this method to set all pixels of a range of HSV values instead of a specific pixel value to another value?

1 Answers

Use inRange to find the mask, then replace the origin image with other value.

The following is replace the GREEN range into RED.

enter image description here

import numpy as np
import cv2

img = cv2.imread( "sunflower.jpg" )

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## mask of green (36,0,0) ~ (70, 255,255)
mask = cv2.inRange(hsv, (36, 0, 0), (70, 255,255))
bak = img.copy()

# replace with red 
bak[mask > 0] = (0, 0, 255)

cv2.imwrite("bak.png", bak)

Some links:

  1. How to define a threshold value to detect only green colour objects in an image :Opencv

  2. How to change the image color when the pixels hsv values are in specific ranges?

Related