Ask Your Question

How can I get the values of the pixels that are inside a contour?

asked 2019-06-27 15:17:08 -0500

Joe95ec gravatar image

I'm developing an application that allows the user to load an image, make a selection of a certain region (by drawing a random closed shape) and I want to have the values of the pixels that are inside this region but I'm having trouble doing so. All the functionality of drawing the shape on top of the image I've done it with PyQt and later the image with the draw on it is passed to a function where I want to analyze it with OpenCV.

Here is an example of the input image:

image description

So basically I want to get the values of the pixels inside the red shape. I know OpenCV already has a ROI function, but unfortunately the ROI selection is a square shape and I can't make square selections. They have to be a shape drawn by the user.

edit retag flag offensive close merge delete


sturkmen gravatar imagesturkmen ( 2019-06-29 12:29:29 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-06-29 10:21:45 -0500

Use a mask. Get the user selection as a contour then draw it as filled in a separate blank image. The 2nd image from the left below is the mask. Many OpenCV functions can use a mask. If you just need to access the pixels, you can iterate through each pixel in the contour's bounding rect roi but only use the ones that are "on" (non-zero) in the mask.

image description

edit flag offensive delete link more


@Chris what is PixProc2019?

sturkmen gravatar imagesturkmen ( 2019-06-29 15:40:56 -0500 )edit

It is a program I've been working on that allows you to test various computer vision algorithms and parameters. I plan to publish it later this year at

Chris gravatar imageChris ( 2019-06-30 15:07:32 -0500 )edit

Thanks a lot! I didn't get the user selection as a contour but I made a binary image of the input image with a lower and upper red threshold, then I filled the hole and I had a mask that I used to get the pixels inside. I didn't use contours because the actual images I'll process have a lot of objects in the scene but very little to no red at all. I will still consider using contours if using a threshold becomes a problem.

Joe95ec gravatar imageJoe95ec ( 2019-07-09 09:46:45 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2019-06-27 15:17:08 -0500

Seen: 1,286 times

Last updated: Jun 29 '19