c ++和opencv获取和设置像素颜色为Mat [英] c++ and opencv get and set pixel color to Mat
问题描述
我想为某个像素设置一个新的颜色值到cv :: Mat图像中我的代码如下:
Mat image = img;
for(int y = 0; y< img.rows; y ++)
{
for(int x = 0; 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);
看起来在输出中获得了良好的像素)相关像素不被修改。我已经尝试使用color.val [0] ..我仍然无法弄清楚为什么输出图像中的像素颜色不会改变。
感谢
除了将新的像素值复制回图像之外,
$ b
此行将像素的副本复制到局部变量中:
Vec3b color = image .at Vec3b(Point(x,y));
因此,在根据需要更改 color
,只需如下设置:
image.at< Vec3b>(Point(x,y))= color;
所以,完整的,像这样:
Mat image = img;
for(int y = 0; y< img.rows; y ++)
{
for(int x = 0; x {
//获取像素
Vec3b color = image.at< Vec3b>(Point(x,y));
// ...对颜色执行某些操作....
//设置像素
image.at< Vec3b>(Point(x,y ))= color;
}
}
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<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
You did everything except copy 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>(Point(x,y));
// ... do something to the color ....
// set pixel
image.at<Vec3b>(Point(x,y)) = color;
}
}
这篇关于c ++和opencv获取和设置像素颜色为Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!