读取图片并检测图片中的圆
记录下第一篇小代码,供日后查阅。读取图片,转灰度图,进行高斯模糊,用opencv自带的函数HoughCircles检测圆,并画出。
代码
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("C:/Users/HZY/Desktop/3.jpg");
Mat frame = src;
if (src.empty())
{
printf("could not load image....\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
waitKey(0);
cvtColor(src,src, COLOR_BGR2GRAY);
imshow("灰度图", src);
waitKey(0);
GaussianBlur(src, src, Size(3, 3), 2, 2);
imshow("高斯模糊后灰度图", src);
waitKey(0);
std::vector<Vec3f> circles;
HoughCircles(src, circles, HOUGH_GRADIENT, 1.5, 10, 200, 70, 0, 0);
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(frame, center, radius, Scalar(155, 50, 255), 3, 8, 0);
int R = frame.at<Vec3b>(cvRound(circles[i][1]), cvRound(circles[i][0]))[2];//R
int G = frame.at<Vec3b>(cvRound(circles[i][1]), cvRound(circles[i][0]))[1];//G
int B = frame.at<Vec3b>(cvRound(circles[i][1]), cvRound(circles[i][0]))[0];//B
std::cout << "圆的半径是" << radius << std::endl;
std::cout << "圆的X是" << circles[i][0] << "圆的Y是" << circles[i][1] << std::endl;
}
imshow("【效果图】", frame);
waitKey(0);
return 0;
}