Search code examples
c++opencvarearoi

Calculate object area inside ROI in OpenCV


I want to calculate area of detected object (that blue marker I used) inside actual ROI. I mean one of those two rectangles that are my Regions Of Interest in Threshold image (which is black and white).

How to calculate area of object (I think - sum of "recognized" cluster of pixels, which are white color) inside ROI?

enter image description here

I just want to consider only those pixels that are inside of concrete ROI (in below example - the left one). So all pixels beyond left ROI will not be taken into calculations.

enter image description here

ROIs are created like this:

rectangle( imgOriginal, Point( 20, 100 ), Point( 170, 250), Scalar( 0, 0, 255 ), +5, 4 );
rectangle( imgThresholded, Point( 20, 100 ), Point( 170, 250), Scalar( 255, 255, 255 ), +5, 4 );
rectangle( imgOriginal, Point( 450, 100 ), Point( 600, 250), Scalar( 0, 0, 255 ), +5, 4 );
rectangle( imgThresholded, Point( 450, 100 ), Point( 600, 250), Scalar( 255, 255, 255 ), +5, 4 );

Solution

  • You may use cv::countNonZero function to count non-zero pixels inside ROI in imgThresholded image. This is exactly what you need.

    cv::Rect leftROI(cv::Point(20, 100), cv::Point(170, 250));
    int leftArea = cv::countNonZero(imgThresholded(leftROI));