首页 文章

在openCV中设置特定图像中像素的RGB值

提问于
浏览
1

我试图在二进制图像中设置一些像素的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 <= 2 && data &&(unsigned)i0 <(unsigned)size.p [0] &&(unsigned)(i1 * DataType <_Tp> :: channels)<(unsigned)(size.p 1 * channels())&&((((sizeof(size_t)<< 28)| 0x8442211)>>((DataType <_Tp> :: depth)&((1 << 3) - 1))* 4)& 15)== elemSize1())在cv :: Mat :: at,文件e:\ opencv \ opencv \ build \ include \ opencv2 \ core \ mat.hpp,第538行

这是任何类型的内存空间错误吗?在此先感谢您的帮助! :)

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

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;

我的测试图像就在这里

This is my test image here

输出就在这里

Output image here

1 回答

  • 0

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

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

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

相关问题