c++ - 为什么成像操作在opencv中执行到图像的一半(垂直)

标签 c++ opencv image-processing

我正在使用 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);

The original image The binary image

如果您能调查一下这个问题/问题,将不胜感激。我想不通。

最佳答案

因为您正在处理一个 3 channel 图像(默认加载 imread ),就好像它是一个 1 channel 图像(您正在使用 .at<uchar> 访问它)。

确保处理灰度图像。要么:

  1. 直接加载为灰度:

    Mat img = imread("/Users/tanmoy/Documents/345.jpg", IMREAD_GRAYSCALE);
    Mat output = img.clone();
    
  2. 转换为灰度:

    Mat img = imread("/Users/tanmoy/Documents/345.jpg"); // Default loads a 3 channel image
    cvtColor(img, img, COLOR_BGR2GRAY);
    Mat output = img.clone();
    

请注意,您可以避免显式 for循环,要么:

  1. 使用 cv::threshold :

    Mat output;
    threshold(img, output, 128, 255, THRESH_BINARY);
    
  2. 使用矩阵二元运算:

    Mat output = img > 128;
    

关于c++ - 为什么成像操作在opencv中执行到图像的一半(垂直),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599036/

相关文章:

c++ - 链接到 boost 库

c++ - 如何在opencv C++中将文本放入图像中

C++ 与 Qt 编译失败

c++ - 如果使用 *pt = &stu1,字符串成员变为空

c# - 未找到 EmguCV DLL 异常 - 无法找到 cvextern?

matlab - 使用matlab从具有透视失真的图像中进行文本检测

algorithm - 计算密集型算法

android - 用于识别android中2个图像之间相似性的库

javascript - cv.Mat 不是构造函数 opencv

Python:使用 OpenCV 返回图像中任意/ dentry 形状的位置和大小