Wednesday, November 29, 2017

Histogram and binary image in opencv?




I would like to compute how many zeros and ones (e.i. 255) in a binary image. The following code to generate a binary image by using Matlab.


I = imread('images.jpg');
level = graythresh(I);
BW = im2bw(I, level);
imshow(BW)
imwrite(BW, 'img.jpg');

This is my C++ code.


#include 
#include

#include
#include
#include

std::map computeHistogram(const cv::Mat& image)
{
std::map histogram;

for ( int row = 0; row < image.rows; ++row)
{

for ( int col = 0; col < image.cols; ++col)
{
++histogram[(int)image.at(row, col)];

}
}

return histogram;
}


void printHistogram(const std::map& histogram)
{
std::map::const_iterator histogram_iter;
std::cout << "\n------------------\n";
for( histogram_iter = histogram.begin(); histogram_iter != histogram.end(); ++histogram_iter)
{
std::cout << std::setw(5) << histogram_iter->first << " : " << histogram_iter->second << "\n";
}
std::cout << "------------------\n";
}


int main(int argc, char **argv)
{
cv::Mat img = cv::imread("img.jpg", CV_BGR2GRAY);
printHistogram(computeHistogram(img));
return 0;
}

This is what I got


------------------

0 : 11451
1 : 590
2 : 602
3 : 498
4 : 428
5 : 376
6 : 387
7 : 349
8 : 314
9 : 278

10 : 229
11 : 206
12 : 212
13 : 159
14 : 142
15 : 112
16 : 106
17 : 96
18 : 86
19 : 54

20 : 44
21 : 37
22 : 26
23 : 26
24 : 14
25 : 14
26 : 10
27 : 4
28 : 7
29 : 8

30 : 2
32 : 7
33 : 2
34 : 3
36 : 2
37 : 4
38 : 1
211 : 1
216 : 1
217 : 1

219 : 4
220 : 2
221 : 2
223 : 3
224 : 5
225 : 2
226 : 4
227 : 4
228 : 5
229 : 8

230 : 15
231 : 19
232 : 22
233 : 25
234 : 36
235 : 21
236 : 54
237 : 54
238 : 64
239 : 93

240 : 113
241 : 111
242 : 127
243 : 163
244 : 193
245 : 182
246 : 202
247 : 218
248 : 263
249 : 289

250 : 291
251 : 301
252 : 403
253 : 458
254 : 469
255 : 29211
------------------

Is this right? What I'm expecting is the number of 0s and 255s.



Answer




The answer is posted as a reply to Otsu's method problem? . So it is now a duplicate I guess.


No comments:

Post a Comment

digital communications - Understanding the Matched Filter

I have a question about matched filtering. Does the matched filter maximise the SNR at the moment of decision only? As far as I understand, ...