无法从灰度图像访问像素值

Unable to access pixel values from greyscale image

本文关键字:像素 访问 灰度图像      更新时间:2023-10-16

我正在读取大小为1600x1200的灰度图像,然后试图访问位置(1201,0)的像素值。最后我得到了段错误,如注释所示:

Mat gray_image = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);   // Read the file
if(! gray_image.data )                              // Check for invalid input
{
    cout <<  "Could not open or find the image" << std::endl ;
    return -1;
}
const int width = gray_image.cols; 
const int height = gray_image.rows;
cout<<gray_image.cols<<endl; // 1600
cout<<gray_image.rows<<endl; // 1200
cout<<(int)gray_image.at<uchar>(1201,0)<<endl; //SEGFAULT

您已经说过您正在读取大小为1600x1200的图像,那么您如何仅从总共1200行中访问1201元素,实际上您误解了mat.at<>()的约定。我建议您以这种方式使用mat.at<>(cv::Point(p_x, p_y)),您永远不会与mat.at<>()中传递的行和颜色混淆。

EDIT:然而,创建一个新的cv::Point并不是@Micka建议的访问像素的推荐方式,因此将其视为一种变通方法,不要完全依赖cv::Point()来访问像素。迭代像素的最佳方法在Opencv文档中定义。

应该是。at(row,col)而不是(col,row)并且你没有第1201行这就是为什么它是一个分段错误