Dealing with pixels in contours (OpenCV)?

10,022

Solution 1

First get all of your contours. Use this information to create a binary image with the white parts being the contour's outline and area. Perform an AND operation on the two images. The result will be the contours and area on a black background. Then just sum all of the pixels in this image.

Solution 2

If I understand right you want to sum all the pixel intensities from a gray image that are inside a contour. If so, the method that i think of is to draw that contour on a blank image and fill it , in so making yourself a mask. After that to optimize the process you can also compute the bounding rect of the contour with :

CvRect cvBoundingRect(CvArr* points, int update=0 );

After this you can make an intermediate image with :

void cvAddS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);

using the value 0, the mask obtained from the contour and setting before as ROI the bounding rect.

After this, a sum on the resulting image will be a little faster.

Share:
10,022
fdh
Author by

fdh

Please delete me.

Updated on June 15, 2022

Comments

  • fdh
    fdh almost 2 years

    I have retrieved a contour from an image and want to specifically work on the pixels in the contour. I need to find the sum (not area) of the pixel values in the contour. OpenCV only supports rectangle shaped ROI, so I have no idea how to do this. cvSum also only accepts complete images and doesn't have a mask option, so I am a bit lost on how to proceed. Does anyone have any suggestions on how to find the sum of the values of pixels in a specific contour?