Skip to content

Instantly share code, notes, and snippets.

@xef6
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xef6/402118a27ace8247478f to your computer and use it in GitHub Desktop.
Save xef6/402118a27ace8247478f to your computer and use it in GitHub Desktop.
// 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