3

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?

Ahmad 阿德
  • 155
  • 2
  • 12
  • with cv2.inRange you get a binary image out of it, then you can do `im[binaryImage == 255] = [0,0,100]` – api55 Oct 23 '18 at 06:53
  • @api55 do you mean `HSV-img = cv2.cvtColor(original-img, cv2.COLOR_BGR2HSV) minR = np.array([HMin, SMin, VMin]) maxR = np.array([HMax, SMax, VMax]) orange-mask = cv2.inRange(HSV-img, minR , maxR) original-img[orange-mask]=[0,0,100] ` – Ahmad 阿德 Oct 23 '18 at 07:57
  • Take a look to the answer, @Silencer did what I tried to say, with pictures and everything :) but what you said is more or less that, original-img[orange-mask > 0]=[0,0,100] – api55 Oct 23 '18 at 08:15

1 Answers1

6

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?

Kinght 金
  • 17,681
  • 4
  • 60
  • 74