How to get the total of the same number in a MAT

Hi, I have a mat M size -1 X48 M = [4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0]

How can i seggregate and know that inside the Mat there are 5 frequency for #3, 8 frequency for #2 and 5 frequency of #4.

Example for my code here not able to calculate #2 and only stated 0. Any advice?

 for(int y=0;y< 1;y++){
for (int x=0;x< 48; x++){

if (frame_gray.at<uchar>(y,x)==2)
{ two++;}
else {}

}  }

cout << "zero =" << zero << endl;
cout << "two =" << two << endl;
cout << "four =" << four << endl;


the output

M = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0]

zero =0 two =0 four =0

edit retag close merge delete

Sort by ยป oldest newest most voted

i think, you want a histogram here. one could use calcHist for this, but it's probably overkill.

// demo data:
Mat_<uchar> data(1,48);
data << 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0;

// uchar Mat's can hold 256 distinct values:
Mat_<int> hist(256, 1);
hist = 0; // all set to 0 initially

for (int i=0; i<data.cols; i++) {
uchar v = data(0,i);
hist(v) ++;  // increase bin for number
}

cerr << hist(0) << " zeros." << endl;
cerr << hist(2) << " twos." << endl;
cerr << hist(4) << " fours." << endl;

// output
35 zeros.
8 twos.
5 fours.

more

thanks @berak

( 2017-03-13 02:22:02 -0500 )edit

@berak, what is the data type of hist(0)? i tried to get the percentage by calculating it..

Mat_<int> hist(256, 1);
hist = 0; // all set to 0 initially

for (int i=0; i<data.cols; i++) {
uchar v = data(0,i);
hist(v) ++;  // increase bin for number
}

float twos = (hist(2)/13)*100;

cerr << hist(0) << " zeros." << endl;
cerr << twos << " twos." << endl;
cerr << hist(4) << " fours." << endl;


found the twos always displays 0 instead of number previoulsy if I do not do any operation on the hist(2).I think my code should be correct but the data type maybe cause me a problem.

thanks

( 2017-11-14 04:51:26 -0500 )edit
1

@zms, it is int, like the Mat it is in ..

therefore, you have to take care with divisions, since 1/17==0, etc. no automatic conversion here !

you have to either reorder the terms (and properly brace it), like:

int twos = (hist(2)*100)/13; // again, don't expect a "magic" conversion !


or , better, explicitly cast it to float before the division:

float h2 = (float)hist(2);
float twos = (h2/13)*100;

( 2017-11-14 04:59:20 -0500 )edit

thanks berak!

( 2017-11-15 20:49:20 -0500 )edit