我已经彻底搜索了互联网和 stackoverflow,但我还没有找到我的问题的答案:
如何在 OpenCV 中获取/设置某些(由 x,y 坐标给出)像素的(两者)RGB 值?重要的是,我用 C++ 编写,图像存储在 cv::Mat 变量中。我知道有一个 IplImage() 运算符,但是 IplImage 使用起来不太舒服——据我所知它来自 C API。
是的,我知道 OpenCV 2.2 中已经存在像素访问< /a> 线程,但它只是关于黑白位图。
编辑:
非常感谢您的所有回答。我发现有很多方法可以获取/设置像素的 RGB 值。我从我的好朋友那里得到了另一个想法——谢谢本尼!这非常简单有效。我认为选择哪一个只是品味问题。
Mat image;
(...)
Point3_<uchar>* p = image.ptr<Point3_<uchar> >(y,x);
然后您可以使用以下命令读取/写入 RGB 值:
p->x //B
p->y //G
p->z //R
I have searched internet and stackoverflow thoroughly, but I haven't found answer to my question:
How can I get/set (both) RGB value of certain (given by x,y coordinates) pixel in OpenCV? What's important-I'm writing in C++, the image is stored in cv::Mat variable. I know there is an IplImage() operator, but IplImage is not very comfortable in use-as far as I know it comes from C API.
Yes, I'm aware that there was already this Pixel access in OpenCV 2.2 thread, but it was only about black and white bitmaps.
EDIT:
Thank you very much for all your answers. I see there are many ways to get/set RGB value of pixel. I got one more idea from my close friend-thanks Benny! It's very simple and effective. I think it's a matter of taste which one you choose.
Mat image;
(...)
Point3_<uchar>* p = image.ptr<Point3_<uchar> >(y,x);
And then you can read/write RGB values with:
p->x //B
p->y //G
p->z //R
发布评论
评论(6)
尝试以下操作:
image.at(y,x);
为您提供cv::Vec3b
类型的 RGB(可能以 BGR 形式排序)向量代码>Try the following:
image.at<cv::Vec3b>(y,x);
gives you the RGB (it might be ordered as BGR) vector of typecv::Vec3b
低级方法是直接访问矩阵数据。在 RGB 图像中(我相信 OpenCV 通常将其存储为 BGR),并假设您的 cv::Mat 变量称为
frame
,您可以在位置 (x
>,y
)(从左上角开始)这样:同样,获取 B、G 和 R:
请注意,此代码假设步幅等于图像的宽度。
The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called
frame
, you could get the blue value at location (x
,y
) (from the top left) this way:Likewise, to get B, G, and R:
Note that this code assumes the stride is equal to the width of the image.
对于遇到此类问题的人来说,一段代码更容易。我把我的代码分享出来,大家可以直接使用。请注意,OpenCV 将像素存储为 BGR。
A piece of code is easier for people who have such problem. I share my code and you can use it directly. Please note that OpenCV store pixels as BGR.
当前版本允许
cv::Mat::at
函数处理 3 个维度。因此,对于Mat
对象m
,m.at(0,0,0)
应该可以工作。The current version allows the
cv::Mat::at
function to handle 3 dimensions. So for aMat
objectm
,m.at<uchar>(0,0,0)
should work.