Mat像素点位置的读取和设置方式

常用的有三种方式对Mat像素进行操作

1.数据指针快模式

这中方式需要用到Mat的 step 数据,step 表示每行数据所占的步长;
现在以一个统一的例子,给图像的中心块赋予红色。

string filename = "F:/data/lena.jpg";
Mat img = imread(filename);
//方法1; 指针模式 step
for (size_t i = img.rows/4; i < img.rows*3/4; i++)
{
	uchar* it = img.data + i * img.step; // 每行数据的起始位置
	it += (img.cols / 4)*3; // 列方向的偏移,这里为3个通道所以乘以3倍
	for (size_t j = img.cols/4; j < img.cols*3/4; j++)
	{
		it[0] = 0;
		it[1] = 0;
		it[2] = 255;
		it += 3;
	}
}

生成的图像为:

2. 行指针模式

同样以上图为例,赋予中心块为蓝色。

//方法2:行指针
for (size_t i = img.rows / 4; i < img.rows * 3 / 4; i++)
{
	Vec3b* it = img.ptr<Vec3b>(i);
	it += img.cols / 4;
	for (size_t j = img.cols / 4; j < img.cols * 3 / 4; j++)
	{
		(*it)[0] = 0;
		(*it)[1] = 255;
		(*it)[2] = 0;
		it++;
	}
}

在这里插入图片描述
如果是灰度图的话,读取的行数据为:

char* it = img.ptr<uchar>(i);

3.按坐标模式

这种方式,是官网推荐的,使用起来比较方便,但是效率会低于前两者。

//方法3:标准方法
for (size_t i = img.rows / 4; i < img.rows * 3 / 4; i++)
{
	for (size_t j = img.cols / 4; j < img.cols * 3 / 4; j++)
	{
		Vec3b& pixel = img.at<Vec3b>(i, j);
		pixel[0] = 255;
		pixel[1] = 0;
		pixel[2] = 0;
	}
}

在这里插入图片描述

总结

安装效率来说的话,三种方法,依次降低,不过个人比较喜欢用第二种方式。

发布了24 篇原创文章 · 获赞 4 · 访问量 8301

猜你喜欢

转载自blog.csdn.net/zhaitianyong/article/details/94602896