Opencv通過網路攝影機畫框

來源:互聯網
上載者:User

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

//視頻跟蹤中經常需要確定第一幀中的目標位置,本程式利用滑鼠響應函數實現了在視頻的任意位置畫框,並且可以反覆的重新畫框

//代碼主要參考了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;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.