我正在读取大小为 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
的图像, 那么你如何访问 1201
总共只有1200行的元素,其实你误解了mat.at<>()
的约定.我建议您使用 mat.at<>(cv::Point(p_x, p_y))
通过这种方式,您永远不会对要在 mat.at<>()
中传递的行和列感到困惑。 .
编辑: 但是,创建一个新的 cv::Point
不是@Micka 建议的访问像素的推荐方式,因此将其视为一种解决方法,不要完全依赖 cv::Point()
访问一个像素。迭代像素的最佳方法在 Opencv documentation 中定义。 .
关于c++ - 无法从灰度图像访问像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932316/