| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- #include "../pch/pch.h"
- #include "CVideoCaptureWorker.h"
- #include "../tool/CAppEnv.h"
- CVideoCaptureWorker::CVideoCaptureWorker()
- {
- }
- CVideoCaptureWorker::~CVideoCaptureWorker()
- {
-
- }
- //开始工作
- void CVideoCaptureWorker::Start()
- {
- m_is_work = true;
- //持续获取摄像头数据,直到程序退出,这里开启一个线程来处理摄像头数据的获取,避免阻塞主线程
- std::thread(&CVideoCaptureWorker::HandleVideoCapture, this).detach();
- }
- //停止工作
- void CVideoCaptureWorker::Stop()
- {
- m_is_work = false;
- }
- // 新增:自动检测可用摄像头索引
- int CVideoCaptureWorker::findAvailableCamera()
- {
- for (int i = 0; i < 10; i++)
- {
- // 检测前10个索引
- cv::VideoCapture tempCap(i, cv::CAP_DSHOW);
- if (tempCap.isOpened())
- {
- tempCap.release();
- return i;
- }
- }
- return -1;
- }
- void CVideoCaptureWorker::HandleVideoCapture()
- {
- int cameraIndex = findAvailableCamera();
- if (cameraIndex == -1)
- {
- DEBUG_LOG("未找到任何可用摄像头!");
- return;
- }
- cv::VideoCapture cap(cameraIndex, cv::CAP_DSHOW);
- if (!cap.isOpened())
- {
- CSystem::my_sleep(1);
- DEBUG_LOG("打开摄像头失败,正在重试...");
-
- return;
- }
- DEBUG_LOG("摄像头打开成功!");
- /*
- 160×120(QQVGA):适用于低带宽或嵌入式场景,资源占用极低
- 320×240(QVGA):轻量级视频传输常用,适合实时性要求高的应用
- 640×480(VGA):OpenCV 默认常用分辨率,兼容性强,广泛用于基础图像处理
- 800×600(SVGA):中等清晰度,适用于需要细节但不追求高清的场景
- 1024×768(XGA):较高清分辨率,适合文档扫描或静态图像采集
- 1280×720(720p HD):标准高清分辨率,广泛用于人脸识别、目标检测等视觉任务
- 1920×1080(1080p Full HD):全高清分辨率,提供高质量图像,适用于高精度视觉分析
- */
- int width = 800;
- int height = 600;
- cap.set(cv::CAP_PROP_FRAME_WIDTH, width);
- cap.set(cv::CAP_PROP_FRAME_HEIGHT, height);
- // 验证设置是否成功
- double actualWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH);
- double actualHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
- std::cout << "设置的分辨率: " << width << " x " << height << std::endl;
- std::cout << "实际分辨率: " << actualWidth << " x " << actualHeight << std::endl;
- while (m_is_work == true)
- {
- // 读取摄像头帧
- cap >> m_frame;
- if (m_frame.empty())
- {
- DEBUG_LOG("读取摄像头帧失败,正在重试...");
- CSystem::my_sleep(1);
- continue;
- }
- // 控制帧率,避免占用过多CPU资源,这里设置为30帧每秒
- Sleep(1000 / 30);
- //什么都不用做,只需要把摄像头读取的帧放在成员变量里就行,后续其他地方需要用到摄像头数据的时候直接从成员变量里取就行了
- // 显示摄像头帧(可选)
- //cv::imshow("Camera", m_frame);
- //if (cv::waitKey(30) >= 0) break; // 按任意键退出
- }
- // 程序走到这里,说明收银系统被退出了,这里不释放资源也无所谓了,释放资源太慢了要卡住几百毫秒
- //cap.release();
- //cv::destroyAllWindows();
- //走到这里说明线程要退出了,做一些清理工作
- CAppEnv::GetInstance()->DelWorkerNum();
- return;
- }
- void CVideoCaptureWorker::GetFrame(cv::Mat& frame)
- {
- frame = m_frame.clone();
- }
|