C++实现鼠标选取感兴趣区域,并保存坐标到txt文件

无论在视频检测或追踪的过程中,提取感兴趣区域有助于缩小范围,提升性能。初版实现过程可以使用,但还有很大优化空间,视频可以根据图像形式修改,具体代码如下:

#include
#include
#include
#include
#include

using namespace std;
using namespace cv;
Mat src;
char* window_name="Region of Interest";
bool ldown=false,lup=false;
Point corner1,corner2;
Rect box;

static void mouse_callback(int event, int x, int y,int , void*)
{
    
    if (event==EVENT_LBUTTONDOWN)
    {
        ldown=true;
        corner1.x=x;
        corner1.y=y;
        cout<<"corner1 recorded at"<<corner1<<endl;
    }
  
    if(event==EVENT_LBUTTONUP)
    {
        if(abs(x-corner1.x)>20&& abs(y-corner1.y)>20)
        {
            lup=true;
            corner2.x=x;
            corner2.y=y;
            cout<<"corner2 recorded at"<<corner2<<endl;
        }
        else{
            ldown=false;
            cout<<"Please Select a bigger region!"<<endl;
        }
    }
    if (ldown==true &&lup==true)
    {
        Point pt;
        Point center;
        pt.x=x;
        pt.y=y;
        Mat local_img =src.clone();
        rectangle(local_img,corner1,pt,Scalar(0,0,255));
        imshow(window_name,local_img);
    }

    if (ldown==true &&lup==true)
    {
        Point center;
        //计算感兴趣区域的宽和高
        box.width=abs(corner1.x-corner2.x);
        box.height=abs(corner1.y-corner2.y);
        box.x=min(corner1.x, corner2.x);
        box.y=min(corner1.y,corner2.y);
        
        //计算感兴趣区域的中心点
        center.x=(corner1.x+corner2.x)/2;
        center.y=(corner1.y+corner2.y)/2;
        
        //定义输出流
        ofstream outtxt_name;
        outtxt_name.open("../123.txt",ios::out | ios::trunc);//打开txt文件
        outtxt_name<<fixed;
        //依次把坐标保存到txt中
        outtxt_name<<center.x;
        outtxt_name<<center.y;
        outtxt_name<<box.width;
        outtxt_name<<box.height;
        outtxt_name.close();
        
        Mat crop(src,box);
        imshow("Crop", crop);
        ldown=false;
        lup=false;
    }
}

int main()
{
    src=imread("../0.jpg");//读取视频文件,注意../是为了推出build文件读取图像
    namedWindow(window_name);//窗口名
    imshow(window_name,src);

    setMouseCallback(window_name,mouse_callback);

    while ((char)waitKey(0)!='q');

    return 0;
}

你可能感兴趣的:(c++,opencv,开发语言)