opencv 鼠标操作 裁剪图片

rt, 本程序用调用了opencv裁剪图片, 其实本质上就是鼠标操作。


#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include 
#include 
using namespace cv;
using namespace std;

// global variable
static Mat g_img_src;
static Mat g_img_src_res;
static Mat g_img_dst;
static Mat g_img_sub;


static bool g_is_rect_inited = false;
static Point g_rect_tl;
static string g_window_name = "image";

static int imagenum = 13;

string sourcefolder = "sele" ;
string resfolder = "re";

static void onMouse( int event, int x, int y, int, void* )
{

	if(CV_EVENT_LBUTTONDOWN == event){
		g_is_rect_inited = true;
		g_rect_tl = Point(x, y);    
	}
	else if (CV_EVENT_MOUSEMOVE == event && g_is_rect_inited){      
		g_img_src.copyTo(g_img_dst);
		rectangle(g_img_dst, g_rect_tl, Point(x,y), Scalar_::all(255), 3, 8);
		imshow(g_window_name, g_img_dst);   
	}
	else if (CV_EVENT_LBUTTONUP == event && g_rect_tl.x != x && g_rect_tl.y != y){
		if (x >= g_img_src.cols)
		{
			x = g_img_src.cols-1;
		}
		if (y > g_img_src.rows)
		{
			y = g_img_src.rows-1;
		}
		if (x < 0)
		{
			x = 0;
		}
		if (y < 0)
		{
			y = 0;
		}
		g_img_src(Rect(g_rect_tl, Point(x,y))).copyTo(g_img_sub);
		imshow("sub image", g_img_sub);
		g_is_rect_inited = false;

		char rename[50];
		sprintf(rename, "%s\\%d_sub.jpg", resfolder.c_str(), imagenum);
		imwrite(rename, g_img_sub);

		imagenum += 10;
		char filename[50];
		sprintf(filename, "%s\\%d.jpg", sourcefolder.c_str(), imagenum);
		g_img_src = imread(filename);
		if (g_img_src.empty())
		{
			exit(0);
		}
		resize(g_img_src, g_img_src_res, Size(960, 540));
		g_img_src = g_img_src_res;
		imshow(g_window_name, g_img_dst);
		waitKey(0);
	}
}

int main(int argc, char** argv)
{
	system("mkdir re");

	char filename[50];
	sprintf(filename, "%s\\%d.jpg", sourcefolder.c_str(), imagenum);
	g_img_src = imread(filename);
	resize(g_img_src, g_img_src_res, Size(960, 540));
	g_img_src = g_img_src_res;
	
	if (g_img_src.empty()){
		cerr << "[ERROR] : please check your image file name." << endl;
		return EXIT_FAILURE;
	}

	namedWindow(g_window_name, CV_WINDOW_KEEPRATIO);
	setMouseCallback(g_window_name, onMouse, 0);

	while(true){
		imshow(g_window_name, g_img_src);
		int c = waitKey(0);
		if( (c & 255) == 27 ){ // Esc
			destroyAllWindows();
			cout << "Exiting ...\n";
			break;
		}
	}

	return EXIT_SUCCESS;
}


结果大概是opencv 鼠标操作 裁剪图片_第1张图片


变成了


opencv 鼠标操作 裁剪图片_第2张图片


over。





你可能感兴趣的:(opencv)