码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-12-04 10:33:54      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:namespace   poi   open   bsp   思路   gui   out   value   eai   

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();
}

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

标签:namespace   poi   open   bsp   思路   gui   out   value   eai   

原文地址:https://www.cnblogs.com/runningsoybean/p/11981178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!