Home > Net >  how to get only contour area color range
how to get only contour area color range

Time:12-26

I want to get contour area color range and do some condition for example this is input image:input image Below is the code to find contours:

import cv2

img = cv2.imread('D:/original.png', cv2.IMREAD_UNCHANGED)

#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 100
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Now I am trying to get each contour color and write condition for example:

if contours[0] in color range ((100,100,100),(200,200,200)) then drawContour

All the things I'm trying to do are: get each contour area and check if selected contour is in specific color range or not.

CodePudding user response:

In order to extract single contours differentiated by color, the logical way to approach this problem would be to use the different colors and not convert the image to grayscale.

You can than work on single channels. For instance, for the the blue channel:

thresh = 100

ret,thresh_img = cv2.threshold(b, thresh, 255, cv2.THRESH_BINARY)

thresh on blue channel

Then with a combination of bit_wise operations, you can extract a specific contour.

Another approach would be to replace the threshold operator with the Canny operator.

thresh1 = 40
thresh2 = 120
#get canny image
thresh_img = cv2.Canny(img[:,:,0], thresh1,thresh2)
#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Which yields the following contours: Canny on blue channel

The use of Canny as preprocessing for contour is suggested by the enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

  • Related