<span style="font-family:Microsoft YaHei;font-size:14px;">#include <cmath> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; const int kvalue = 15;//双边滤波邻域大小 int main() { Mat src_color = imread("1.png");//读取原彩色图 imshow("原图-彩色", src_color); //声明一个三通道图像,像素值全为0,用来将霍夫变换检测出的圆画在上面 Mat dst(src_color.size(), src_color.type()); dst = Scalar::all(0); Mat src_gray;//彩色图像转化成灰度图 cvtColor(src_color, src_gray, COLOR_BGR2GRAY); imshow("原图-灰度", src_gray); imwrite("src_gray.png", src_gray); Mat bf;//对灰度图像进行双边滤波 bilateralFilter(src_gray, bf, kvalue, kvalue*2, kvalue/2); imshow("灰度双边滤波处理", bf); imwrite("src_bf.png", bf); vector<Vec3f> circles;//声明一个向量,保存检测出的圆的圆心坐标和半径 HoughCircles(bf, circles, CV_HOUGH_GRADIENT, 1.5, 20, 130, 38, 10, 50);//霍夫变换检测圆 std::vector<int> v;//保存圆心的横坐标减纵坐标的绝对值,用于区分两排灯 cout << "x=\ty=\tr=" << endl; for(size_t i = 0; i < circles.size(); i++)//把霍夫变换检测出的圆画出来 { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); circle( dst, center, 1, Scalar(0, 255, 0), -1, 8, 0 );//画出圆心,颜色为绿色 circle( dst, center, radius, Scalar(0, 0, 255), 1, 8, 0 );//画出圆的轮廓,颜色为红色 v.push_back(abs(center.x-center.y));//存储圆心的横坐标减纵坐标的绝对值,用于区分两排灯 cout << center.x << "\t" << center.y << "\t" << radius << endl;//在控制台输出圆心坐标和半径 } sort(v.begin(), v.end());//从小到大排序 std::vector<Point> points1, points2;//声明点向量,分别存储两排灯的圆心坐标 for (size_t i = 0; i < circles.size(); i++)//用来区分两排灯 { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); if (abs(center.x-center.y) < v[12]) points1.push_back(Point(center.x, center.y));//存储从左上到右下那排灯的圆心坐标 else points2.push_back(Point(center.x, center.y));//存储从左下到右上那排灯的圆心坐标 } cv::Vec4f line1, line2;//拟合直线 fitLine(Mat(points1), line1, CV_DIST_L2, 0, 0.01, 0.01); fitLine(Mat(points2), line2, CV_DIST_L2, 0, 0.01, 0.01); int x01 = (int)line1[2]; int y01 = (int)line1[3]; int x11 = (int)(x01 + 300*line1[0]); int y11 = (int)(y01 + 300*line1[1]); int x21 = (int)(x01 - 300*line1[0]); int y21 = (int)(y01 - 300*line1[1]); int x02 = (int)line2[2]; int y02 = (int)line2[3]; int x12 = (int)(x02 + 300*line2[0]); int y12 = (int)(y02 + 300*line2[1]); int x22 = (int)(x02 - 300*line2[0]); int y22 = (int)(y02 - 300*line2[1]); cv::line(dst, Point(x11, y11), Point(x21, y21), Scalar(255, 255, 255), 1);//画出直线 cv::line(dst, Point(x12, y12), Point(x22, y22), Scalar(255, 255, 255), 1); imshow("特征提取", dst); imwrite("dst.png", dst); waitKey(); }</span>
原图:
效果图:
时间: 2024-12-14 16:09:20