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;
	}
}

在這裏插入圖片描述

總結

安裝效率來說的話,三種方法,依次降低,不過個人比較喜歡用第二種方式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章