Matlab:
I=imread('pic.jpg');
figure(1); imshow(I); title('Input Image');
text(6,6,'Left click to get points, right click to get end point','FontSize',[12],'Color', 'r');
[m,xi,yi]=roipoly;
min_xi=min(xi);
max_xi=max(xi);
min_yi=min(yi);
max_yi=max(yi);
roi=I(min_yi:max_yi,min_xi:max_xi);
C++:
按下鼠标左键开始选取区域,按下鼠标右键显示截取的区域:
Mat org, dst, img, tmp;
static Point pre_pt = (-1, -1);
static Point cur_pt = (-1, -1);
void on_mouse(int event, int x, int y, int flags, void *)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
pre_pt = Point(x, y);
}
else if (event == CV_EVENT_MOUSEMOVE && flags)//摁下左键,flags为1
{
org.copyTo(tmp);
cur_pt = Point(x, y);
circle(tmp, cur_pt, 4, Scalar(0, 255, 0, 0), 2, 8);
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);
rectangle(img, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);
imshow("img", img);//画完后显示框
}
if (event == CV_EVENT_RBUTTONUP) //右键UP,截取所选区域
{
if (!dst.empty())
dst = NULL;
int width = abs(pre_pt.x - cur_pt.x);
int height = abs(pre_pt.y - cur_pt.y);
if (width == 0 || height == 0)
{
imshow("img", img);//画完后显示框
}
else
{
dst = org(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height));
namedWindow("dst");
imshow("dst", dst);
}
flags = 0;
}
}
int main()
{
Mat image=imread("pic.jpg");
org = image.clone();
org.copyTo(img);
namedWindow("img");
imshow("img", img);
setMouseCallback("img", on_mouse, 0);
waitKey(0);
}