鱼眼摄像头(一)多平面格式 单缓冲读取图像并显示

news2025/5/13 12:10:00

鱼眼摄像头(一)多平面格式 单缓冲读取图像并显示

1.摄像头格式

1. 单平面格式(Single Plane):各通道数据保存在同一个平面(缓冲),图像数据按行连续存储
	a. mjpeg,yuyv等,适用于轻量级或者简单场景
2. 多平面格式(Multi-plane):图像数据分别保存在多个平面(缓冲)
	a. NV12,Y平面+UV平面
	b. 每个平面都有自己单独的物理内存缓冲区。因此对于ISP,写入DMA等场景来说分通道处理更高效
    c. 代码层面对于多平面数据的采集可以借助v4l2

2.流程图

在这里插入图片描述

3.重要流程详解

  1. 设置格式
    没搞懂为什么nv12反而还是设置一个plane,不是多平面么
bool V4L2MPlaneCamera::initFormat()
{
    struct v4l2_format fmt = {};
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    fmt.fmt.pix_mp.width = width_;
    fmt.fmt.pix_mp.height = height_;
    fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
    fmt.fmt.pix_mp.num_planes = 1;

    return ioctl(fd_, VIDIOC_S_FMT, &fmt) >= 0;
}
  1. 请求缓冲区,获取申请的缓冲区信息,用于后续取数据
    i. 测试可申请一个,但是读写可能会冲突,程序得等待写完再读,读的时候无法写,效率不高
    ii. 实际工作根据场景申请3-6个,流水线采集,更稳定,也可根据需要申请更多6-12
bool V4L2MPlaneCamera::initMMap()
{
    if (!initFormat())
        return false;

    struct v4l2_requestbuffers req = {};
    req.count = 1;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    req.memory = V4L2_MEMORY_MMAP;

    if (ioctl(fd_, VIDIOC_REQBUFS, &req) < 0)
        return false;

    struct v4l2_buffer buf = {};
    struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_MMAP;
    buf.index = 0; // 缓冲区索引
    buf.m.planes = planes;
    buf.length = 1; // 表示 planes 数组中有多少个 plane

    // 向驱动请求第 index 个缓冲区的详细信息,比如大小、偏移位置,实际 plane 的个数等。
    if (ioctl(fd_, VIDIOC_QUERYBUF, &buf) < 0)
        return false;

    buffer_.length = buf.m.planes[0].length; // plane 的实际内存长度
    buffer_.start = mmap(NULL, buf.m.planes[0].length, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, buf.m.planes[0].m.mem_offset);
    return buffer_.start != MAP_FAILED;
}
  1. 启动采集,注意每次采集前必须设置缓冲区队列ioctl(fd_, VIDIOC_QBUF, &buf)
bool V4L2MPlaneCamera::queueBuffer()
{
    struct v4l2_buffer buf = {};
    struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_MMAP;
    buf.index = 0;                     // 缓冲区索引
    buf.length = 1;                    // 本缓冲区包含多少个 plane(平面)。
    buf.m.planes = planes;             // 接收 plane 结果
    planes[0].length = buffer_.length; // plane 的实际内存长度

    return ioctl(fd_, VIDIOC_QBUF, &buf) >= 0;
}

bool V4L2MPlaneCamera::startCapture()
{
    if (!queueBuffer())
        return false;

    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    return ioctl(fd_, VIDIOC_STREAMON, &type) >= 0;
}
  1. 取帧数据,再送入队列
    根据前面获取到的缓冲区数据及mmap信息,直接取出缓冲区数据,转换为opencv格式并显示,最后再将取出的缓冲区放回队列,若不放回,驱动不会再写入数据
bool V4L2MPlaneCamera::readFrame(cv::Mat &bgr)
{
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(fd_, &fds);

    // 等待1s后返回
    struct timeval tv = {1, 0};
    int r = select(fd_ + 1, &fds, NULL, NULL, &tv);
    if (r <= 0)
        return false;

    struct v4l2_buffer buf = {};
    struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_MMAP;
    buf.index = 0;         // 缓冲区索引
    buf.length = 1;        // 本缓冲区包含多少个 plane(平面)。
    buf.m.planes = planes; // 接收 plane 结果

    // 从缓冲队列中取出一帧缓冲区
    if (ioctl(fd_, VIDIOC_DQBUF, &buf) < 0)
        return false;

    cv::Mat yuv(height_ + height_ / 2, width_, CV_8UC1, buffer_.start);
    cv::cvtColor(yuv, bgr, cv::COLOR_YUV2BGR_NV12);

    // 将取出的缓冲区重新放回队列
    if (!queueBuffer())
        return false;

    return true;
}

