OpenCV入門:Hough霍夫變換-圓形選擇(HoughCircles)
阿新 • • 發佈:2018-12-25
霍夫變換:圓形選擇
#include <iostream> #include <fstream> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <math.h> using namespace cv; using namespace std; int main() { Mat src, gray; src = imread("C:/Users/defaultuser0.DESKTOP-RNJTL1M/Desktop/OpenCV_Distinguish/DistinguishImages/11.jpg"); if (!src.data) return -1; cvtColor(src, gray, CV_BGR2GRAY); Mat contours; Canny(gray, contours, 125, 350); threshold(contours, contours, 128, 255, THRESH_BINARY); //高斯模糊平滑 //GaussianBlur(gray, gray, Size(9, 9), 2, 2); imshow("contours", contours); vector<Vec3f> circles; //霍夫變換 /* HoughCircles函式的原型為: void HoughCircles(InputArray image,OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0,int maxRadius=0 ) image為輸入影象,要求是灰度影象 circles為輸出圓向量,每個向量包括三個浮點型的元素——圓心橫座標,圓心縱座標和圓半徑 method為使用霍夫變換圓檢測的演算法,Opencv2.4.9只實現了2-1霍夫變換,它的引數是CV_HOUGH_GRADIENT dp為第一階段所使用的霍夫空間的解析度,dp=1時表示霍夫空間與輸入影象空間的大小一致,dp=2時霍夫空間是輸入影象空間的一半,以此類推 minDist為圓心之間的最小距離,如果檢測到的兩個圓心之間距離小於該值,則認為它們是同一個圓心 param1、param2為閾值 minRadius和maxRadius為所檢測到的圓半徑的最小值和最大值 */ HoughCircles(contours, circles, CV_HOUGH_GRADIENT, 1, contours.rows / 5, 150, 70, 0, 0); //在原圖中畫出圓心和圓 for (size_t i = 0; i < circles.size(); i++) { //提取出圓心座標 Point center(round(circles[i][0]), round(circles[i][1])); //提取出圓半徑 int radius = round(circles[i][2]); //圓心 circle(src, center, 3, Scalar(0, 255, 0), -1, 4, 0); //圓 circle(src, center, radius, Scalar(0, 0, 255), 3, 4, 0); } namedWindow("Circle", CV_WINDOW_AUTOSIZE); imshow("Circle", src); waitKey(0); return 0; }
效果圖: