1. 程式人生 > >opencv擷取矩形框中的影象

opencv擷取矩形框中的影象

#include <opencv\cv.h>
#include <opencv/highgui.h>
#include <iostream>


using namespace std;
using namespace cv;

Mat org,img,tmp,dst;

Rect rect;

void on_mouse(int event, int x, int y, int flags, void* ustc)
{
    static CvPoint pre_pt = { -1, -1 };
    static CvPoint cur_pt = { -1
, -1 }; char temp[16]; if (event == CV_EVENT_LBUTTONDOWN) { org.copyTo(img); /*cvCopy(org, img);*/ sprintf(temp, "(%d,%d)", x, y); pre_pt = cvPoint(x, y); putText(img, temp, pre_pt, 1,1, Scalar(0, 0, 255),1); circle(img, pre_pt, 3, cvScalar(255
, 0, 0, 0), CV_FILLED, CV_AA, 0); imshow("img", img); img.copyTo(tmp); } else if (event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON)) { tmp.copyTo(img); sprintf(temp, "(%d,%d)", x, y); cur_pt = cvPoint(x, y); putText(img, temp, cur_pt, 1
, 1, Scalar(0, 0, 255), 1); imshow("img", img); } else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON)) { tmp.copyTo(img); sprintf(temp, "(%d,%d)", x, y); cur_pt = cvPoint(x, y); putText(img, temp, cur_pt, 1, 1, Scalar(0, 0, 255), 1); rectangle(img, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, 8, 0); imshow("img", img); } else if (event == CV_EVENT_LBUTTONUP) { tmp.copyTo(img); sprintf(temp, "(%d,%d)", x, y); cur_pt = cvPoint(x, y); putText(img, temp, cur_pt, 1, 1, Scalar(0, 0, 255), 1); circle(img, cur_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0); rectangle(img, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, 8, 0); imshow("img", img); img.copyTo(tmp); int width = abs(pre_pt.x - cur_pt.x); int height = abs(pre_pt.y - cur_pt.y); if (width == 0 || height == 0) return; dst = Mat(cvSize(width, height), org.type()); if (pre_pt.x<cur_pt.x && pre_pt.y<cur_pt.y) { rect = Rect(pre_pt.x, pre_pt.y, width, height); } else if (pre_pt.x>cur_pt.x && pre_pt.y<cur_pt.y) { rect = Rect(cur_pt.x, pre_pt.y, width, height); } else if (pre_pt.x>cur_pt.x && pre_pt.y>cur_pt.y) { rect = Rect(cur_pt.x, cur_pt.y, width, height); } else if (pre_pt.x<cur_pt.x && pre_pt.y>cur_pt.y) { rect = Rect(pre_pt.x, cur_pt.y, width, height); } dst = Mat(img, rect); cvNamedWindow("dst", 1); imshow("dst", dst); waitKey(); } } int main() { org = imread("D:\\Source Code\\grabcut\\Grabcut\\a.jpg"); img = org.clone(); tmp = org.clone(); int a = org.at<Vec3b>(1, 1)[0]; cvNamedWindow("img", 1); cvSetMouseCallback("img", on_mouse, 0); imshow("dst", img); cvWaitKey(0); }