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

前端 未结 3 534
遇见更好的自我
遇见更好的自我 2020-12-08 02:18

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

    Mat image = img;
    for(int y=0;y

        
相关标签:
3条回答
  • 2020-12-08 02:47

    just use a reference:

    Vec3b & color = image.at<Vec3b>(y,x);
    color[2] = 13;
    
    0 讨论(0)
  • 2020-12-08 02:47

    I would not use .at for performance reasons.

    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:

    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

    0 讨论(0)
  • 2020-12-08 02:56

    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 color as you require, just set it back like this:

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题