1. 程式人生 > 實用技巧 >03.矩陣的掩膜操作

03.矩陣的掩膜操作

1、獲取影象畫素指標
2、掩膜操作解釋
3、程式碼演示

1、獲取影象畫素指標

2、掩膜操作解釋

掩膜操作實現影象對比度調整。
獲取影象的行數和列數程式碼:

int rows = picture1.rows;
int cols = picture1.cols * picture1.channels();

3、程式碼演示
未進行畫素範圍處理的掩膜操作圖片:

進行畫素範圍處理的掩膜操作圖片:

加強了對比度的提高,從圖片上看立體感更加強烈了
編寫進行掩膜操作的程式碼:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace cv;
using namespace std;

int main(int agrc, char** agrv)
{
	Mat picture1,picture2;
	picture1 = imread("F://opencvpicture//1.jpg");
	if (picture1.empty())
	{
		printf("圖片載入失敗..\n.");
		return -1;
	}
	namedWindow("input window", WINDOW_AUTOSIZE);
	imshow("input window", picture1);

	int cols =( picture1.cols-1) * picture1.channels();
	int rows = picture1.rows;
	int offsetx = picture1.channels();
	picture2 = Mat::zeros(picture1.size(),picture1.type());
	for (int row = 1;row<(rows-1);row++)
	{
		const uchar* previous = picture1.ptr<uchar>(row-1);
		const uchar* current = picture1.ptr<uchar>(row);
		const uchar* next = picture1.ptr<uchar>(row+1);
		uchar* p2current = picture2.ptr<uchar>(row);
		for (int col=offsetx;col<cols;col++)
		{
			p2current[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + previous[col] + next[col]));
		}
	}


	namedWindow("image demo window", WINDOW_AUTOSIZE);
	imshow("image demo window",picture2);

	waitKey(0);
	return 0;
}

利用函式進行掩膜操作:

完整程式碼:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace cv;
using namespace std;

int main(int agrc, char** agrv)
{
	Mat picture1, picture2;
	picture1 = imread("F://opencvpicture//1.jpg");
	if (picture1.empty())
	{
		printf("圖片載入失敗..\n.");
		return -1;
	}
	namedWindow("input window", WINDOW_AUTOSIZE);
	imshow("input window", picture1);

	Mat kernel = (Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
	filter2D(picture1,picture2,picture1.depth(),kernel);

	namedWindow("image demo window", WINDOW_AUTOSIZE);
	imshow("image demo window", picture2);

	waitKey(0);
	return 0;
}

獲取程式執行時間程式碼:

        double t = getTickCount();
	Mat kernel = (Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
	filter2D(picture1,picture2,-1,kernel);//-1取和原圖片同深度
	double timeconsume = (getTickCount() - t) / getTickFrequency();
	printf("timeconsume: %.2f\n",timeconsume);