在openCV中访问特定图像中所有像素的RGB值
Accessing RGB values of all pixels in a certain image in openCV
我已经彻底搜索了 Internet 和 Whosebug,但没有找到我要找的东西!
如何在 OpenCV 中获取特定图像(图像的所有像素)的 RGB(实际上是 BGR)值?我正在使用 C++,图像存储在 cv::Mat 变量中。
我展示了我到目前为止的一些努力:我从另一个 Whosebug link 尝试了这段代码。但是每次我重新 运行 代码时,十六进制值都会改变!例如它的 00CD5D7C,在下一个 运行 是 00C09D7C.
cv::Mat img_rgb = cv::imread("img6.jpg");
Point3_<uchar>* p = img_rgb.ptr<Point3_<uchar> >(10,10);
p->x; //B
p->y; //G
p->z; //R
std::cout<<p;
在另一次尝试中,我使用了另一个答案中的这段代码。这里的输出总是-858993460.
img_rgb.at<cv::Vec3b>(10,10);
img_rgb.at<cv::Vec3b>(10,10)[0] = newval[0];
img_rgb.at<cv::Vec3b>(10,10)[1] = newval[1];
img_rgb.at<cv::Vec3b>(10,10)[2] = newval[2];
cout<<newval[0]; //For cout<<newval[1]; cout<<newval[2]; the result is still same
注意:我使用 (10,10) 作为获取 RGB 的测试,我的目标是获取整个图像的 RGB 值!
由于您正在加载彩色图像(CV_8UC3
类型),您需要使用 .at<Vec3b>(row, col)
访问其元素。元素按 BGR 顺序排列:
Mat img_bgr = imread("path_to_img");
for(int r = 0; r < img_bgr.rows; ++r) {
for(int c = 0; c < img_bgr.cols; ++c) {
std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
img_bgr.at<Vec3b>(r,c) << std::endl;
}
}
你也可以使用Mat3b
(又名Mat_<Vec3b>
)来简化,这样你就不需要使用.at
函数,而是直接使用括号:
Mat3b img_bgr = imread("path_to_img");
for(int r = 0; r < img_bgr.rows; ++r) {
for(int c = 0; c < img_bgr.cols; ++c) {
std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
img_bgr(r,c) << std::endl;
}
}
要获取每个单独的频道,您可以轻松地做到:
Vec3b pixel = img_bgr(r,c); // or img_bgr.at<Vec3b>(r,c)
uchar blue = pixel[0];
uchar green = pixel[1];
uchar red = pixel[2];
我已经彻底搜索了 Internet 和 Whosebug,但没有找到我要找的东西!
如何在 OpenCV 中获取特定图像(图像的所有像素)的 RGB(实际上是 BGR)值?我正在使用 C++,图像存储在 cv::Mat 变量中。
我展示了我到目前为止的一些努力:我从另一个 Whosebug link 尝试了这段代码。但是每次我重新 运行 代码时,十六进制值都会改变!例如它的 00CD5D7C,在下一个 运行 是 00C09D7C.
cv::Mat img_rgb = cv::imread("img6.jpg");
Point3_<uchar>* p = img_rgb.ptr<Point3_<uchar> >(10,10);
p->x; //B
p->y; //G
p->z; //R
std::cout<<p;
在另一次尝试中,我使用了另一个答案中的这段代码。这里的输出总是-858993460.
img_rgb.at<cv::Vec3b>(10,10);
img_rgb.at<cv::Vec3b>(10,10)[0] = newval[0];
img_rgb.at<cv::Vec3b>(10,10)[1] = newval[1];
img_rgb.at<cv::Vec3b>(10,10)[2] = newval[2];
cout<<newval[0]; //For cout<<newval[1]; cout<<newval[2]; the result is still same
注意:我使用 (10,10) 作为获取 RGB 的测试,我的目标是获取整个图像的 RGB 值!
由于您正在加载彩色图像(CV_8UC3
类型),您需要使用 .at<Vec3b>(row, col)
访问其元素。元素按 BGR 顺序排列:
Mat img_bgr = imread("path_to_img");
for(int r = 0; r < img_bgr.rows; ++r) {
for(int c = 0; c < img_bgr.cols; ++c) {
std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
img_bgr.at<Vec3b>(r,c) << std::endl;
}
}
你也可以使用Mat3b
(又名Mat_<Vec3b>
)来简化,这样你就不需要使用.at
函数,而是直接使用括号:
Mat3b img_bgr = imread("path_to_img");
for(int r = 0; r < img_bgr.rows; ++r) {
for(int c = 0; c < img_bgr.cols; ++c) {
std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
img_bgr(r,c) << std::endl;
}
}
要获取每个单独的频道,您可以轻松地做到:
Vec3b pixel = img_bgr(r,c); // or img_bgr.at<Vec3b>(r,c)
uchar blue = pixel[0];
uchar green = pixel[1];
uchar red = pixel[2];