3.完整代码

#ifndef V4L2MPLANECAMERA_H
#define V4L2MPLANECAMERA_H

#pragma once

#include <linux/videodev2.h>

#include <opencv2/opencv.hpp>
#include <string>
#include <vector>

struct FormatInfo {
  std::string fourcc;
  std::string description;
  std::vector<std::pair<int, int>> resolutions;
};

class V4L2MPlaneCamera {
 public:
  V4L2MPlaneCamera(const std::string &devPath, int width, int height);
  ~V4L2MPlaneCamera();

  std::vector<FormatInfo> listFormats();

  bool openDevice();
  bool initMMap();
  bool startCapture();
  bool stopCapture();
  void closeDevice();
  bool readFrame(cv::Mat &bgr);

 private:
  struct Buffer {
    void *start;
    size_t length;
  };

  std::string devicePath_;
  int width_, height_;
  int fd_ = -1;
  Buffer buffer_;
  int bufferCount_ = 4;
  enum v4l2_buf_type bufferType_ = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;

  bool initFormat();
  bool queueBuffer();
};

#endif
#include "V4L2MPlaneCamera.h"

#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

#include <cstring>
#include <iostream>

static std::string fourccToString(__u32 fmt);

V4L2MPlaneCamera::V4L2MPlaneCamera(const std::string &devPath, int width,
                                   int height)
    : devicePath_(devPath), width_(width), height_(height) {}

V4L2MPlaneCamera::~V4L2MPlaneCamera() {
  stopCapture();
  closeDevice();
}

bool V4L2MPlaneCamera::openDevice() {
  fd_ = ::open(devicePath_.c_str(), O_RDWR | O_NONBLOCK);
  return fd_ >= 0;
}

bool V4L2MPlaneCamera::initFormat() {
  struct v4l2_format fmt = {};
  fmt.type = bufferType_;
  fmt.fmt.pix_mp.width = width_;
  fmt.fmt.pix_mp.height = height_;
  fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
  fmt.fmt.pix_mp.num_planes = 1;  // NV12只有一个plane

  return ioctl(fd_, VIDIOC_S_FMT, &fmt) >= 0;
}

bool V4L2MPlaneCamera::initMMap() {
  if (!initFormat()) return false;

  struct v4l2_requestbuffers req = {};
  req.count = 1;
  req.type = bufferType_;
  req.memory = V4L2_MEMORY_MMAP;

  if (ioctl(fd_, VIDIOC_REQBUFS, &req) < 0) return false;

  struct v4l2_buffer buf = {};
  struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
  buf.type = bufferType_;
  buf.memory = V4L2_MEMORY_MMAP;
  buf.index = 0;  // 缓冲区索引
  buf.m.planes = planes;
  buf.length = 1;  // 表示 planes 数组中有多少个 plane

  // 向驱动请求第 index 个缓冲区的详细信息,比如大小、偏移位置,实际 plane
  // 的个数等。
  if (ioctl(fd_, VIDIOC_QUERYBUF, &buf) < 0) return false;

  buffer_.length = buf.m.planes[0].length;  // plane 的实际内存长度
  buffer_.start = mmap(NULL, buf.m.planes[0].length, PROT_READ | PROT_WRITE,
                       MAP_SHARED, fd_, buf.m.planes[0].m.mem_offset);
  return buffer_.start != MAP_FAILED;
}

bool V4L2MPlaneCamera::queueBuffer() {
  struct v4l2_buffer buf = {};
  struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
  buf.type = bufferType_;
  buf.memory = V4L2_MEMORY_MMAP;
  buf.index = 0;          // 缓冲区索引
  buf.length = 1;         // 本缓冲区包含多少个 plane(平面)。
  buf.m.planes = planes;  // 接收 plane 结果
  planes[0].length = buffer_.length;  // plane 的实际内存长度

  return ioctl(fd_, VIDIOC_QBUF, &buf) >= 0;
}

bool V4L2MPlaneCamera::startCapture() {
  if (!queueBuffer()) return false;

  return ioctl(fd_, VIDIOC_STREAMON, &bufferType_) >= 0;
}

