Yasin
Yasin

Reputation: 619

Check if pixel is inside a connected component in opencv python

I'm thresholding an image which gives me some white regions. And I have a pixel location that's located in one of these regions. I'm using opencv connectedComponentsWithStats to get the regions and then find if the pixel is in any of these regions. How can I do that?

On that note, is there a better way of finding in which thresholded region that pixel is located?

Upvotes: 2

Views: 2815

Answers (2)

Gopiraj
Gopiraj

Reputation: 657

You can use pointPolygonTest function to check whether a point is inside a contour or not.

So, after thresholding, find the contours in the image using findContours function. Then you can pass the contours and the point to this function to check whether the point is inside the region or not.

Since you have the connected components and stats (that you found using connectedComponentsWithStats), you can test faster using this approach.

Upvotes: 0

Sanchit.Jain
Sanchit.Jain

Reputation: 608

numLabels, labelImage, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)

numLabels = number of labels or regions in your thresholded image

labelImage = matrix or image containing unique labels(1, 2, 3..) representing each region, background is represented as 0 in labelImage.

stats = stats is a matrix of stats which contains information about the regions.

centroids = centroid of each region.

In your case, you can use the labelImage to find out the unique label value on the pixel coordinate to find out in which region it lies in.

Upvotes: 3

Related Questions