C++ opencv-基于颜色的圆形目标检测

Python版见https://blog.csdn.net/qq_40870689/article/details/88757081

思路:

1,RGB转HSV,图中只保留红色,https://blog.csdn.net/coldwindha/article/details/82080176

2,通过腐蚀或者膨胀操作,改进将离散的区域的连通性,

3,查找轮廓,寻找最大外轮廓的索引,

4,在原图上绘制圆。

#include <stdio.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int hmin = 170, hmax = 180, smin = 43, smax = 255, vmin = 46, vmax = 255;
int g_nStructElementSize = 3;
int g_nGaussianBlurValue = 6;

int main()
{

Mat img = imread("C:\\TCDProjectFiles\\ColorCycle\\redtest.bmp");
Mat imghsv;
cvtColor(img, imghsv, COLOR_BGR2HSV);//RGB to HSV
imshow("hsv", imghsv);

Mat mask;
inRange(imghsv, Scalar(hmin, smin, vmin), Scalar(hmax, smax, vmax), mask);//filter red color
imshow("mask", mask);

Mat out2;
Mat element = getStructuringElement(MORPH_RECT, Size(2 * g_nStructElementSize + 1, 2 * g_nStructElementSize + 1), Point(g_nStructElementSize, g_nStructElementSize));
erode(mask, out2, element); //erode
imshow("腐蚀", out2);

Mat gaussian;
GaussianBlur(out2, gaussian, Size(g_nGaussianBlurValue * 2 + 1, g_nGaussianBlurValue * 2 + 1), 0, 0);//模糊化
imshow("高斯滤波", gaussian);

vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat imgcontours;
Point2f center;
float radius;


findContours(gaussian, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
double maxarea = 0;
int maxareaidx = 0;
for (int index = contours.size() - 1; index >= 0; index --)// find the maxarea return contour index
{
double tmparea = fabs(contourArea(contours[index]));
if (tmparea > maxarea)
{
maxarea = tmparea;
maxareaidx = index;
}
}
minEnclosingCircle(contours[maxareaidx], center, radius);//using index ssearching the min circle
circle(img, static_cast<Point>(center), (int)radius, Scalar(255,0,0), 3);//using contour index to drawing circle
imshow("轮廓", img);

waitKey();
}

猜你喜欢

转载自www.cnblogs.com/runningsoybean/p/11981178.html