11

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); } 

2 Answers 2

29

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use this

int nPixels = (m.cols*m.channels())*m.rows; cout << nPixels << endl; 

1 Comment

This gives the number of elements in the data buffer, but not the number of pixels. (Except for single-channel images, that is.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.