bool V4L2MPlaneCamera::readFrame(cv::Mat &bgr) {
  fd_set fds;
  FD_ZERO(&fds);
  FD_SET(fd_, &fds);

  // 等待1s后返回
  struct timeval tv = {1, 0};
  int r = select(fd_ + 1, &fds, NULL, NULL, &tv);
  if (r <= 0) return false;

  struct v4l2_buffer buf = {};
  struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
  buf.type = bufferType_;
  buf.memory = V4L2_MEMORY_MMAP;
  buf.index = 0;          // 缓冲区索引
  buf.length = 1;         // 本缓冲区包含多少个 plane(平面)。
  buf.m.planes = planes;  // 接收 plane 结果

  // 从缓冲队列中取出一帧缓冲区
  if (ioctl(fd_, VIDIOC_DQBUF, &buf) < 0) return false;

  cv::Mat yuv(height_ + height_ / 2, width_, CV_8UC1, buffer_.start);
  cv::cvtColor(yuv, bgr, cv::COLOR_YUV2BGR_NV12);

  // 将取出的缓冲区重新放回队列
  if (!queueBuffer()) return false;

  return true;
}

bool V4L2MPlaneCamera::stopCapture() {
  return ioctl(fd_, VIDIOC_STREAMOFF, &bufferType_) >= 0;
}

void V4L2MPlaneCamera::closeDevice() {
  if (fd_ >= 0) {
    munmap(buffer_.start, buffer_.length);
    close(fd_);
    fd_ = -1;
  }
}

