Skip to content

Instantly share code, notes, and snippets.

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");
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 ){
unsigned totpix = img.rows*img.cols;
printf("%d black pixels out of %d total (%0.3f%%)\n",
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment