C++ 在 opencv 中使用 Mat::at(i,j) 作为二维 Mat 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14303073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:12:07  来源:igfitidea点击:

Using Mat::at(i,j) in opencv for a 2-D Mat object

c++opencvimage-processing

提问by Chani

I am using Ubuntu 12.04 and OpenCV 2

我正在使用 Ubuntu 12.04 和 OpenCV 2

I have written the following code :

我写了以下代码:

IplImage* img =0;
img = cvLoadImage("nature.jpg");
if(img != 0)
{
    Mat Img_mat(img);
    std::vector<Mat> RGB;
    split(Img_mat, RGB);

    int data = (RGB[0]).at<int>(i,j)); /*Where i, j are inside the bounds of the matrix size .. i have checked this*/ 
}

The problem is I am getting negative values and very large values in the data variable. I think I have made some mistake somewhere. Can you please point it out.
I have been reading the documentation (I have not finished it fully.. it is quite large. ) But from what I have read, this should work. But it isnt. What is going wrong here?

问题是我在数据变量中得到负值和非常大的值。我想我在某个地方犯了一些错误。你能不能指出来。
我一直在阅读文档(我还没有完全读完……它很大。)但是从我读过的内容来看,这应该有效。但它不是。这里出了什么问题?

回答by rotating_image

Img_matis a 3 channeled image. Each channel consists of pixel values ucharin data type. So with split(Img_mat, BGR)the Img_matis split into 3 planes of blue, green and red which are collectively stored in a vector BGR. So BGR[0]is the first (blue) plane with uchardata type pixels...hence it will be

Img_mat是一个 3 通道图像。每个通道由uchar数据类型的像素值组成。因此,split(Img_mat, BGR)Img_mat被分成蓝色、绿色和红色的 3 个平面,它们共同存储在一个向量中BGR。所以,BGR[0]是第一个(蓝色)平面与uchar数据类型像素...因此,这将是

int dataB = (int)BGR[0].at<uchar>(i,j);
int dataG = (int)BGR[1].at<uchar>(i,j);

so on...

很快...

回答by flowfree

You have to specify the correct type for cv::Mat::at(i,j). You are accessing the pixel as int, while it should be a vector of uchar. Your code should look something like this:

您必须为 指定正确的类型cv::Mat::at(i,j)。您正在访问像素为int,而它应该是 的向量uchar。您的代码应如下所示:

IplImage* img = 0;
img = cvLoadImage("nature.jpg");
if(img != 0)
{
  Mat Img_mat(img);
  std::vector<Mat> BGR;
  split(Img_mat, BGR);

  Vec3b data = BGR[0].at<Vec3b>(i,j);
  // data[0] -> blue
  // data[1] -> green
  // data[2] -> red
}

回答by aLu

Why are you loading an IplImage first? You are mixing the C and C++ interfaces. Loading a cv::Mat with imread directly would be more straight-forward.

为什么要先加载 IplImage?您正在混合 C 和 C++ 接口。直接用 imread 加载 cv::Mat 会更直接。

This way you can also specify the type and use the according type in your at call.

通过这种方式,您还可以指定类型并在通话中使用相应的类型。