opencv怎样识别图片上带颜色的圆
人气:1识别带颜色的圆,首先需要先查询该颜色的HSV值,下图部分紫色归为红色了:
比如红色:
//红色的HSV值 int low_H = 0,low_S = 123,low_V = 100; int High_H = 5,High_S = 255,High_V = 255;
然后将图片从BGR转化成HSV,接着二值化:
cvtColor(image,src,COLOR_BGR2HSV); //从BGR-> HSV inRange(src,Scalar(low_H,low_S,low_V),Scalar(High_H,High_S,High_V),src); //二值化
如果有噪声可以去噪(这一步可以没有):
GaussianBlur(src,src,Size(5,3 ),2,2);
接着用HoughCircles来找圆,后面的参数可以根据需要自己设置:
HoughCircles(src,circles,CV_HOUGH_GRADIENT,1,50,15,7,10,30); //找圆,最后两个参数是圆半径范围,20是最小圆半径,30是最大圆半径
HoughCircles介绍:
HoughCircles(image,method,dp,minDist [,circles [,param1 [,param2 [,minRadius [,maxRadius]]]]])
完整代码:
#include <iostream> #include <vector> #include <limits> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <string> #include <math.h> #include <iomanip> #include <cstdio> #pragma comment (lib, "opencv_core2413d.lib") #pragma comment (lib, "opencv_highgui2413d.lib") #pragma comment (lib, "opencv_imgproc2413d.lib") #pragma comment (lib, "opencv_video2413d.lib") #pragma comment (lib, "opencv_features2d2413d.lib") using namespace std; using namespace cv; void drawCircle(Mat &input, const vector<Vec3f> &circles); int main(){ Mat image, src;//加载进来的图片 vector<Vec3f> circles;//识别出来的圆,每一行是一个圆,第一列是圆心的x坐标,第二列是圆心的y坐标,第三列是圆的半径 image = imread("D:/code/map3.png"); Mat result = imread("D:/code/map3.png");//结果图 //红色的HSV值 int low_H = 0,low_S = 123,low_V = 100; int High_H = 5,High_S = 255,High_V = 255; cvtColor(image, src, COLOR_BGR2HSV);//从BGR->HSV inRange(src, Scalar(low_H, low_S, low_V), Scalar(High_H, High_S, High_V), src);//二值化 //Reduce the noise so we avoid false circle detection GaussianBlur(src, src, Size(5, 3), 2, 2); HoughCircles(src, circles, CV_HOUGH_GRADIENT, 1, 50, 15, 7,10,30);//找圆,最后两个参数是圆半径范围,20是最小圆半径,30是最大圆半径 drawCircle(result, circles);//画圆 namedWindow("Display window1", WINDOW_NORMAL);//展示结果 namedWindow("Display window2", WINDOW_NORMAL); resizeWindow("Display window1", 1240, 680); resizeWindow("Display window2", 1240, 680); imshow("Display window1", image); imshow("Display window2", result); waitKey(0); return 0; } void drawCircle(Mat &input, const vector<Vec3f> &circles){ for (int i = 0; i<circles.size(); i++){ Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); circle(input, center, radius, Scalar(255, 0, 0), 3, 8, 0); } }
您可能感兴趣的文章:
加载全部内容