1. 程式人生 > >霍夫變換提取圓心座標,並擬合直線

霍夫變換提取圓心座標,並擬合直線

<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>

原圖:


效果圖: