1. 程式人生 > >OpenCV3之——影象修補inpaint()函式

OpenCV3之——影象修補inpaint()函式

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

#define WINDOW_NAME1 "原始圖"
#define WINDOW_NAME2 "修補後的效果圖"

Mat srcImage1, inpaintMask;
Point previousPoint(-1, -1);//初始座標

static void on_Mouse(int event, int x, int y, int flags, void*);

int main(int argc, char** argv) {
	Mat srcImage = imread("1.jpg", -1);
	if (!srcImage.data) {
		cout << "讀入圖片錯誤\n" << endl;
		return false;
	}
	srcImage1 = srcImage.clone();
	inpaintMask = Mat::zeros(srcImage1.size(), CV_8U);

	imshow(WINDOW_NAME1, srcImage1);

	//設定滑鼠回撥訊息
	setMouseCallback(WINDOW_NAME1, on_Mouse, 0);

	//輪詢按鍵
	while (1) {
		//獲取按鍵
		char c = (char)waitKey();

		if (c == 27)
			break;
		if (c == '2') {
			inpaintMask = Scalar::all(0);
			srcImage.copyTo(srcImage1);
			imshow(WINDOW_NAME1, srcImage1);
		}

		if (c == '1' || c == ' ') {
			Mat inpaintedImage;
			inpaint(srcImage1, inpaintMask, inpaintedImage, 3, INPAINT_TELEA);
			imshow(WINDOW_NAME2, inpaintedImage);
		}
	}
	return 0;
}

static void on_Mouse(int event, int x, int y, int flags, void*) {
	if (event == EVENT_LBUTTONUP || !(flags&EVENT_FLAG_LBUTTON))
		previousPoint = Point(-1, -1);
	else if (event == EVENT_LBUTTONDOWN)
		previousPoint = Point(x, y);
	else if (event == EVENT_MOUSEMOVE && (flags&EVENT_FLAG_LBUTTON)) {
		Point pt(x, y);
		if (previousPoint.x < 0)
			previousPoint = pt;
		line(inpaintMask, previousPoint, pt, Scalar::all(255), 5, 8, 0);
		line(srcImage1, previousPoint, pt, Scalar::all(255), 5, 8, 0);
		previousPoint = pt;
		imshow(WINDOW_NAME1, srcImage1);
	}
}