在Linux上,您可以使用V4L2(Video for Linux 2)API来查找连接的摄像头列表以及其可用分辨率。以下是一个简单的C++示例代码,展示如何列出所有视频设备及其支持的分辨率。
C++ 示例代码
#include <iostream>
#include <string>
#include <linux/videodev2.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <vector>
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_RDWR | O_NONBLOCK, 0);
if (fd == -1) {
continue; // 如果设备不存在,则继续
}
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == -1) {
close(fd);
continue;
}
std::cout << "Device: " << devicePath << "\n";
std::cout << " Driver: " << cap.driver << "\n";
// 列出可用的分辨率
struct v4l2_format fmt;
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
for (int width = 320; width <= 1920; width += 320) {
for (int height = 240; height <= 1080; height += 240) {
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
if (ioctl(fd, VIDIOC_S_FMT, &fmt) != -1) {
std::cout << " Supported resolution: "
<< width << "x" << height << "\n";
}
}
}
close(fd);
}
}
int main() {
listVideoDevices();
return 0;
}
编译与运行
- 保存代码到
list_video_devices.cpp
文件中。 - 编译:
g++ list_video_devices.cpp -o list_video_devices -lv4l2
- 运行:
./list_video_devices
注意事项
- 确保你的系统已经安装了V4L2库和开发文件。
- 权限问题:有时访问
/dev/video*
的权限可能需要使用sudo
。 - 上述代码是简化版本,实际应用中可能需要更复杂的错误处理和条件检查。
内容由零声教学AI助手提供,问题来源于学员提问