本文共 2711 字,大约阅读时间需要 9 分钟。
在本项目中,首先需要从摄像头读取视频流。通过OpenCV库,可以使用VideoCapture类来实现这一点。在代码中,我们使用了以下命令:
VideoCapture capture(1);
为了获取视频的基本属性(如帧数、宽度、高度等),我们可以使用VideoCapture提供的属性获取方法:
int width = capture.get(CV_CAP_PROP_FRAME_WIDTH);int height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);int frameCount = capture.get(CV_CAP_PROP_FRAME_COUNT);int fps = capture.get(CV_CAP_PROP_FPS);
如果需要将捕获的视频流保存到文件中,可以使用VideoWriter类。以下是基本的写入代码结构:
VideoWriter writer;writer.open("output.avi", CV_FOURCC('D', 'I', 'V', 'X'), fps, Size(width, height)); 使用while循环来持续读取和处理每一帧视频:
while (true) { Mat frame; capture >> frame; // 转换为灰度图像 Mat gray; cvtColor(frame, gray, COLOR_BGR2GRAY); // 应用高斯模糊 GaussianBlur(gray, gray, Size(9, 9), 2, 2); 在这一步骤中,我们使用霍夫圆变换来检测圆形物体。具体实现如下:
vectorcircles;HoughCircles(gray, circles, HOUGH_GRADIENT, 1.5, 10, 200, 100, 0, 0);
循环遍历检测到的圆,并绘制它们的圆心和轮廓:
for (size_t i = 0; i < circles.size(); ++i) { Point center(circles[i][0], circles[i][1]); int radius = circles[i][2]; circle(frame, center, 3, Scalar(0, 255, 0), -1, 8, 0); circle(frame, center, radius, Scalar(155, 50, 255), 3, 8, 0);} 使用imshow函数显示当前帧,并使用waitKey函数控制帧显示时间:
imshow("实时视频", frame);waitKey(10); 当用户按下q键时,程序退出:
if (waitKey(100) & 'q') { break;} #include#include #include using namespace std;using namespace cv;int main() { VideoCapture capture(1); // 获取视频属性 int width = capture.get(CV_CAP_PROP_FRAME_WIDTH); int height = capture.get(CV_CAP_PROP_FRAME_HEIGHT); int frameCount = capture.get(CV_CAP_PROP_FRAME_COUNT); int fps = capture.get(CV_CAP_PROP_FPS); VideoWriter writer; writer.open("output.avi", CV_FOURCC('D', 'I', 'V', 'X'), fps, Size(width, height)); while (true) { Mat frame; capture >> frame; // 转换为灰度图像 Mat gray; cvtColor(frame, gray, COLOR_BGR2GRAY); // 应用高斯模糊 GaussianBlur(gray, gray, Size(9, 9), 2, 2); // 进行霍夫圆变换 vector circles; HoughCircles(gray, circles, HOUGH_GRADIENT, 1.5, 10, 200, 100, 0, 0); // 绘制圆心和轮廓 for (size_t i = 0; i < circles.size(); ++i) { Point center(circles[i][0], circles[i][1]); int radius = circles[i][2]; circle(frame, center, 3, Scalar(0, 255, 0), -1, 8, 0); circle(frame, center, radius, Scalar(155, 50, 255), 3, 8, 0); } // 显示当前帧 imshow("实时视频", frame); if (waitKey(100) & 'q') { break; } } return 0;}
通过以上代码,我们可以实现一个实时检测圆形物体中心的应用程序。该程序利用OpenCV库中的VideoCapture和VideoWriter类来读取和写入视频文件,同时使用HoughCircles函数进行霍夫圆变换,从而快速而准确地检测圆形物体的中心位置。
转载地址:http://dfunz.baihongyu.com/