How to detect colored patches in an image using OpenCV?

To process the colorful image in HSV color-space is a good direction. And I split the channels and find the S channel is great. Because S is Saturation(饱和度) of color.

enter image description here

Then threshold the S with thresh of 100, you will get this.
enter image description here

It will be easy to separate the colorful region in the threshed binary image.


As @Mark suggest, we can use adaptive thresh other than the fixed one. So, add THRESH_OTSU in the flags.

Core python code is presented as follow:

##(1) read into  bgr-space
img = cv2.imread("test.png")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`)  
th, threshed = cv2.threshold(s, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY)

##(4) print the thresh, and save the result
print("Thresh : {}".format(th))
cv2.imwrite("result.png", threshed)


## >>> Thresh : 85.0

enter image description here

Related answers:

  1. Detect Colored Segment in an image
  2. Edge detection in opencv android
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Leave a Comment