OpenCV画矩形.txt
上传用户:sales16
上传日期:2022-06-10
资源大小:1k
文件大小:2k
源码类别:

OpenCV

开发平台:

Visual C++

  1. #include "stdafx.h"
  2. #include <cv.h>
  3. #include <highgui.h>
  4. #pragma comment(lib,"cv.lib")
  5. #pragma comment(lib,"cxcore.lib")
  6. #pragma comment(lib,"highgui.lib")
  7.  
  8. CvRect box;
  9. bool Drawing=false;
  10. void my_mouse_callback(int event, int x, int y, int flags, void* param);//实现对窗口Window_Name上的对象param添加鼠标响应操作
  11. void DrawRect(IplImage*img,CvRect rect)
  12. {
  13.     cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0x00,0xff,0x00),2);
  14. }
  15.  int main(int argc,char*argv[])
  16.  {
  17.     box=cvRect(0,0,-1,-1);
  18.     
  19.     IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
  20.     
  21.     cvZero(img);
  22.     IplImage*temp=cvCloneImage(img);
  23. cvNamedWindow("Draw_Rectangle",CV_WINDOW_AUTOSIZE);
  24. cvSetMouseCallback("Draw_Rectangle",my_mouse_callback,(void*)img);//设置鼠标事件回调函数
  25.      while(1)
  26.      {
  27.          cvCopyImage(img,temp);
  28.          if(Drawing)
  29.            DrawRect(temp,box);
  30.          cvShowImage("Draw_Rectangle",temp);
  31.  
  32.          if(cvWaitKey(100)==27)
  33.              break;
  34.      }
  35.     cvReleaseImage(&img);
  36.         cvReleaseImage(&temp);
  37.     cvDestroyWindow("Draw_Rectangle");
  38.     return 0;
  39. }
  40.  void my_mouse_callback(int event,int x,int y,int flags,void*param)
  41.  {
  42.     IplImage*img=(IplImage*)param;
  43.         switch(event)
  44.      {
  45.      case CV_EVENT_MOUSEMOVE:
  46.      {
  47.              if(Drawing)
  48.          {
  49. box.width=x-box.x;
  50. box.height=y-box.y;
  51.          }
  52.   }
  53.       break;
  54.  case CV_EVENT_LBUTTONDOWN:
  55.          {
  56.         Drawing=true;
  57.             box=cvRect(x,y,0,0);
  58.  }
  59.      break;
  60.      case CV_EVENT_LBUTTONUP:
  61.         {
  62.         Drawing=false;
  63.         if (box.width<0)
  64.     {
  65.         box.x+=box.width;
  66.         box.width*=-1;
  67.     }
  68.              if (box.height<0)
  69.      {
  70.         box.y+=box.height;
  71.         box.height*=-1;
  72.      }
  73.          DrawRect(img,box);
  74.     }
  75.      break;
  76.      }
  77.  }