任务3:鼠标获取任意ROI区域

#include     
#include
#include     
#include      

using namespace cv;

Point prev_pt = Point(-1,-1);  //定义初始坐标。如果将prev_pt写在on_mouse里,画的线会出问题
Mat img, BG_mask, FG_mask;

void on_mouse(int event, int x, int y, int flags, void*)

{

    if (event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON))      //松开鼠标左键或者不是左拖拽  
    {
        prev_pt = Point(-1, -1);
    }
    else if (event == CV_EVENT_LBUTTONDOWN)                                    //按下左键  
    {
        prev_pt = Point(x, y);
    }
    else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))  //移动鼠标并且左拖拽  
    {

        Point pt = Point(x, y);

        //line(BG_mask, prev_pt, pt, Scalar(0), 2, 8, 0);        //背景模板上划线  
        line(FG_mask, prev_pt, pt, Scalar(255), 2, 8, 0);      //前景模板上划线  
        line(img, prev_pt, pt, Scalar::all (255), 2, 8, 0);     //原图上划线   Scalar::all(255)意思就是BGR通道像素值全为255,即Scalar(255,255,255)
        prev_pt = pt;//起点等于终点,说明曲线要比
        imshow("image", img);//画好线后还在原图上显示
    }
    if (event == CV_EVENT_RBUTTONUP)                        //右键UP,截取所选区域  
    {
        Mat BG, FG;    
        //floodFill(BG_mask, Point(x, y), Scalar(0));   //画线闭合区域被黑色填充显示在BG_mask上
        floodFill(FG_mask, Point(x, y), Scalar(255));//画线闭合区域被白色填充显示在FG_mask上
        //imshow("BG_mask", BG_mask);              //显示黑色模板  
        imshow("FG_mask", FG_mask);              //显示白色填充模板
        //img.copyTo(BG, BG_mask);//img中被BG_mask掩盖后的图像附到BG中显示  
        img.copyTo(FG, FG_mask);// img中被FG_mask掩盖后的图像附到FG中显示   
        imshow("FG", FG);
        //imshow("BG", BG);

    }
}

int main()
{
    Mat image = imread("E:\\opencvTest\\11.jpg");
    //初始化前景和背景模板      
    FG_mask = Mat(image.size(), CV_8UC1, Scalar(0));    //FG_mask是背景纯白与img等大小的模板 
    //BG_mask = Mat(image.size(), CV_8UC1, Scalar(255));  //BG_mask是背景纯黑与img等大小的模板 

    image.copyTo(img);//把image附到img图上显示
    imshow("image", img);  //显示原图  

    //鼠标回调函数  
    cvSetMouseCallback("image", on_mouse, 0);

    waitKey(0);
    return 0;
}

你可能感兴趣的:(深度学习入门)