需要用到一个圆弧检测的程序,苦于网上没有C++版的,自己根据MATLAB函数写了一个,自己感觉没什么问题,编译也可以通过,但结果就是很奇怪,求各位大咖帮忙,新手,小白一个。。。。
void hough_circle(IplImage *BW,double step_r,double step_angle,double r_min,double r_max,double p) { //[m,n] = size(BW); int m=BW->width,n=BW->height; int size_r = (int)((r_max-r_min)/step_r)+1; int size_angle = (int)(2*pi/step_angle); //hough_space = zeros(m,n,size_r); int l=m*n*size_r; int *hough_space=new int [l]; for(int i=0;i<l;i++) hough_space[i]=0; //[rows,cols] = find(BW); typedef struct Str { int row; int col; }Str; int SIZE=BW->height*BW->width; Str *location=new Str [SIZE]; int ecount=0;//计数,统计白点 for (int i = 0; i < BW->height; i++) { for (int j = 0; j < BW->width; j++) { char pixel = *(BW->imageData + i*BW->widthStep+j); if(pixel==255) { location[ecount].row=i; location[ecount].col=j; ecount++; } } } //ecount = size(rows); /*% Hough变换 % 将图像空间(x,y)对应到参数空间(a,b,r) % a = x-r*cos(angle) % b = y-r*sin(angle)*/ /*for i=1:ecount for r=1:size_r for k=1:size_angle a = round(rows(i)-(r_min+(r-1)*step_r)*cos(k*step_angle)); b = round(cols(i)-(r_min+(r-1)*step_r)*sin(k*step_angle)); if(a>0&a<=m&b>0&b<=n) hough_space(a,b,r) = hough_space(a,b,r)+1; end end end end*/ int a=0,b=0; for(int i=0;i<ecount;i++) for(int r=1;r<=size_r;r++) for(int k=1;k<=size_angle;k++) { a = (int)(location[i].row-(r_min+(r-1)*step_r)*cos(k*step_angle)); b = (int)(location[i].col-(r_min+(r-1)*step_r)*sin(k*step_angle)); if((a>0)&(a<=m)&(b>0)&(b<=n)) hough_space[r*m*n+a*m+b]++; } // 搜索超过阈值的聚集点 /*max_para = max(max(max(hough_space))); index = find(hough_space>=max_para*p); length = size(index); hough_circle=zeros(m,n);*/ int max_para=hough_space[0]; for(int i=1;i<l;i++) { max_para=max_para>=hough_space[i]?max_para:hough_space[i]; } int thre=max_para*p; int par1[LEN],par2[LEN],par3[LEN]; for (int j=0;j<LEN;j++) { par1[j]=0,par2[j]=0,par3[j]=0; } int length=0;//超过阈值的点个数 for(int i=1;i<l;i++) if(hough_space[i]>=thre) { par3[length]=i/(m*n)+1; par2[length]=(i%(m*n))/m+1; par1[length]=(i%(m*n))%m+1; length++; } int size_h=m*n; int *hough_circle=new int [size_h]; for (int i=0;i<size_h;i++) hough_circle[i]=0; /*for i=1:ecount for k=1:length par3 = floor(index(k)/(m*n))+1; par2 = floor((index(k)-(par3-1)*(m*n))/m)+1; par1 = index(k)-(par3-1)*(m*n)-(par2-1)*m; if((rows(i)-par1)^2+(cols(i)-par2)^2<(r_min+(par3-1)*step_r)^2+5&... (rows(i)-par1)^2+(cols(i)-par2)^2>(r_min+(par3-1)*step_r)^2-5) hough_circle(rows(i),cols(i)) = 1; end end end*/ //par3是半径,par1和par2是要检测的圆的坐标。 //index(k)在hough_space中的三维位置(par1,par2,par3) for(int i=0;i<ecount;i++) for (int k=0;k<length;k++) if(((location[i].row-par1[k])^2+(location[i].col-par2[k])^2<(r_min+(par3[k]-1)*step_r)^2+5)&((location[i].row-par1[k])^2+(location[i].col-par2[k])^2>(r_min+(par3[k]-1)*step_r)^2-5)) hough_circle[location[i].row*m+location[i].col] = 1; //打印结果 cout<<"圆点坐标 "<<"半径 "<<endl; for (int k=0;k<length;k++) { par3[k] = r_min+(par3[k]-1)*step_r; cout<<par1[k]<<" "<<par2[k]<<" "<<par3[k]<<endl; } }如上,其中注释部分是MATLAB对应代码