c ++和opencv获取并将像素颜色设置为Mat

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23001512/
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-28 00:17:56  来源:igfitidea点击:

c++ and opencv get and set pixel color to Mat

c++opencvimage-processingpixelmat

提问by grll

I'm trying to set a new color value to some pixel into a cv::Mat image my code is below:

我正在尝试将某个像素的新颜色值设置为 cv::Mat 图像,我的代码如下:

    Mat image = img;
    for(int y=0;y<img.rows;y++)
    {
        for(int x=0;x<img.cols;x++)
        {
        Vec3b color = image.at<Vec3b>(Point(x,y));
        if(color[0] > 150 && color[1] > 150 && color[2] > 150)
        {
            color[0] = 0;
            color[1] = 0;
            color[2] = 0;
            cout << "Pixel >200 :" << x << "," << y << endl;
        }
        else
        {
            color.val[0] = 255;
            color.val[1] = 255;
            color.val[2] = 255;
        }
    }
    imwrite("../images/imgopti"+to_string(i)+".tiff",image);

It seems to get the good pixel in output (with cout) however in the output image (with imwrite) the pixel concerned aren't modified. I have already tried using color.val[0].. I still can't figure out why the pixel colors in the output image dont change. thanks

它似乎在输出(使用 cout)中获得了良好的像素,但是在输出图像(使用 imwrite)中,相关像素没有被修改。我已经尝试过使用 color.val[0] .. 我仍然无法弄清楚为什么输出图像中的像素颜色没有改变。谢谢

回答by Roger Rowland

You did everything except copying the new pixel value back to the image.

除了将新像素值复制回图像之外,您已完成所有操作。

This line takes a copy of the pixel into a local variable:

此行将像素的副本复制到局部变量中:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing coloras you require, just set it back like this:

因此,color根据需要进行更改后,只需将其设置回如下:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

所以,完整的,是这样的:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

回答by berak

just use a reference:

只需使用参考:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

回答by Flocke

I would not use .at for performance reasons.

出于性能原因,我不会使用 .at。

Define a struct:

定义一个结构:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

然后在你的 cv::Mat 图像上像这样使用它:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

image.ptr(y) 给你一个指向扫描线 y 的指针。并使用 x 和 y 循环遍历像素