Locating, or counting, non-zero elements can come in quite handy, especially when looking for specific regions in an image after a threshold operation, or when looking for the area covered by a specific color. OpenCV contains the findNonZero and countNonZero functions, which simply allow you to find or count the pixels with non-zero (or bright) values in an image.
Here is an example that depicts how you can use the findNonZero function to find the first non-black pixel in a grayscale image and print its position:
Mat image = imread("Test.png", IMREAD_GRAYSCALE); Mat result; vector<Point> idx; findNonZero(image, idx); if(idx.size() > 0) cout << idx[0].x << "," << idx[0].y << endl;
Here is another example code that shows how you can find the percentage of black pixels in a grayscale image:
Mat image = imread("Test.png", IMREAD_GRAYSCALE); Mat result; int nonZero = countNonZero(image); float white = float(nonZero) / float(image.total()); float black = 1.0 - white; cout << black << endl;