要在 Linux 上使用 C++ 查询摄像头的可用分辨率,您可以使用 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 listSupportedResolutions(const std::string& devicePath) {
int fd = open(devicePath.c_str(), O_RDWR);
if (fd == -1) {
std::cerr << "Failed to open device: " << devicePath << "\n";
return;
}
struct v4l2_frmsizeenum frmSizeEnum;
frmSizeEnum.pixel_format = V4L2_PIX_FMT_MJPEG; // Change as needed for specific pixel formats
frmSizeEnum.index = 0;
std::cout << "Supported resolutions for device: " << devicePath << "\n";
while (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmSizeEnum) == 0) {
if (frmSizeEnum.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
std::cout << "Resolution: "
<< 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 "
<< frmSizeEnum.stepwise.max_width
<< "x"
<< frmSizeEnum.stepwise.max_height
<< ", step size: "
<< frmSizeEnum.stepwise.step_width
<< "x"
<< frmSizeEnum.stepwise.step_height
<< "\n";
}
++frmSizeEnum.index;
}
close(fd);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr<< "Usage: "<< argv[0] <<" /dev/videoX\n";
return -1;
}
listSupportedResolutions(argv[1]);
return 0;
}
编译与运行
- 保存代码到
list_camera_resolutions.cpp
文件中。 - 编译:
g++ list_camera_resolutions.cpp -o list_camera_resolutions
- 运行(假设你要查询
/dev/video2
):./list_camera_resolutions /dev/video2
注意事项
- 确保您的系统上安装了必要的开发工具和库,通常需要安装
libv4l-dev
包:sudo apt-get install libv4l-dev
- 您可能需要以
sudo
权限运行程序来访问/dev/video*
。 - 您可以根据需要修改
frmSizeEnum.pixel_format
来指定特定的像素格式,以获取该格式下的分辨率信息。
内容由零声教学AI助手提供,问题来源于学员提问