《OpenCV视频中截取矩形框》

来源:互联网 发布:淘宝怎么捡漏 编辑:程序博客网 时间:2024/05/22 08:05

分割圆形区域链接地址:《《OpenCV视频中分割圆形区域》》


【一】效果图



【二】源代码

#include<opencv2/opencv.hpp>#include<iostream>using namespace std;using namespace cv;void Draw_rectangle(Point pt1, Point pt2);void on_mouse(int event, int x, int y, int flags, void* ustc);Mat srcImage;Point pre_pt=(0,0), pre_pt_first, pre_pt_first1;//鼠标点Point cur_pt=(0,0), cur_pt_end, cur_pt_end1;int box1_width = 0, box1_height = 0;//画框的宽和高Rect box1;bool flag1 = false;bool flag2 = false;bool flag3 = false;int main(){//VideoCapture capture(0);VideoCapture capture("C:\\Users\\Administrator\\Desktop\\1.avi");capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);while (true){capture >> srcImage;/*if (!capture.isOpened())//判断摄像头是否打开  {cout << "视频加载失败 !" << endl;}*/if (srcImage.empty()){cout << "视频加载失败 !" << endl;return -1;}setMouseCallback("【采集视频】", on_mouse, 0);if (flag3==true){Draw_rectangle(pre_pt_first, cur_pt_end);// 【2】定义一个Mat类型并给其设定ROI区域Mat imageROI = srcImage(Rect(pre_pt_first.x, pre_pt_first.y, box1_width, box1_height));Mat logoImage = imageROI;imshow("【logo】", logoImage);imwrite("logo.jpeg", logoImage);}imshow("【采集视频】", srcImage);waitKey(1);}return 0;}//【画框】void Draw_rectangle(Point pt1, Point pt2){rectangle(srcImage, pt1, pt2, Scalar(0, 255, 0), 2, 8, 0);}//鼠标操作void on_mouse(int event, int x, int y, int flags, void* ustc){char temp_1[20];if (event == CV_EVENT_LBUTTONDOWN)//左键按下{flag1 = true;pre_pt = Point(x, y);pre_pt_first = pre_pt;//sprintf(temp_1,"x:%d,y:%d",x,y);    //putText(src,temp_1,Point(x,y),FONT_HERSHEY_SIMPLEX,0.5,Scalar(255,255,255));  imshow("【采集视频】", srcImage);}else if (event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON))//左键按下并且鼠标移动{if (flag1 == true){flag2 = true;}cur_pt = Point(x, y);sprintf(temp_1, "x:%d,y:%d", x, y);putText(srcImage, temp_1, Point(x, y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 255));Draw_rectangle(pre_pt, cur_pt);imshow("【采集视频】", srcImage);}else if (event == CV_EVENT_LBUTTONUP)//左键弹起{if (flag2 == true){flag3 = true;}cur_pt = Point(x, y);cur_pt_end = cur_pt;//sprintf(temp_1, "x:%d,y:%d", x, y);//putText(srcImage1, temp_1, Point(x, y), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(0, 255, 255));//circle(srcImage1, cur_pt, 3, cvScalar(255, 0, 0), CV_FILLED, CV_AA, 0);Draw_rectangle(pre_pt, cur_pt);imshow("【采集视频】", srcImage);}box1_width = cur_pt.x - pre_pt.x;box1_height = cur_pt.y - pre_pt.y;Rect box1(pre_pt_first.x, pre_pt_first.y, box1_width, box1_height);}