基于opencv进行摄像头精准识别检测追踪小球系统c++代码
时间: 2023-08-01 20:11:13 浏览: 134
opencv 启动摄像头操作 c++
5星 · 资源好评率100%
以下是基于OpenCV进行摄像头精准识别检测追踪小球的C++代码:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "Failed to open camera!" << endl;
return -1;
}
namedWindow("Ball Tracking", WINDOW_AUTOSIZE);
int lowH = 0, lowS = 155, lowV = 0;
int highH = 10, highS = 255, highV = 255;
Mat frame, frame_HSV, frame_threshold;
while (true)
{
bool ret = cap.read(frame);
if (!ret)
{
cout << "Failed to read frame from camera!" << endl;
break;
}
cvtColor(frame, frame_HSV, COLOR_BGR2HSV);
inRange(frame_HSV, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), frame_threshold);
erode(frame_threshold, frame_threshold, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(frame_threshold, frame_threshold, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(frame_threshold, frame_threshold, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(frame_threshold, frame_threshold, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(frame_threshold, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
vector<vector<Point>> contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
Point2f center;
float radius = 0;
for (size_t i = 0; i < contours.size(); i++)
{
approxPolyDP(contours[i], contours_poly[i], 3, true);
boundRect[i] = boundingRect(contours_poly[i]);
minEnclosingCircle(contours_poly[i], center, radius);
}
for (size_t i = 0; i < contours.size(); i++)
{
if (radius > 10)
{
rectangle(frame, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 2, 8, 0);
circle(frame, center, radius, Scalar(0, 0, 255), 2, 8, 0);
}
}
imshow("Ball Tracking", frame);
if (waitKey(30) == 27)
{
cout << "ESC key is pressed by user!" << endl;
break;
}
}
return 0;
}
```
该代码使用了OpenCV的VideoCapture类来读取摄像头的图像,并使用inRange函数进行图像阈值分割,得到二值化图像。然后通过形态学操作(腐蚀和膨胀)对图像进行处理,使得图像中的小球能够更加准确地被检测到。接着使用findContours函数和minEnclosingCircle函数来找到小球的轮廓和最小外接圆。最后将检测到的小球用矩形和圆形标记出来,并在窗口中显示出来。
阅读全文