我想使用OpenCV和圆形Hough变换(HoughCircles
)来检测圆形对象。在图像中我有3个圆圈,但我只能在设置阈值时检测到一个(或两个)。我想有更强大的代码,可以检测所有3个圆圈,然后我将过滤感兴趣的圆(基本上使用半径)。但首先我如何能够一起检测所有3个圆圈。有帮助吗?这是我的代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace cv;
using namespace std;
int thresh = 100;
int max_thresh = 9000;
Mat src;
void thresh_callback(int, void* );
int main()
{
cv::Mat src = cv::imread("w1.png");
resize(src, src, Size(640,480), 0, 0, INTER_CUBIC);
char* source_window = "Source";
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, src );
createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
thresh_callback( 0, 0 );
waitKey(0);
return(0);
}
void thresh_callback(int, void* ) {
Mat src_gray, gray;
cv::Mat bgr_image = cv::imread( "w1.png");
cv::Mat orig_image = bgr_image.clone();
//blur( bgr_image, src_gray, Size(1,1) );
medianBlur(bgr_image, src_gray,1);
//cv::GaussianBlur(bgr_image, src_gray, cv::Size(1, 1), 1, 1);
cvtColor( src_gray,gray, CV_BGR2GRAY );
Mat canny_output;
Canny( gray, canny_output, thresh, thresh*1, 5,true );
Mat bw,dil,bw1,erd;
dilate(canny_output,dil,Mat());
erode(dil,erd,Mat());
Mat tmp=canny_output.clone();
Size kernalSize (15,15);
Mat element = getStructuringElement (MORPH_RECT, kernalSize, Point(9,9) );
morphologyEx( canny_output, bw1, MORPH_CLOSE, element );
// Use the Hough transform to detect circles in the combined threshold image
std::vector<cv::Vec3f> circles;
cv::HoughCircles(canny_output, circles, CV_HOUGH_GRADIENT, 1, canny_output.rows/1.1, 10, 100, 10, 0);
//cv::HoughCircles(blue_hue_image, circles, CV_HOUGH_GRADIENT, 1, blue_hue_image.rows/1, 10, 100, 10, 0);
// Loop over all detected circles and outline them on the original image
if(circles.size() == 0) std::exit(-1);
for(size_t current_circle = 0; current_circle < circles.size(); ++current_circle) {
Point center(cvRound(circles[current_circle][0]), cvRound(circles[current_circle][1]));
int radius = cvRound(circles[current_circle][2]);
cv::circle(orig_image, center, radius, cv::Scalar(0, 255, 0), 10);
}
// Show images
resize(orig_image, orig_image, Size(640,480), 0, 0, INTER_CUBIC);
char* source_window4 = "Detected window on the input image";
namedWindow( source_window4, CV_WINDOW_AUTOSIZE );
imshow( source_window4, orig_image );
}
这里是输入图像