cv::Mat 优于 IplImage,因为它简化了您的代码
cv::Mat img = cv::imread("lenna.png");
for(int i=0; i<img.rows; i++)
for(int j=0; j<img.cols; j++)
// You can now access the pixel value with cv::Vec3b
std::cout << img.at<cv::Vec3b>(i,j)[0] << " " << img.at<cv::Vec3b>(i,j)[1] << " " << img.at<cv::Vec3b>(i,j)[2] << std::endl;
这假设您需要一起使用 RGB 值。如果不这样做,您可以使用 cv::split 分别获取每个通道。有关示例链接,请参见 etarion 的答案。
另外,在我的情况下,您只需要灰度图像。然后,您可以加载灰度图像并将其作为 uchar 数组访问。
cv::Mat img = cv::imread("lenna.png",0);
for(int i=0; i<img.rows; i++)
for(int j=0; j<img.cols; j++)
std::cout << img.at<uchar>(i,j) << std::endl;
更新:使用 split 获取 3 个频道
cv::Mat img = cv::imread("lenna.png");
std::vector<cv::Mat> three_channels = cv::split(img);
// Now I can access each channel separately
for(int i=0; i<img.rows; i++)
for(int j=0; j<img.cols; j++)
std::cout << three_channels[0].at<uchar>(i,j) << " " << three_channels[1].at<uchar>(i,j) << " " << three_channels[2].at<uchar>(i,j) << std::endl;
// Similarly for the other two channels
更新:感谢 entarion 发现我在从 cv::Vec3b 示例复制和粘贴时引入的错误。