要在Linux中查找摄像头列表及其支持的可用分辨率,您可以使用V4L2(Video for Linux 2)API。以下是一个示例代码,它不仅列出可用的视频设备,还显示每个设备支持的分辨率。
C++ 示例代码
#include <iostream>
#include <string>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <unistd.h>
void listVideoDevices() {
const std::string devicePrefix = "/dev/video";
for (int i = 0; i < 10; ++i) { // 假设最多有10个视频设备
std::string devicePath = devicePrefix + std::to_string(i);
int fd = open(devicePath.c_str(), O_RDONLY);
if (fd == -1) {
continue; // 如果设备不存在,则继续
}
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0) {
std::cout << "Device: " << devicePath << "\n";
std::cout << " Driver: " << cap.driver << "\n";
std::cout << " Card: " << cap.card << "\n";
std::cout << " Bus info: " << cap.bus_info << "\n";
std::cout << " Version: "
<< ((cap.version >> 16) & 0xFF) << "."
<< ((cap.version >> 8) & 0xFF) << "."
<< (cap.version & 0xFF) << "\n";
// 查询格式支持情况
struct v4l2_fmtdesc fmtDesc;
fmtDesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
std::cout << "Supported formats:\n";
while (ioctl(fd, VIDIOC_ENUM_FMT, &fmtDesc) == 0) {
std::cout << " - Format: "
<< fmtDesc.description
<< " ("
<< fmtDesc.pixelformat
<< ")"
<< "\n";
// 查询该格式下的可用分辨率
struct v4l2_frmsizeenum frmSizeEnum;
frmSizeEnum.pixel_format = fmtDesc.pixelformat;
while (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmSizeEnum) == 0) {
if (frmSizeEnum.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
std::cout << " Discrete size: "
<< frmSizeEnum.discrete.width
<< "x"
<< frmSizeEnum.discrete.height
<< "\n";
} else if (frmSizeEnum.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
std::cout<< " Stepwise sizes from "
<< frmSizeEnum.stepwise.min_width
<<"x"
<< frmSizeEnum.stepwise.min_height
<<" to "
<<"Max Size:"
<<"Width:"
/* Add more information about stepwise format here */
;
}
++frmSizeEnum.index;
}
++fmtDesc.index;
}
} else {
std::cerr<< "[ERROR] Failed to query capabilities for "<< devicePath<<"\n";
}
close(fd);
}
}
int main() {
listVideoDevices();
return 0;
}
编译与运行
- 保存代码到
list_video_devices.cpp
文件中。 - 编译:
g++ list_video_devices.cpp -o list_video_devices
- 运行:
./list_video_devices
注意事项
- 确保您的系统安装了必要的开发工具和库,通常需要安装
libv4l-dev
包:sudo apt-get install libv4l-dev
- 权限问题:访问
/dev/video*
的权限可能需要使用sudo
。 - 此示例假设最多有10个视频设备,如果你的系统上有更多设备,请调整循环的范围。
内容由零声教学AI助手提供,问题来源于学员提问