15,662,782 members
See more:
How to count number of pixels inside a CRgn object?
One method is to get the bounding rect of the region and then checking for each pixel in the bounding rect whether it lies inside the CRgn or not.
This method takes more time and it depends on the size of CRgn object.
Is there any other method to calculate the number of pixel inside CRgn object which takes less time and which is not dependent on the size of CRgn object?
Posted

## Solution 3

Below is the code for calculating the number of pixel inside CRgn

C#
```int nNumberOfPixel = 0;
int nSize = m_pROIRgn->GetRegionData(NULL, NULL);
if(nSize)
{
RGNDATA * pRegion = (RGNDATA *) new char[nSize];
m_pROIRgn->GetRegionData(pRegion, nSize);
const RECT* pRect = (const RECT *) & pRegion->Buffer;
int rectcount = pRegion->rdh.nCount;
for(int i = 0; i < rectcount; i++)
{
nNumberOfPixel = nNumberOfPixel + ((pRect[ i ].right - pRect[ i ].left) * (pRect[ i ].bottom - pRect[ i ].top));
}
delete [] (char *) pRegion;
}```

Thanks CPallini and YDaoust for help.

CPallini 23-Jun-11 10:01am
Well done.
Please note, I suppose YDaoust is right, you are missing some points.

## Solution 1

You may call GetRegionData[^] method and then use the RGDNDATAHEADER[^] and RGNDATA[^] info to compute the number of pixel in the rectangles composing the region (just a guess, I didn't test it).

Roger Gonsalves 22-Jun-11 4:50am
Could you please explain it with example?
CPallini 22-Jun-11 4:56am
That would be the grunt work (and it is up to you). You should extract info of all the rectangles from the struct.

## Solution 2

I support what CPallini says. You can retrieve a region as a decomposition into rectangles. The total area is the sum of width x height for all these rectangles.

This will be very fast compared to querying every pixel. (Time proportional to the number of rows, or even less if the regions are simple.)

v2

## Solution 4

Should it be `right - left` or `right - left + 1` ? I mean, is `right` the last or afterlast abscissa ? (same about `bottom`)

Roger Gonsalves 27-Jun-11 1:37am
In my situation I want to ignore the bottom and right side (by 1 pixel) of the region.

## Solution 5

I did ask this question because errors of one pixel on width or height have a great impact.

For instance, in the case of a polygon with oblique sides, all returned rectangles can have a height of 1 row. If you compute 0 instead of 1, the total area will be 0; if you compute 2 instead of 1, you'll get the double area !

v2
Roger Gonsalves 28-Jun-11 0:44am
I have tried to print the rect information in the region and found that there is not a single case where top and bottom (or left and right) will be same.
If you came across any such scenario, can you please upload the code?
YDaoust 29-Jun-11 11:44am
This is a good sign. If you use a shape with non-vertical sides (ellipse), you should see a number rectangles with top and bottom differing by one, which confirms your formula.