尝试在给定阈值下将所有像素更改为黑白

Trying to change all the pixels to black and white at a given threshold

本文关键字:像素 黑白 阈值      更新时间:2023-10-16

我试图使图像黑白,所以我把阈值100。 所有低于 100 的值都将为黑色,其余值将为白色。所以我遍历每个像素并检查其值是否低于 100,然后我将值更改为 0,否则我将其更改为 255。但是代码不起作用。当我打印图像的值时。图像的所有值都变成了 225。运行前的图像 输入图像,这是运行后的图像输出

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

if语句有一个错误。删除其末尾的分号。

if( img.at<int>(z,y) >= 100 ){
    img.at<int>(z, y) = 255;
}else{
    img.at<int>(z, y) =   0;
}

请注意,您很可能不希望遍历所有像素,因为它可能没有针对某些处理器进行很好的优化。使用opencv,您可以简单地编写

img = img > 100;

这将与您的周期相同。

另一种选择是opencv函数threshold

threshold(img, img, 100, 255, THRESH_BINARY)