Opencv通过摄像头画框

来源:互联网 发布:99云呼软件 编辑:程序博客网 时间:2024/06/10 19:00

/************************************************************************/

//视频跟踪中经常需要确定第一帧中的目标位置,本程序利用鼠标响应函数实现了在视频的任意位置画框,并且可以反复的重新画框

//代码主要参考了CT跟踪的画框方法
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
using namespace cv;
using namespace std;

Rect box; // tracking object
bool drawing_box = false;
bool gotBB = false; // got tracking box or not
string video;
bool fromfile=false;
// tracking box mouse callback
void mouseHandler(int event, int x, int y, int flags, void *param)
{
 switch (event)
 {
 case CV_EVENT_MOUSEMOVE:
  if (drawing_box)
  {
   box.width = x - box.x;
   box.height = y - box.y;
  }
  break;
 case CV_EVENT_LBUTTONDOWN:
  drawing_box = true;
  box = Rect(x, y, 0, 0);
  break;
 case CV_EVENT_LBUTTONUP:
  drawing_box = false;
  if (box.width < 0)
  {
   box.x += box.width;
   box.width *= -1;
  }
  if( box.height < 0 )
  {
   box.y += box.height;
   box.height *= -1;
  }
  gotBB = true;
  printf("Initial Tracking Box = x:%d y:%d h:%d w:%d\n", box.x, box.y, box.width, box.height);
  break;
 default:
  break;
 }
}

int main(int argc, char * argv[])
{

 VideoCapture capture;
 capture.open(0);;
 // Init camera
 if (!capture.isOpened())
 {
  cout << "capture device failed to open!" << endl;
  return 1;
 }
 // Register mouse callback to draw the tracking box
 namedWindow("Disp", CV_WINDOW_AUTOSIZE);
 setMouseCallback("Disp", mouseHandler, NULL);
 Mat frame;
 Mat first;
 if (fromfile)
 {
  capture >> frame;
  frame.copyTo(first);
 }
 else
 {
  capture.set(CV_CAP_PROP_FRAME_WIDTH, 340);
  capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
 }

 // Initialization
 while(!gotBB)
 {
  if (!fromfile)
  {
   capture >> frame;
  }
  else
  {
   first.copyTo(frame);
  }
  rectangle(frame, box, Scalar(0,0,255));
  imshow("Disp", frame);
  if (cvWaitKey(33) == 'q') { return 0; }
 }
  while(capture.read(frame))
 {
  
  rectangle(frame, box, Scalar(0,0,255));
  // Display
  imshow("Disp", frame);
  if (cvWaitKey(33) == 'q') { break; }
 }
 return 0;
}

 

原创粉丝点击