【问题标题】:Setting RGB values of pixels in a certain image in openCV在openCV中设置某个图像中像素的RGB值
【发布时间】:2017-06-08 00:34:36
【问题描述】:

我正在尝试设置二进制图像中某些像素的 RGB 值。但是每当坐标超过 (89, 89) 时,它就会给我一个断言错误!我的图像分辨率没问题,因为我正在从 (150, 150) 坐标访问 RGB 值。如果坐标为 (89, 89) 或更小,则可以正常工作。我的代码:

cv::Mat img_gray, img_bw;
//read an image
cv::Mat3b img_bgr = cv::imread("test.jpg");
cv::imshow("Original Image", img_bgr);

//conversion to binary from color
cv::cvtColor(img_bgr, img_gray,CV_RGB2GRAY);
cv::threshold(img_gray, img_bw, 75.0, 255.0, THRESH_BINARY);

//accessing BGR of position (150, 150) from a color image
std::cout<<"Pixel at position (x, y) : ("<<150<<", "<<150<<") ="<<img_bgr(150,150)<<std::endl;  

//Setting BGR of position (150, 150) in binary image
img_bw.at<Vec3b>(150, 150)[0] = 255;
img_bw.at<Vec3b>(150, 150)[1] = 255;
img_bw.at<Vec3b>(150, 150)[2] = 255;
std::cout<<"Pixel at position (x, y) : ("<<150<<", "<<150<<") ="<<img_bw.at<Vec3b>(150, 150)<<std::endl;

如果我在“设置 BGR”部分中输入 89 而不是 150,那么它就可以工作。否则完整的错误是:

OpenCV 错误:断言失败 (dims ::channels) 1*channels()) && ((((sizeof(size_t)> ((DataType<_tp>::depth) & ((1

那么这是任何类型的内存空间错误吗? 提前感谢您的帮助! :)

更新:我已经尝试过这种方式!但是现在输出是空白的。

cv::Mat img_gray, img_bw;
//read an image
cv::Mat3b img_bgr = cv::imread("test.jpg");
cv::imshow("Original Image", img_bgr);

//conversion to binary from color
cv::cvtColor(img_bgr, img_gray,CV_RGB2GRAY);
cv::threshold(img_gray, img_bw, 75.0, 255.0, THRESH_BINARY);

//accessing BGR of position (150, 150) from a color image
std::cout<<"Pixel at position (x, y) : ("<<150<<", "<<150<<") ="<<img_bgr(150,150)<<std::endl;  

//Setting BGR of position (150, 150) in binary image
img_bw.at<uchar>(150, 150) = 255;
std::cout<<"Pixel at position (x, y) : ("<<150<<", "<<150<<") ="<<img_bw.at<uchar>(150, 150)<<std::endl;

我的测试图在这里

输出在这里

【问题讨论】:

  • 您的 img_bw 是灰色类型。因此,您无法通过键入 img_bw.at 访问任何像素。您应该改用 img_bw.at(150,150) = 255
  • @alex 我已经试过了。在那种情况下,我的 std::cout
  • @TousifZaman 我们无法修复您未向我们展示的代码。你知道使用Vec3b 是不正确的。如果您使用 uchar 向我们展示您的代码以及错误和您的输入图像,也许我们可以帮助您。
  • @TousifZaman 更新应该使用edit 添加到问题本身,而不是在 cmets 中。我们还没有您的输入图像,因此我们无法重现您的错误。
  • 您正在打印出&lt;uchar&gt;,其值为0255。这些(在 ascii 或 utf-8 中)都不是可打印的字符。尝试将像素值分配给 int 变量,然后打印。

标签: c++ opencv image-processing


【解决方案1】:

好的,感谢烧杯在评论中的提示,我现在有了答案 :) 我正在为其他人提供解决方案!

我只需要将输出定义为整数。所以最后一个 cout 会是这样的

std::cout<<"Pixel at position (x, y) : ("<<150<<", "<<150<<") ="<<(int)img_bw.at<uchar>(150, 150)<<std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 2020-05-18
    • 2018-12-12
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多