# Count black pixel each column manual

Hi guys, i have already counted black pixel from binary image using countNonZero function. And i was curious to implement it manually. Here is my code to count black pixel on each column :

for(int aa = 0; aa < after_shear.cols;aa++){
Mat aaTmp = after_shear.col(aa);
int  jumlah = 0;
for(int oalah = 0; oalah < aaTmp.rows;oalah++){
for(int oalah2 = 0; oalah2<aaTmp.cols;oalah2++){
//cout <<(int)fuckTmp.at<uchar>(oalah,oalah2)<<endl;
if((int)aaTmp.at<uchar>(oalah,oalah2)==0){
jumlah++;
}
}
}

if(jumlah==0||jumlah==1){
pspArray2.push_back(fuck2);
}
}


But, it gives me zero result.

Can anyone help me ? Thanks

edit retag close merge delete

Sort by » oldest newest most voted

Why not start with naming your valuables into something senseworthy, like rows, cols, i and j. It would make your code much clearer. That being said, I am unsure why you need 3 for loops to go over a 2D matrix, when in principle 2 should be enough.

Some sample code that should work just fine

int counter = 0;
for (int row=0; row<image.rows; row++){
for(int col=0; col<image.cols; col++){
if(image.at<uchar>(row,col) == 0){
counter++;
}
}
}


This will only work IF

• The image is 8UC1, because the uchar is for an 8 bit jump.
• The black is actually black, so not very small values like 1 or 3 or so.
• Your image/mask is single channel. For a 3 channel you will need to use Vec3b iterators.

ADDITION: adding sample code for looking at transitions in columns

int previous = 0, current = 0, int counter = 0;
for (int col=1; col<image.rows; col++){
for(int row=1; row<image.cols; row++){
previous = image.at<uchar>(row-1,col-1);
current = image.at<uchar>(row,col);
if(previous  != current){
counter++;
}
}
}


Notice that I start calculating from the second element, because else we cannot compare. Also I am expecting white to be 255 or 1 and black to be 0, so only 2 possible values.

more

if i want to iterate each column, it means i should change image.at<uchar>(row,col) to image.at<uchar>(col,row) ? Thanks.

But why iterate over columns, that is so inefficient... it will have you jump through memory like crazy...

And no, the indexing has to stay row,col --> thats how OpenCV uses it coordinates. You can however, change the order of the loops but again, that will take longer than this code.

sorry, i still don't understand. could you give me an example ? Because actually i want to count number of transition from black to white pixel on each column. Thanks

Well actually that is something completely different. You never talked about transitions before. So for transitions in columns I will add some extra sample code.

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2017-05-30 21:56:10 -0500

Seen: 356 times

Last updated: Jun 01 '17