我正在使用 opencv 进行非常简单的操作,但我无法理解为什么会出现此错误/问题。图像被操作到图像的一半(垂直)。
Mat img = imread("/Users/tanmoy/Documents/345.jpg");
Mat output = img.clone();
if( img.empty())
{
cout << "File not available for reading"<<endl;
return -1;
}
for(int y = 0; y < img.rows; y++){
for(int x = 0; x < img.cols; x++){
if(img.at<uchar>(y,x) < 128)
output.at<uchar>(y,x) = 0;
else
output.at<uchar>(y,x) = 256-1;
}
}
imwrite("/Users/tanmoy/Documents/binary.jpg", output);
如果您能调查一下这个问题/问题,将不胜感激。我想不通。
最佳答案
因为您正在处理一个 3 channel 图像(默认加载 imread
),就好像它是一个 1 channel 图像(您正在使用 .at<uchar>
访问它)。
确保处理灰度图像。要么:
直接加载为灰度:
Mat img = imread("/Users/tanmoy/Documents/345.jpg", IMREAD_GRAYSCALE); Mat output = img.clone();
转换为灰度:
Mat img = imread("/Users/tanmoy/Documents/345.jpg"); // Default loads a 3 channel image cvtColor(img, img, COLOR_BGR2GRAY); Mat output = img.clone();
请注意,您可以避免显式 for
循环,要么:
使用 cv::threshold :
Mat output; threshold(img, output, 128, 255, THRESH_BINARY);
使用矩阵二元运算:
Mat output = img > 128;
关于c++ - 为什么成像操作在opencv中执行到图像的一半(垂直),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599036/