0

I would like to know what is the problem in below code, since it only appears only part of the Gray image as Binary image!

cv::Mat gry = cv::imread("image_gray.jpg");

cv::Mat bin(gry.size(), gry.type());

for (int i=0; i<gry.rows ;i++)

  {

   for (int j=0; j<gry.cols ;j++) 

   {
      if (gry.at<uchar>(i,j)>=100)

           bin.at<uchar>(i,j)=255;
      else 
          bin.at<uchar>(i,j)=0;

   }

  }

cv::namedWindow("After", cv::WINDOW_AUTOSIZE);

cv::imshow("After",bin);

waitKey(0);

cvDestroyWindow( "After" );

imwrite("binary_image.bmp", bin);
Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Z.usa
  • 3
  • 1
  • 3
  • Have you considered simply using `Mat bin = gray>=100;`? Probably much faster and cleaner. – Iwillnotexist Idonotexist Sep 06 '14 at 17:19
  • 2
    possible duplicate of [Converting an OpenCV Image to Black and White](http://stackoverflow.com/questions/7624765/converting-an-opencv-image-to-black-and-white) – Basilevs Sep 06 '14 at 17:19
  • Thank you very much for your answer lwillnotexist Idonotexist But I am a student and my instructor want do this step by step :( – Z.usa Sep 06 '14 at 17:51
  • Basilevs Thank you but it is not the same what I want in their case use built in function to do the convert but in my case I do this by loops – Z.usa Sep 06 '14 at 17:52

2 Answers2

2

Your problem is in cv::imread.
The function assumes it should load the image as a color image, if you want to load it as a garyscale image, you should call the function as follows:

cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE)

By the way, the reason you only see part of the image, is because the image is simply bigger than a uchar for each pixel. (and you end up iterating only over part of it).

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Dean Fenster
  • 2,345
  • 1
  • 18
  • 27
  • Thank you very much for your help. As you said the problem was with imread function. I am so grateful to your help I spent one day and didn't know what is the problem. Thank you. – Z.usa Sep 06 '14 at 19:27
0

it would be easier if you use use the OpenCV function:

cv::threshold(image_src, image_dst, 200, 255, cv::THRESH_BINARY);

This piece of code set as black value (255) all those pixels which have as original value 200.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30