图像剪切
用OpenCV 写一个图像剪切函数 imageCrop() 如下:
1 //图像剪切
2 //参数:src为源图像, dst为结果图像, rect为剪切区域
3 //返回值:返回0表示成功,否则返回错误代码
4 int imageCrop(InputArray src, OutputArray dst, Rect rect)
5 {
6 Mat input = src.getMat();
7 if( input.empty() ) {
8 return -1;
9 }
10
11 //计算剪切区域: 剪切Rect与源图像所在Rect的交集
12 Rect srcRect(0, 0, input.cols, input.rows);
13 rect = rect & srcRect;
14 if ( rect.width <= 0 || rect.height <= 0 ) return -2;
15
16 //创建结果图像
17 dst.create(Size(rect.width, rect.height), src.type());
18 Mat output = dst.getMat();
19 if ( output.empty() ) return -1;
20
21 try {
22 //复制源图像的剪切区域 到结果图像
23 input(rect).copyTo( output );
24 return 0;
25 } catch (...) {
26 return -3;
27 }
28 }
然后,编写测试程序如下:
1 #include <iostream>
2 #include "opencv2/core.hpp"
3 #include "opencv2/imgproc.hpp"
4 #include "opencv2/highgui.hpp"
5
6 using namespace std;
7 using namespace cv;
8
9
10 //图像剪切
11 //参数:src为源图像, dst为结果图像, rect为剪切区域
12 //返回值:返回0表示成功,否则返回错误代码
13 int imageCrop(InputArray src, OutputArray dst, Rect rect)
14 {
15 Mat input = src.getMat();
16 if( input.empty() ) {
17 return -1;
18 }
19
20 //计算剪切区域: 剪切Rect与源图像所在Rect的交集
21 Rect srcRect(0, 0, input.cols, input.rows);
22 rect = rect & srcRect;
23 if ( rect.width <= 0 || rect.height <= 0 ) return -2;
24
25 //创建结果图像
26 dst.create(Size(rect.width, rect.height), src.type());
27 Mat output = dst.getMat();
28 if ( output.empty() ) return -1;
29
30 try {
31 //复制源图像的剪切区域 到结果图像
32 input(rect).copyTo( output );
33 return 0;
34 } catch (...) {
35 return -3;
36 }
37 }
38
39 //======================== 主程序开始 ==========================
40
41 static string window_name = "Draw a Rect to crop";
42 static Mat src; //源图片
43 bool isDrag = false;
44 Point point1; //矩形的第一个点
45 Point point2; //矩形的第二个点
46
47 static void callbackMouseEvent(int mouseEvent, int x, int y, int flags, void* param)
48 {
49 switch(mouseEvent) {
50
51 case CV_EVENT_LBUTTONDOWN:
52 point1 = Point(x,y);
53 point2 = Point(x,y);
54 isDrag = true;
55 break;
56
57 case CV_EVENT_MOUSEMOVE:
58 if ( isDrag ) {
59 point2 = Point(x,y);
60 Mat dst = src.clone();
61 Rect rect (point1, point2); //得到矩形
62 rectangle(dst, rect, Scalar(0,0,255));//画矩形
63 imshow(window_name, dst); //显示图像
64 }
65 break;
66
67 case CV_EVENT_LBUTTONUP:
68 if (isDrag) {
69 isDrag = false;
70 Rect rect (point1, point2); //得到矩形
71 imageCrop(src, src, rect); //图像剪切
72 imshow(window_name, src); //显示图像
73 }
74 break;
75
76 }
77
78 return;
79 }
80
81
82 int main()
83 {
84 //read image file
85 src = imread("building.jpg");
86 if ( !src.data ) {
87 cout << "error read image" << endl;
88 return -1;
89 }
90
91 //create window
92 namedWindow(window_name);
93 imshow(window_name, src);
94
95 //set mouse event call back
96 setMouseCallback(window_name, callbackMouseEvent, NULL );
97
98 waitKey();
99
100 return 0;
101
102 }
运行结果,画一个框后,切下,OK