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);
4
  • Have you considered simply using Mat bin = gray>=100;? Probably much faster and cleaner. Commented Sep 6, 2014 at 17:19
  • 2
    possible duplicate of Converting an OpenCV Image to Black and White Commented Sep 6, 2014 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 :( Commented Sep 6, 2014 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 Commented Sep 6, 2014 at 17:52

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.