我正在尝试将图像设为黑白,因此我将阈值100设置为100以下的所有值都将为黑色,其余值将为白色。所以我浏览每个像素并检查其值是否低于100然后我将值更改为0否则我将其更改为255.但代码不起作用。当我打印图像的值。图像的所有值都变为225。 运行前的图像The input image,这是运行the 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;
}
答案 0 :(得分:4)
if
语句有错误。删除分号。
if( img.at<int>(z,y) >= 100 ){
img.at<int>(z, y) = 255;
}else{
img.at<int>(z, y) = 0;
}
答案 1 :(得分:0)
请注意,您很可能不希望迭代所有像素,因为它可能无法针对某些处理器进行优化。使用opencv,您只需编写
即可img = img > 100;
与你的周期一样。
另一个选项是opencv function threshold
threshold(img, img, 100, 255, THRESH_BINARY)