OpenCV实现最小外接正矩形

时间:2021-12-15 06:19:57

本文实例为大家分享了OpenCV实现最小外接正矩形的具体代码,供大家参考,具体内容如下

  1. #include "stdafx.h"
  2. #include "cv.h"
  3. #include "highgui.h"
  4. #include "cxcore.h"
  5. #include "math.h"
  6. #include <iostream.h>
  7. int main(int argc, char* argv[])
  8.  
  9. {
  10.  
  11. IplImage *src;
  12. IplImage *dst;
  13. IplImage *ROI;
  14. CvMemStorage* storage=cvCreateMemStorage(0);
  15. CvSeq* contour=0;
  16. src=cvLoadImage("I:\\test.jpg",0);
  17. cvNamedWindow("image0",1);
  18. cvShowImage("image0",src);
  19.  
  20. int hei=src->height;
  21. int wid=src->width;
  22. uchar *data;
  23. data=(uchar*)src->imageData;
  24. int widstep=src->widthStep;
  25. int channel=src->nChannels;
  26. dst=cvCreateImage(cvSize(wid,hei),IPL_DEPTH_8U,3);
  27. ROI=cvCreateImage(cvSize(wid,hei),IPL_DEPTH_8U,3);
  28.  
  29. for (int i=0;i<hei;i++)
  30.  
  31. {
  32.  
  33. for(int j=0;j<wid;j++)
  34.  
  35. {
  36.  
  37. if (data[i*widstep+j*channel]>120)
  38.  
  39. {
  40.  
  41. data[i*widstep+j*channel]=0;
  42.  
  43. }
  44.  
  45. else
  46.  
  47. {
  48.  
  49. data[i*widstep+j*channel]=255;
  50.  
  51. }
  52.  
  53. }
  54.  
  55. }
  56.  
  57. cvNamedWindow("image",0);
  58. cvShowImage("image",src);
  59. printf("图像的高为:%d,宽为:%d\n\n",hei,wid);
  60. cvCvtColor(src, dst, CV_GRAY2BGR);;
  61. cvFindContours(src,storage,&contour,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
  62. for(;contour!=0;contour=contour->h_next)
  63.  
  64. {
  65.  
  66. double length =cvArcLength(contour);
  67. double area =fabs(cvContourArea(contour));
  68. CvRect rect = cvBoundingRect(contour,1);
  69. cout<<"Length="<<length<<" Area="<<area<<endl;
  70. CvPoint p1;
  71. CvPoint p2;
  72. p1.x=rect.x;
  73. p1.y=rect.y;
  74. p2.x=rect.x+rect.width;
  75. p2.y=rect.y+rect.height;
  76. cout<<"p1=("<<p1.x<<","<<p1.y<<")";
  77. cout<<"p2=("<<p2.x<<","<<p2.y<<")"<<endl;
  78. cvRectangle(dst,p1,p2,CV_RGB(255,0,0),1,8,0);
  79.  
  80. }
  81.  
  82. cvNamedWindow("dst",1);
  83. cvShowImage("dst",dst);
  84. cvWaitKey(0);
  85.  
  86. return 0;
  87.  
  88. }

原图:

OpenCV实现最小外接正矩形

二值化反色图:

OpenCV实现最小外接正矩形

最小正矩形图:

OpenCV实现最小外接正矩形

最小正矩形信息:

OpenCV实现最小外接正矩形

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/suimenghuashi/article/details/39032333