0

I am trying to make an image black and white so i put threshold 100. all the values below 100 will be black and the rest will be white. So i go through every pixel and check its value if it below 100 then i change the value to 0 otherwise i change it to 255. but the code doesn't work. when i print the values of the image. all the value of the image became 225. Image before run The input image and this is the image after runthe output

int main()
{
int x;
Mat img = imread("Canny.png");
cout << depthToStr(img.depth()) << endl;

img.convertTo(img, CV_32S);
// threshold  100. 
for (int z = 0; z < img.rows; z++)
{
    for (int y = 0; y < img.cols; y++)
    {
        if (img.at<int>(z,y) >= 100);
        {
            img.at<int>(z, y) = 225;
        }
    }

}
// Print the images.
for (int z = 0; z < img.rows; z++)
{
    for (int y = 0; y < img.cols; y++)
    {
        cout << img.at<int>(z, y) <<  "\t";
    }
    cout << endl;
}
img.convertTo(img, CV_8U);
imshow(" ",img);
waitKey(0);
cin >> x;
waitKey(0);
return 0;
}
Jed
  • 171
  • 3
  • 11
  • Check the range of values present in your image before thresholding so as to be able to choose a sensible threshold value https://stackoverflow.com/a/15956104/2836621 – Mark Setchell Feb 03 '18 at 12:44

2 Answers2

4

The if statement has a bug. Remove the semicolon at its end.

if( img.at<int>(z,y) >= 100 ){
    img.at<int>(z, y) = 255;
}else{
    img.at<int>(z, y) =   0;
}
shawnhcorey
  • 3,545
  • 1
  • 15
  • 17
0

Note that you most likely don't want to iterate over all pixels because it might not be well optimized for some processors. With opencv you can simply write

img = img > 100;

which would do the same as your cycle.

Another option is opencv function threshold

threshold(img, img, 100, 255, THRESH_BINARY)
Dmitrii Z.
  • 2,287
  • 3
  • 19
  • 29