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 

. 

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 &lt;opencv2\core\core.hpp&gt;
#include &lt;opencv2\highgui\highgui.hpp&gt;
#include &lt;opencv\cv.h&gt;
#include &lt;map&gt;
#include &lt;iomanip&gt;

std::map&lt;int, int&gt; computeHistogram(const cv::Mat&amp; image)
{
    std::map&lt;int, int&gt; histogram;

    for ( int row = 0; row &lt; image.rows; ++row)
    {
        for ( int col = 0; col &lt; image.cols; ++col)
        {
          ++histogram[(int)image.at&lt;uchar&gt;(row, col)];

        }
    }

    return histogram;
}

void printHistogram(const std::map&lt;int, int&gt;&amp; histogram)
{
    std::map&lt;int, int&gt;::const_iterator histogram_iter;
    std::cout &lt;&lt; "\n------------------\n";
    for( histogram_iter = histogram.begin(); histogram_iter != histogram.end(); ++histogram_iter)
    {
      std::cout &lt;&lt; std::setw(5) &lt;&lt; histogram_iter-&gt;first &lt;&lt;  " : " &lt;&lt; histogram_iter-&gt;second &lt;&lt; "\n";
    }
    std::cout &lt;&lt; "------------------\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.
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.)