矩形ROI截圖,實時顯示滑鼠的座標值,顯示原圖與截圖C++程式
阿新 • • 發佈:2019-01-02
//main.cpp檔案 #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdio.h> using namespace cv; cv::Mat org, dst, img, tmp; void on_mouse(int event, int x, int y, int flags, void *ustc)//event滑鼠事件代號,x,y滑鼠座標,flags拖拽和鍵盤操作的代號 { static Point pre_pt = (-1, -1);//初始座標 static Point cur_pt = (-1, -1);//實時座標 Point cirpoint = (-1, -1);//圓心座標 int r = 0; char temp[16]; if (event == CV_EVENT_LBUTTONDOWN)//左鍵按下,讀取初始座標,並在影象上該點處劃圓 { org.copyTo(img);//將原始圖片複製到img中 sprintf(temp, "(%d,%d)", x, y); pre_pt = Point(x, y); putText(img, temp, pre_pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0, 255), 1, 8);//在視窗上顯示座標 circle(img, pre_pt, 2, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);//劃圓 imshow("img", img); } else if (event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))//左鍵沒有按下的情況下滑鼠移動的處理函式 { img.copyTo(tmp);//將img複製到臨時影象tmp上,用於顯示實時座標 sprintf(temp, "(%d,%d)", x, y); cur_pt = Point(x, y); putText(tmp, temp, cur_pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0, 255));//只是實時顯示滑鼠移動的座標 imshow("img", tmp); } else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))//左鍵按下時,滑鼠移動,則在影象上劃矩形 { img.copyTo(tmp); sprintf(temp, "(%d,%d)", x, y); cur_pt = Point(x, y); putText(tmp, temp, cur_pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0, 255)); rectangle(tmp, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);//在臨時影象上實時顯示滑鼠拖動時形成的矩形 imshow("img", tmp); } else if (event == CV_EVENT_LBUTTONUP)//左鍵鬆開,將在影象上劃矩形 { org.copyTo(img); sprintf(temp, "(%d,%d)", x, y); cur_pt = Point(x, y); putText(img, temp, cur_pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0, 255)); //circle(img, pre_pt, 2, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0); //rectangle(img, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);//根據初始點和結束點,將矩形畫到img上 cirpoint.x = (pre_pt.x + cur_pt.x) / 2; cirpoint.y = (pre_pt.y + cur_pt.y) / 2; r = min(abs(pre_pt.x - cur_pt.x), abs(pre_pt.y - cur_pt.y)); r = r / 2.0; circle(img, cirpoint, r, Scalar(0, 0, 225, 0), 1, 8, 0);//繪製第一個圓,半徑為100,圓心(350,300),線寬為7 imshow("img", img); img.copyTo(tmp); //擷取矩形包圍的影象,並儲存到dst中 int width = abs(pre_pt.x - cur_pt.x); int height = abs(pre_pt.y - cur_pt.y); if (width == 0 || height == 0) { printf("width == 0 || height == 0"); return; } dst = org(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height)); namedWindow("dst"); imshow("dst", dst); waitKey(0); } } void main() { org = imread("1.jpg"); org.copyTo(img); org.copyTo(tmp); namedWindow("img");//定義一個img視窗 setMouseCallback("img", on_mouse, 0);//呼叫回撥函式 imshow("img", img); cv::waitKey(0); }