std::vector<FormatInfo> V4L2MPlaneCamera::listFormats() {
  std::vector<FormatInfo> formats;
  if (fd_ < 0) {
    std::cerr << "[错误] 摄像头设备未打开。" << std::endl;
    return formats;
  }

  struct v4l2_fmtdesc fmtDesc = {};
  fmtDesc.type = bufferType_;

  std::cout << "[信息] 开始枚举支持的图像格式..." << std::endl;

  for (fmtDesc.index = 0; ioctl(fd_, VIDIOC_ENUM_FMT, &fmtDesc) == 0;
       fmtDesc.index++) {
    FormatInfo info;
    info.fourcc = fourccToString(fmtDesc.pixelformat);
    info.description = reinterpret_cast<char *>(fmtDesc.description);

    std::cout << "  - 格式: " << info.fourcc << " (" << info.description << ")"
              << std::endl;

    struct v4l2_frmsizeenum sizeEnum = {};
    sizeEnum.pixel_format = fmtDesc.pixelformat;

    bool hasResolution = false;

    for (sizeEnum.index = 0; ioctl(fd_, VIDIOC_ENUM_FRAMESIZES, &sizeEnum) == 0;
         sizeEnum.index++) {
      switch (sizeEnum.type) {
        case V4L2_FRMSIZE_TYPE_DISCRETE:
          std::cout << "      离散分辨率: " << sizeEnum.discrete.width << "x"
                    << sizeEnum.discrete.height << std::endl;
          info.resolutions.emplace_back(sizeEnum.discrete.width,
                                        sizeEnum.discrete.height);
          hasResolution = true;
          break;

        case V4L2_FRMSIZE_TYPE_CONTINUOUS:
          std::cout << "      连续分辨率范围: " << sizeEnum.stepwise.min_width
                    << "x" << sizeEnum.stepwise.min_height << " 到 "
                    << sizeEnum.stepwise.max_width << "x"
                    << sizeEnum.stepwise.max_height << "(任意值均可)"
                    << std::endl;
          hasResolution = true;
          // 可考虑生成若干预设分辨率加入 info.resolutions
          break;

        case V4L2_FRMSIZE_TYPE_STEPWISE:
          std::cout << "      步进型分辨率: "
                    << "宽度 [" << sizeEnum.stepwise.min_width << "~"
                    << sizeEnum.stepwise.max_width << "] 步长 "
                    << sizeEnum.stepwise.step_width << ",高度 ["
                    << sizeEnum.stepwise.min_height << "~"
                    << sizeEnum.stepwise.max_height << "] 步长 "
                    << sizeEnum.stepwise.step_height << std::endl;
          hasResolution = true;
          // 同上可生成预设 resolution
          break;

        default:
          std::cerr << "      [警告] 未知分辨率类型: " << sizeEnum.type
                    << std::endl;
          break;
      }
    }

    if (!hasResolution) {
      std::cerr << "    [警告] 无可用分辨率" << std::endl;
    }

    formats.push_back(info);
  }

  if (fmtDesc.index == 0) {
    std::cerr << "[警告] 未能枚举到任何图像格式!" << std::endl;
  } else {
    std::cout << "[信息] 完成格式枚举,总共: " << fmtDesc.index << " 种格式"
              << std::endl;
  }

  return formats;
}
static std::string fourccToString(__u32 fmt) {
  char str[5];
  str[0] = fmt & 0xFF;
  str[1] = (fmt >> 8) & 0xFF;
  str[2] = (fmt >> 16) & 0xFF;
  str[3] = (fmt >> 24) & 0xFF;
  str[4] = '\0';
  return std::string(str);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2374643.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

机器学习笔记——特征工程

大家好&#xff0c;这里是好评笔记&#xff0c;公主号&#xff1a;Goodnote&#xff0c;专栏文章私信限时Free。本笔记介绍机器学习中常见的特征工程方法、正则化方法和简要介绍强化学习。 文章目录 特征工程&#xff08;Fzeature Engineering&#xff09;1. 特征提取&#xff…

A Survey of Learning from Rewards:从训练到应用的全面剖析

A Survey of Learning from Rewards&#xff1a;从训练到应用的全面剖析 你知道大语言模型&#xff08;LLMs&#xff09;如何通过奖励学习变得更智能吗&#xff1f;这篇论文将带你深入探索。从克服预训练局限的新范式&#xff0c;到训练、推理各阶段的策略&#xff0c;再到广泛…

Python爬虫第20节-使用 Selenium 爬取小米商城空调商品

目录 前言 一、 本文目标 二、环境准备 2.1 安装依赖 2.2 配置 ChromeDriver 三、小米商城页面结构分析 3.1 商品列表结构 3.2 分页结构 四、Selenium 自动化爬虫实现 4.1 脚本整体结构 4.2 代码实现 五、关键技术详解 5.1 Selenium 启动与配置 5.2 页面等待与异…

Aware和InitializingBean接口以及@Autowired注解失效分析

Aware 接口用于注入一些与容器相关信息&#xff0c;例如&#xff1a; ​ a. BeanNameAware 注入 Bean 的名字 ​ b. BeanFactoryAware 注入 BeanFactory 容器 ​ c. ApplicationContextAware 注入 ApplicationContext 容器 ​ d. EmbeddedValueResolverAware 注入 解析器&a…

Unity3D仿星露谷物语开发41之创建池管理器

1、目标 在PersistentScene中创建池管理器&#xff08;Pool Manager&#xff09;。这将允许一个预制对象池被创建和重用。 在游戏中当鼠标点击地面时&#xff0c;便会启用某一个对象。比如点击地面&#xff0c;就创建了一棵树&#xff0c;而这棵树是从预制体对象池中获取的&a…

Modbus协议介绍

Modbus是一种串行通信协议&#xff0c;由Modicon公司&#xff08;现为施耐德电气&#xff09;在1979年为可编程逻辑控制器&#xff08;PLC&#xff09;通信而开发。它是工业自动化领域最常用的通信协议之一&#xff0c;具有开放性、简单性和跨平台兼容性&#xff0c;广泛应用于…

I/O多路复用(select/poll/epoll)

通过一个进程来维护多个Socket&#xff0c;也就是I/O多路复用&#xff0c;是一种常见的并发编程技术&#xff0c;它允许单个线程或进程同时监视多个输入/输出&#xff08;I/O&#xff09;流&#xff08;例如网络连接、文件描述符&#xff09;。当任何一个I/O流准备好进行读写操…

Westlake-Omni 情感端音频生成式输出模型

简述 github地址在 GitHub - xinchen-ai/Westlake-OmniContribute to xinchen-ai/Westlake-Omni development by creating an account on GitHub.https://github.com/xinchen-ai/Westlake-Omni Westlake-Omni 是由西湖心辰&#xff08;xinchen-ai&#xff09;开发的一个开源…

随手记录5

一些顶级思维&#xff1a; ​ 顶级思维 1、永远不要自卑。 也永远不要感觉自己比别人差&#xff0c;这个人有没有钱&#xff0c;有多少钱&#xff0c;其实跟你都没有关系。有很多人就是那个奴性太强&#xff0c;看到比自己优秀的人&#xff0c;甚至一些装逼的人&#xff0c;这…

Linux驱动:驱动编译流程了解

要求 1、开发板中的linux的zImage必须是自己编译的 2、内核源码树,其实就是一个经过了配置编译之后的内核源码。 3、nfs挂载的rootfs,主机ubuntu中必须搭建一个nfs服务器。 内核源码树 解压 tar -jxvf x210kernel.tar.bz2 编译 make x210ii_qt_defconfigmakeCan’t use ‘…

使用 Flowise 构建基于私有知识库的智能客服 Agent(图文教程)

使用 Flowise 构建基于私有知识库的智能客服 Agent(图文教程) 在构建 AI 客服时,常见的需求是让机器人基于企业自身的知识文档,提供准确可靠的答案。本文将手把手教你如何使用 Flowise + 向量数据库(如 Pinecone),构建一个结合 RAG(Retrieval-Augmented Generation)检…

RabbitMQ ③-Spring使用RabbitMQ

Spring使用RabbitMQ 创建 Spring 项目后&#xff0c;引入依赖&#xff1a; <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp --> <dependency><groupId>org.springframework.boot</groupId><artifac…

linux中常用的命令(四)

目录 1-cat查看文件内容 2-more命令 3-less命令 4-head命令 5-tail命令 1-cat查看文件内容 cat中的一些操作 -b : 列出行号&#xff08;不含空白行&#xff09;-E : 将结尾的断行以 $ 的形式展示出来-n : 列出行号&#xff08;含空白行&#xff09;-T : 将 tab 键 以 ^I 显示…

利用SSRF击穿内网!kali靶机实验

目录 1. 靶场拓扑图 2. 判断SSRF的存在 3. SSRF获取本地信息 3.1. SSRF常用协议 3.2. 使用file协议 4. 172.150.23.1/24探测端口 5. 172.150.23.22 - 代码注入 6. 172.150.23.23 SQL注入 7. 172.150.23.24 命令执行 7.1. 实验步骤 8. 172.150.23.27:6379 Redis未授权…

DVWA在线靶场-xss部分

目录 1. xxs&#xff08;dom&#xff09; 1.1 low 1.2 medium 1.3 high 1.4 impossible 2. xss&#xff08;reflected&#xff09; 反射型 2.1 low 2.2 medium 2.3 high 2.4 impossible 3. xss&#xff08;stored&#xff09;存储型 --留言板 3.1 low 3.2 medium 3.3 high 3.…

Go 语言 slice(切片) 的使用

序言 在许多开发语言中&#xff0c;动态数组是必不可少的一个组成部分。在实际的开发中很少会使用到数组&#xff0c;因为对于数组的大小大多数情况下我们是不能事先就确定好的&#xff0c;所以他不够灵活。动态数组通过提供自动扩容的机制&#xff0c;极大地提升了开发效率。这…

js常用的数组遍历方式

以下是一个完整的示例&#xff0c;将包含图片、文字和数字的数组渲染到 HTML 页面&#xff0c;使用 ​多种遍历方式​ 实现不同的渲染效果&#xff1a; 1. 准备数据&#xff08;数组&#xff09; const items [{ id: 1, name: "苹果", price: 5.99, image: "h…

【网络编程】五、三次握手 四次挥手

文章目录 Ⅰ. 三次握手Ⅱ. 建立连接后的通信Ⅲ. 四次挥手 Ⅰ. 三次握手 ​ 1、首先双方都是处于未通信的状态&#xff0c;也就是关闭状态 CLOSE。 ​ 2、因为服务端是为了服务客户端的&#xff0c;所以它会提前调用 listen() 函数进行对客户端请求的监听。 ​ 3、接着客户端就…

从 AGI 到具身智能体:解构 AI 核心概念与演化路径全景20250509

&#x1f916; 从 AGI 到具身智能体&#xff1a;解构 AI 核心概念与演化路径全景 作者&#xff1a;AI 应用实践者 在过去的几年中&#xff0c;AI 领域飞速发展&#xff0c;从简单的文本生成模型演进为今天具备复杂推理、感知能力的“智能体”系统。本文将从核心概念出发&#x…

Docker Compose 的历史和发展

这张图表展示了Docker Compose从V1到V2的演变过程&#xff0c;并解释了不同版本的Compose文件格式及其支持情况。以下是对图表的详细讲解&#xff1a; Compose V1 No longer supported: Compose V1已经不再支持。Compose file format 3.x: 使用了版本3.x的Compose文件格式。 …