Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// countnonzeropixels.cpp: count the number of non zero value pixels in an image and print it
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
char *fname = argv[1];
if (argc != 2) {
fprintf(stderr, "usage: countnonzeropixels img.jpg\n");
exit(1);
}
Mat img = imread(fname);
unsigned n = 0;
for(int y=0; y<img.rows; y++){
uchar* img_ptr = img.ptr<uchar>(y);
for(int x=0; x<img.cols; x++){
if( img_ptr[x*3] == 0 ){
n++;
}
}
}
unsigned totpix = img.rows*img.cols;
printf("%d black pixels out of %d total (%0.3f%%)\n",
n,totpix,100*n/(float)totpix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment