opencv學習筆記(一)

不愛說話的圓圓發表於2020-10-07
1.Mat 物件和IPImage 物件

IPImage 內部存在記憶體洩漏問題,因此一般不用此物件

mat類常用的建構函式:
Mat::Mat()
Mat::Mat(int rows, int cols, int type)
Mat::Mat(Size size, int type)
Mat::Mat(int rows, int cols, int type, const Scalar& s)
Mat::Mat(Size size, int type, const Scalar& s)
Mat::Mat(const Mat& m)
Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
Mat::Mat(const Mat& m, const Range& rowRange, const Range& colRange)

補充使用方法:

M4 = (Mat_(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);

Mat M8 = Mat::zeros(src.size(), src.type());

案例說明:

	Mat M(100, 100, CV_8UC1, Scalar(127));
	cout << "M=" << M << endl;

	Mat M2(10, 10, CV_8UC3, Scalar(0, 0, 255));
	cout << "M1=" << M2 << endl;

	Mat M3;
	M3.create(src.size(), src.type());
	M3 = Scalar(0, 255, 0);

	Mat M4;
	M4 = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);

	Mat M5 = Mat::eye(src.size(), src.type());
	Mat M6 = Mat::eye(2, 2, src.type());
	Mat M7 = Mat::eye(3, 3, CV_8UC3);
	Mat M8 = Mat::zeros(src.size(), src.type());
	Mat M9 = Mat::zeros(2, 2, CV_8UC2);

其中scalar的使用為進行通道賦值

2.常用簡單方法屬性:

clone copyto ptr channels cols rows

	Mat dst;
	src.copyTo(dst);
	printf("the first row pixel value is %d\n ", dst.ptr<char>(0));
	printf(" rows : %d\n", dst.rows);
	printf(" cols : %d\n", dst.cols);
	printf("channels of dst:%d\n", dst.channels());
3.使用醃模進行影像的增強處理
#include "pch.h"
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2/opencv.hpp>  
#include<iostream>
#include<math.h>

using namespace std;
using namespace cv;
 
int main()
{
	Mat src,dst;
	src = imread("./test.png");
	if (!src.data)
	{
		printf("There is no photo!\n");
		return -1;
	}
	namedWindow("input_image", CV_WINDOW_AUTOSIZE);
	imshow("input_image", src);

//使用指標讀取對應行指標
/***
   image.ptr<uchar>(row)[col] ;第row行第col列畫素的指標 ptr point row
   saturate_cast<uchar>(int) 飽和去除 防止超過 0-255
****/
	int cols = (src.cols-1) * src.channels();
	int offsetx = src.channels();
	int rows = src.rows;

	dst = Mat::zeros(src.size(), src.type());

	for (int row = 1; row < (rows - 1); row++) {
		const uchar* previous = src.ptr<uchar>(row - 1);
		const uchar* current = src.ptr<uchar>(row);
		const uchar* next = src.ptr<uchar>(row + 1);
		uchar* output = dst.ptr<uchar>(row);
		for (int col = offsetx; col < cols; col++) {
			output[col] = saturate_cast<uchar>(5 * current[col] - (current[col- offsetx] + current[col+ offsetx] + previous[col] + next[col]));
		}
	}

//使用醃模方式
	double t = getTickCount(); //獲取作業系統開始到現在經過的運算元 用於計時,也可用clock_t代替
	Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);//常見的初始化核函式的方法
	filter2D(src, dst, src.depth(), kernel);
	double timeconsume = (getTickCount() - t) / getTickFrequency();
	printf("time consume %.2f\n", timeconsume);

	namedWindow("output_image", CV_WINDOW_AUTOSIZE);
	imshow("output_image", dst);
	waitKey(0);
	return 0;

}

相關文章