ZBLOG

linux 查找摄像头列表以及可用分辨率 c++代码

在Linux上,您可以使用V4L2(Video for Linux 2)API来查找连接的摄像头列表以及其可用分辨率。以下是一个简单的C++示例代码,展示如何列出所有视频设备及其支持的分辨率。

C++ 示例代码

  1. #include <iostream>
  2. #include <string>
  3. #include <linux/videodev2.h>
  4. #include <fcntl.h>
  5. #include <sys/ioctl.h>
  6. #include <unistd.h>
  7. #include <vector>
  8. void listVideoDevices() {
  9. const std::string devicePrefix = "/dev/video";
  10. for (int i = 0; i < 10; ++i) { // 假设最多有10个视频设备
  11. std::string devicePath = devicePrefix + std::to_string(i);
  12. int fd = open(devicePath.c_str(), O_RDWR | O_NONBLOCK, 0);
  13. if (fd == -1) {
  14. continue; // 如果设备不存在,则继续
  15. }
  16. struct v4l2_capability cap;
  17. if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == -1) {
  18. close(fd);
  19. continue;
  20. }
  21. std::cout << "Device: " << devicePath << "\n";
  22. std::cout << " Driver: " << cap.driver << "\n";
  23. // 列出可用的分辨率
  24. struct v4l2_format fmt;
  25. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  26. for (int width = 320; width <= 1920; width += 320) {
  27. for (int height = 240; height <= 1080; height += 240) {
  28. fmt.fmt.pix.width = width;
  29. fmt.fmt.pix.height = height;
  30. if (ioctl(fd, VIDIOC_S_FMT, &fmt) != -1) {
  31. std::cout << " Supported resolution: "
  32. << width << "x" << height << "\n";
  33. }
  34. }
  35. }
  36. close(fd);
  37. }
  38. }
  39. int main() {
  40. listVideoDevices();
  41. return 0;
  42. }

编译与运行

  1. 保存代码list_video_devices.cpp 文件中。
  2. 编译
    1. g++ list_video_devices.cpp -o list_video_devices -lv4l2
  3. 运行
    1. ./list_video_devices

注意事项

  • 确保你的系统已经安装了V4L2库和开发文件。
  • 权限问题:有时访问 /dev/video* 的权限可能需要使用 sudo
  • 上述代码是简化版本,实际应用中可能需要更复杂的错误处理和条件检查。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=6228

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?