1. 程式人生 > >用OpenCV實現Photoshop演算法(二): 影象剪下

用OpenCV實現Photoshop演算法(二): 影象剪下

系列文章:

用OpenCV實現Photoshop演算法(四): 色階調整

二、影象剪下

用OpenCV 寫一個影象剪下函式 imageCrop() 如下:

//影象剪下
//引數:src為源影象, dst為結果影象, rect為剪下區域
//返回值:返回0表示成功,否則返回錯誤程式碼
int imageCrop(InputArray src, OutputArray dst, Rect rect)
{
	Mat input = src.getMat();
	if( input.empty() ) {
		return -1;
	}

	//計算剪下區域:  剪下Rect與源影象所在Rect的交集
	Rect srcRect(0, 0, input.cols, input.rows);
	rect = rect & srcRect;
	if ( rect.width <= 0  || rect.height <= 0 ) return -2;

	//建立結果影象
	dst.create(Size(rect.width, rect.height), src.type());
	Mat output = dst.getMat();
	if ( output.empty() ) return -1;

	try {
		//複製源影象的剪下區域 到結果影象
		input(rect).copyTo( output );
		return 0;
	} catch (...) {
		return -3;
	}
}


然後,編寫測試程式如下:

#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;


//影象剪下
//引數:src為源影象, dst為結果影象, rect為剪下區域
//返回值:返回0表示成功,否則返回錯誤程式碼
int imageCrop(InputArray src, OutputArray dst, Rect rect)
{
	Mat input = src.getMat();
	if( input.empty() ) {
		return -1;
	}

	//計算剪下區域:  剪下Rect與源影象所在Rect的交集
	Rect srcRect(0, 0, input.cols, input.rows);
	rect = rect & srcRect;
	if ( rect.width <= 0  || rect.height <= 0 ) return -2;

	//建立結果影象
	dst.create(Size(rect.width, rect.height), src.type());
	Mat output = dst.getMat();
	if ( output.empty() ) return -1;

	try {
		//複製源影象的剪下區域 到結果影象
		input(rect).copyTo( output );
		return 0;
	} catch (...) {
		return -3;
	}
}

//========================  主程式開始 ==========================

static string window_name = "Draw a Rect to crop";
static Mat src;  //源圖片
bool  isDrag = false;
Point point1; //矩形的第一個點
Point point2; //矩形的第二個點

static void callbackMouseEvent(int mouseEvent, int x, int y, int flags, void* param)
{
	switch(mouseEvent) {

	case CV_EVENT_LBUTTONDOWN:
		point1 = Point(x,y);
		point2 = Point(x,y);
		isDrag = true;
		break;

	case CV_EVENT_MOUSEMOVE:
		if ( isDrag ) {
			point2 = Point(x,y);
			Mat dst = src.clone();
			Rect rect (point1, point2); //得到矩形
			rectangle(dst, rect, Scalar(0,0,255));//畫矩形
			imshow(window_name, dst); //顯示影象
		}
		break;

	case CV_EVENT_LBUTTONUP:
		if (isDrag) {
			isDrag = false;
			Rect rect (point1, point2); //得到矩形
			imageCrop(src, src, rect); //影象剪下
			imshow(window_name, src); //顯示影象
		}
		break;

	}

	return;
}


int main()
{
	//read image file
	src = imread("building.jpg");
	if ( !src.data ) {
		cout << "error read image" << endl;
		return -1;
	}

	//create window
	namedWindow(window_name);
	imshow(window_name, src);

	//set mouse event call back
	setMouseCallback(window_name, callbackMouseEvent, NULL );

	waitKey();

	return 0;

}

執行結果,畫一個框後,切下,OK