opencv之求各连通区域内目标的最小外接矩形及其长、宽

更新时间:2023-06-02 15:10:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

这是基于opencv的函数,包含图像二值化,最小外接矩形求法,及最小外接矩阵的长和宽,按照自己思路不一定规范,还望指正。

10、最小外接矩形及长宽的求法 liuqingjie2@ #include "cv.h"

#include "highgui.h"

#include <stdio.h>

#include <math.h>

#include "otsu.h"

int main(int argc,char** argv)

{

IplImage *src,*gray,*bw,*dst;

CvMemStorage* storage=cvCreateMemStorage(0); CvSeq* contour=0;

char* filename=argc==2?argv[1]:"5.jpg";

if(!filename)

printf("can't open the file:%d\n",filename);

src=cvLoadImage(filename,1);

cvNamedWindow("image",1);

cvShowImage("image",src);

gray=cvCreateImage(cvSize(src->width,src->height),src->depth,1); cvCvtColor(src,gray,CV_BGR2GRAY);

hei=gray->height;//注意此处是gray,otsu中要用到hei,wid,已在otsu.h中全局定义;

wid=gray->width;

printf("图像的高为:%d,宽为:%d\n\n",hei,wid);

这是基于opencv的函数,包含图像二值化,最小外接矩形求法,及最小外接矩阵的长和宽,按照自己思路不一定规范,还望指正。

cvNamedWindow("image2",1);

cvShowImage("image2",gray);

bw=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1); otsu(gray,bw);

cvNamedWindow("image4",1);

cvShowImage("image4",bw);

// wb=cvCloneImage(bw);

// cvNot(bw,wb); 只有当目标区域为黑色背景时候,才对其取反。

dst=cvCloneImage(src);

cvFindContours(bw,storage,&contour,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);

for(;contour!=0;contour=contour->h_next)

{ CvBox2D rect=cvMinAreaRect2(contour,storage);

CvPoint2D32f rect_pts0[4];

cvBoxPoints(rect, rect_pts0);

//因为cvPolyLine要求点集的输入类型是CvPoint**

//所以要把 CvPoint2D32f 型的 rect_pts0 转换为 CvPoint 型的 rect_pts

//并赋予一个对应的指针 *pt

int npts = 4,k=0;

int aaa=0,bbb=0;

CvPoint rect_pts[4], *pt = rect_pts;

这是基于opencv的函数,包含图像二值化,最小外接矩形求法,及最小外接矩阵的长和宽,按照自己思路不一定规范,还望指正。

printf("连通区域最小外接矩形顶点坐标分别为:\n");

for (int i=0; i<4; i++)

{

rect_pts[i]= cvPointFrom32f(rect_pts0[i]);

printf("%d %d\n",rect_pts[i].x,rect_pts[i].y);

aaa=(int)sqrt((pow((rect_pts[0].x-rect_pts[1].x),2)+pow((rect_pts[0].y-rect_pts[1].y),2)));

bbb=(int)sqrt((pow((rect_pts[0].x-rect_pts[3].x),2)+pow((rect_pts[0].y-rect_pts[3].y),2)));

if(aaa<bbb)

{

k=aaa;

aaa=bbb;

bbb=k;

}

}

printf("最小外接矩形的长为:%d,宽为:%d。\n\n",aaa,bbb);

//chang=rect_pts[0]-rect_pts[3];

//kuan=rect_pts[0]-rect_pts[1];

//printf("最小外接矩形的长为:%d,宽为:%d\n",chang,kuan);

//画出Box

cvPolyLine(dst, &pt, &npts, 1, 1, CV_RGB(255,0,0), 1);

}

cvNamedWindow("image5",1);

cvShowImage("image5",dst);

这是基于opencv的函数,包含图像二值化,最小外接矩形求法,及最小外接矩阵的长和宽,按照自己思路不一定规范,还望指正。

cvWaitKey(0);//注意此句放的位置,放的不对则。。。

cvDestroyWindow("image");

cvDestroyWindow("image2");

cvDestroyWindow("image4");

cvDestroyWindow("image5");

cvReleaseImage(&src);

cvReleaseImage(&gray);

cvReleaseImage(&bw);

cvReleaseImage(&dst);

return 0;

}

本文来源:https://www.bwwdw.com/article/ek01.html

Top