Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can iterate by columns of a matrix using col(). Then for each column you use cv::countNonZero and subtract that from your column-size and then you have the number of zero-pixels for each column:

cv::Mat1b img = cv::imread("img.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat1i black_pixels(img.cols, 1);

for(int x = 0; x < img.cols; x++){
  cv::Mat col = img.col(x);
  black_pixels(x,0) = img.rows - cv::countNonZero(col);
}

To your code: I don't know how it is related to the question. Some remarks: use the C++ instead of the C interface if you can, i.e. use Mat instead of IplImage then you can also iterate through it much easier. Furthermore, OpenCV has a histogram function, see http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=calchist#void%20calcHist%28const%20Mat%20images,%20int%20nimages,%20const%20int%20channels,%20InputArray%20mask,%20OutputArray%20hist,%20int%20dims,%20const%20int%20histSize,%20const%20float*%20ranges,%20bool%20uniform,%20bool%20accumulate%29 . Maybe you want to use this instead of your calculation. Good luck!

You can iterate by columns of a matrix using col(). Then for each column you use cv::countNonZero and subtract that from your column-size and then you have the number of zero-pixels for each column:

cv::Mat1b img = cv::imread("img.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat1i black_pixels(img.cols, 1);

for(int x = 0; x < img.cols; x++){
  cv::Mat col = img.col(x);
  black_pixels(x,0) = img.rows - cv::countNonZero(col);
}

To your code: I don't know how it is related to the question. Some remarks: use the C++ instead of the C interface if you can, i.e. use Mat instead of IplImage then you can also iterate through it much easier. Furthermore, OpenCV has a histogram function, see http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=calchist#void%20calcHist%28const%20Mat%20images,%20int%20nimages,%20const%20int%20channels,%20InputArray%20mask,%20OutputArray%20hist,%20int%20dims,%20const%20int%20histSize,%20const%20float*%20ranges,%20bool%20uniform,%20bool%20accumulate%29 . Maybe you want to use this instead of your calculation. Good luck!

Edit: Since you are dealing with binary data you can of course also use cv::sum(col)[0] instead of cv::countNonZero(col) - may be slightly faster.