Files
LJ360/test_dir/camera_v4l2.cpp
2025-12-26 10:02:00 +08:00

54 lines
1.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// 使用 V4L2 后端打开摄像头(设备索引 0 对应 /dev/video0
cv::VideoCapture cap(0, cv::CAP_V4L2);
cap.set(cv::CAP_PROP_FRAME_WIDTH, 1920);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, 1080);
cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('Y','U','Y','V'));
// cap.set(cv::CAP_PROP_BUFFERSIZE, 1); // 减少缓冲,降低延迟
if (!cap.isOpened()) {
std::cerr << "❌ 无法打开摄像头 /dev/video0\n";
return -1;
}
// 可选:设置分辨率和格式(根据你的摄像头能力调整)
std::cout << "✅ 摄像头已打开,按 'q' 或 ESC 退出。\n";
cv::Mat frame;
while (true) {
cap >> frame; // 从摄像头读取一帧
if (frame.empty()) {
std::cerr << "⚠️ 读取帧失败,可能摄像头被占用或断开。\n";
break;
}
// 如果是 YUYV 格式2通道转换为 BGR 显示彩色
cv::Mat display_frame;
if (frame.channels() == 2) {
cv::cvtColor(frame, display_frame, cv::COLOR_YUV2BGR_YUYV);
} else {
display_frame = frame; // 假设已经是 BGR
}
// 显示图像
cv::imshow("Camera Feed (V4L2)", display_frame);
// 按 q 或 ESC 退出
int key = cv::waitKey(1) & 0xFF;
if (key == 'q' || key == 27) {
break;
}
}
cap.release();
cv::destroyAllWindows();
std::cout << "👋 已退出。\n";
return 0;
}