Tuesday 2 June 2015

image processing - Otsu's method problem?


I have a problem with Otsu's method. I would like to implement histogram to compute how many ones' and zeros'. For Otsu's method, I have a code from a book and it is running without problem. This is the picture


here.


I've implemented a code to compute the histogram. This is the output of my code.


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

0 : 14332
1 : 2102
2 : 1387
3 : 745
4 : 221
5 : 117
6 : 27
7 : 9
248 : 6
249 : 12

250 : 48
251 : 162
252 : 396
253 : 830
254 : 1377
255 : 28554
------------------

Here's my code:


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;
}

Why this is the result? What I'm expecting is how many 255 and 0 (black and white only). Moreover, if I run another picture, I get another results with the range 0-255.



Answer



jpg is a compressed storage format and no matter how binary your image is, you will almost always end up with gray values in the resulting image (due to compression). Please save it as png and try again.


(Also note that you still have 0s and 255s as the dominant bins, because jpg generally degrades around the edges, which constitute a small portion in the image.)



No comments:

Post a Comment

readings - Appending 内 to a company name is read ない or うち?

For example, if I say マイクロソフト内のパートナーシップは強いです, is the 内 here read as うち or ない? Answer 「内」 in the form: 「Proper Noun + 内」 is always read 「ない...