2

from this stackoverflow question i found this code

import numpy as np
import imutils
import cv2
img_rgb = cv2.imread('black.png')
Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)
img_rgb[mask == 255] = [0, 0, 255]
cv2.imshow("imgOriginal", img_rgb)  # show windows
cv2.imshow("mask", mask)  # show windows
cv2.waitKey(0)

is there any way i could change the line

img_rgb[mask == 255] = [0, 0, 255]

or something else to make it change a range of colors? for example:

([255, 255, 0], [255, 55, 10])
R4nsomW4re
  • 97
  • 1
  • 1
  • 6

1 Answers1

8

Yes you can.

First, you must create a mask of the color range to change, and the answer for that is the inRange function of OpenCV.

Then, via numpy, you can say where the mask is not 0 paint them in my image red. This is the code for that:

import numpy as np
import cv2

# load image and set the bounds
img = cv2.imread("D:\\debug\\HLS.png")
lower =(255, 55, 0) # lower bound for each channel
upper = (255, 255, 10) # upper bound for each channel

# create the mask and use it to change the colors
mask = cv2.inRange(img, lower, upper)
img[mask != 0] = [0,0,255]

# display it
cv2.imshow("frame", img)
cv2.waitKey(0)

If you want actually to get a range of colors (e.g. all blue colors) it is better to use HLS or HSV color spaces.

api55
  • 11,070
  • 4
  • 41
  • 57
  • when i run it i get an error message, Traceback (most recent call last): File "C:/Users/Blake/Desktop/Python3.7/opencvtests2.py", line 10, in mask = cv2.inRange(img, lower, upper) cv2.error: OpenCV(3.4.2) C:\projects\opencv- python\opencv\modules\core\src\arithm.cpp:1761: error: (-215:Assertion failed) ! _src.empty() in function 'cv::inRange' – R4nsomW4re Aug 06 '18 at 22:07
  • @R4nsomW4re it says that the image is empty... so make sure img was loaded correctly :) – api55 Aug 07 '18 at 07:12