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);
}
Counting PixelsNumPy provides a function sum() that returns the sum of all array elements in the NumPy array. This sum() function can be used to count the number of pixels on the basis of the required criteria.
Multiply the width of the image by its height (both in pixels) to get the pixel count. Hence, pixel count = 1,920 × 1,080 pixels . The precise answer is pixel count = 2,073,600 pixels .
Answer #1: For black images you get the total number of pixels (rows*cols) and then subtract it from the result you get from cv2. countNonZero(mat) . For other values, you can create a mask using cv2. inRange() to return a binary mask showing all the locations of the color/label/value you want and then use cv2.
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.
Use this
int nPixels = (m.cols*m.channels())*m.rows;
cout << nPixels << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With