c++ and opencv get and set pixel color to Mat
Solution 1:
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
}
}
Solution 2:
just use a reference:
Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;
Solution 3:
I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct BGR {
uchar blue;
uchar green;
uchar red; };
And then use it like this on your cv::Mat image:
BGR& bgr = image.ptr<BGR>(y)[x];
image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y