10

How to get the number of pixels in an image? Following is my code, and I need to get the total number of pixels in Mat "m".

int main()
{
    Mat m = imread("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg");


    namedWindow("Image");
    imshow("Image",m);



    waitKey(0);


}
System.Windows.Form
  • 249
  • 1
  • 3
  • 11

2 Answers2

28

If you want the total number of pixels, use cv::Mat::total().

int nPixels = m.total();

Note that for multi-channeled images, the number of pixels is distinct from the number of elements in the array. Each pixel most commonly has between one (i.e. greyscale) and four (i.e. BGRA) elements per pixel.

Aurelius
  • 11,111
  • 3
  • 52
  • 69
1

Use this

int nPixels = (m.cols*m.channels())*m.rows;
cout << nPixels << endl;
PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 3
    This gives the number of elements in the data buffer, but **not** the number of pixels. (Except for single-channel images, that is.) – Aurelius Jun 07 '13 at 18:34