数字图像处理(DIP)作业9 part-2设计一种快速圆检测算法
作者:互联网
数字图像处理(DIP)作业9 part-2设计一种快速圆检测算法
文章目录
要求
代码
运行环境:Ubuntu16.04 LTS + OpenCV 3.0.4 + ROS-kinetic-full
代码语言:c++
过程:转灰度图->模糊处理->自适应全局阈值二值化处理->
边界检测->霍夫圆检测->绘制图像。
#include <stdlib.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include<ctime>
#define pi 3.14159265
using namespace cv;
using namespace std;
//基本全局阈值求最佳二值图像
Mat Global_threshold(Mat in){
Mat out=in.clone();
int sum=0;
for (int i=0; i<in.rows; i++){
for (int j=0; j<in.cols; j++){
sum+=in.at<uchar>(i,j);
}
}
int t=int(sum/in.cols/in.rows);
int u1=0;int u2=255;
while((u1+u2)/2-t<=5){
int sum1=0,sum2=0;
for (int i=0; i<in.rows; i++){
for (int j=0; j<in.cols; j++){
if(in.at<uchar>(i,j)<t){
sum1+=in.at<uchar>(i,j);
}else{
sum2+=in.at<uchar>(i,j);
}
}
}
u1=int(sum1/in.cols/in.rows);
u2=int(sum2/in.cols/in.rows);
t=int((u1+u2)/2);
}
threshold(in, out, t, 255, CV_THRESH_BINARY);
return out;
}
Mat Fast_circle_detect(Mat in){
Mat out=in.clone();
// imshow("original image",in);
//转灰度图像
Mat gray;
cvtColor(in, gray, COLOR_BGR2GRAY);
//模糊处理
Mat gaussian;
GaussianBlur(gray, gaussian, Size(7,7), 0, 0);
//自适应全局阈值二值化处理
Mat binary=Global_threshold(gaussian);
// imshow("binary",binary);
//边缘检测(canny)
Mat canny;
Canny(gaussian, canny, 100,180);//200,300
// imshow("canny",canny);
vector <Vec3f> circles;
HoughCircles(canny, circles, HOUGH_GRADIENT, 1, canny.rows/17, 100, 20, 0, 45);
for (int i = 0; i < circles.size(); i++) {
circle(out, Point(circles[i][0], circles[i][1]), circles[i][2], Scalar(0, 0, 255), 2);
}
// imshow("circles_detect",out);
return out;
}
int main(int argc, char **argv)
{
clock_t start,end;
double endtime;
Mat src,out;
start=clock();
src=imread("./src/hw_pkg_9/src/3.jpg");
imshow("original_image_1",src);
out=Fast_circle_detect(src);
imshow("out_1",out);
end=clock();
endtime=(double)(end-start)/CLOCKS_PER_SEC;
cout<<"Total_time_1:"<<endtime<<"s"<<endl;
start=clock();
src=imread("./src/hw_pkg_9/src/4.png");
imshow("original_image_2",src);
out=Fast_circle_detect(src);
imshow("out_2",out);
end=clock();
endtime=(double)(end-start)/CLOCKS_PER_SEC;
cout<<"Total_time_2:"<<endtime<<"s"<<endl;
start=clock();
src=imread("./src/hw_pkg_9/src/4.jpg");
imshow("original_image_3",src);
out=Fast_circle_detect(src);
imshow("out_3",out);
end=clock();
endtime=(double)(end-start)/CLOCKS_PER_SEC;
cout<<"Total_time_3:"<<endtime<<"s"<<endl;
waitKey(0);
return 0;
}
结果
处理三张图片总用时不到0.3s,且开始运行后处理速度越来越快。且精度较高,识别准确。
标签:circles,src,Mat,int,数字图像处理,part,canny,DIP,out 来源: https://blog.csdn.net/qq_46164507/article/details/122502641