请用C++版的opencv写一段代码,要求用摄像头识别红蓝色的圆环,并且绘制出准确的圆环轮廓和对应的圆心,可以用键盘按键q切换红蓝模式
时间: 2023-05-30 20:03:53 浏览: 80
opencv c++ 识别物体边缘代码
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
VideoCapture capture(0);
if (!capture.isOpened())
{
cout << "摄像头打开失败!" << endl;
return -1;
}
Mat frame, hsv, mask_red, mask_blue;
while (1)
{
capture.read(frame);
if (frame.empty())
{
cout << "读取视频失败!" << endl;
break;
}
// 将图像转换到HSV色彩空间
cvtColor(frame, hsv, COLOR_BGR2HSV);
// 红色圆环的颜色范围
Scalar lower_red(0, 70, 50);
Scalar upper_red(10, 255, 255);
inRange(hsv, lower_red, upper_red, mask_red);
// 蓝色圆环的颜色范围
Scalar lower_blue(100, 70, 50);
Scalar upper_blue(124, 255, 255);
inRange(hsv, lower_blue, upper_blue, mask_blue);
// 切换红蓝模式
char key = waitKey(1);
if (key == 'q' || key == 'Q')
{
destroyAllWindows();
break;
}
else if (key == 'r' || key == 'R')
{
imshow("Camera", mask_red);
continue;
}
else if (key == 'b' || key == 'B')
{
imshow("Camera", mask_blue);
continue;
}
// 对图像进行形态学操作,去除噪声
Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
morphologyEx(mask_red, mask_red, MORPH_OPEN, kernel);
morphologyEx(mask_blue, mask_blue, MORPH_OPEN, kernel);
// 查找圆形轮廓
vector<vector<Point>> contours_red, contours_blue;
vector<Vec4i> hierarchy_red, hierarchy_blue;
findContours(mask_red, contours_red, hierarchy_red, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
findContours(mask_blue, contours_blue, hierarchy_blue, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 绘制圆形轮廓和圆心
for (size_t i = 0; i < contours_red.size(); i++)
{
double area = contourArea(contours_red[i]);
if (area < 100)
continue;
RotatedRect rect = minAreaRect(contours_red[i]);
Point2f center = rect.center;
circle(frame, center, 4, Scalar(0, 255, 0), -1);
ellipse(frame, rect, Scalar(0, 255, 0), 2);
}
for (size_t i = 0; i < contours_blue.size(); i++)
{
double area = contourArea(contours_blue[i]);
if (area < 100)
continue;
RotatedRect rect = minAreaRect(contours_blue[i]);
Point2f center = rect.center;
circle(frame, center, 4, Scalar(255, 0, 0), -1);
ellipse(frame, rect, Scalar(255, 0, 0), 2);
}
imshow("Camera", frame);
}
capture.release();
return 0;
}
```
阅读全文