简体   繁体   English

如何将数据从v4l2放入C ++向量

[英]How to put data from v4l2 to a c++ vector

I'm currently trying to read video from a MJPEG UVC webcam using C++. 我目前正在尝试使用C ++从MJPEG UVC网络摄像头读取视频。 Using this tutorial , I'm able to retrieve a JPEG image and to save it on disk. 使用本教程 ,我能够检索JPEG图像并将其保存在磁盘上。 Now, I try to use the JPEG image data without writing it on disk ; 现在,我尝试不使用JPEG图像数据而将其写入磁盘; I want to use a C++ vector to store it, but I can't find how to achieve that . 我想使用C ++向量存储它,但是我找不到如何实现的方法。

As far as I understand, the tutorial maps a memory segment that v4l2 uses to store webcam data in memory : 据我了解,该教程映射了v4l2用于将网络摄像头数据存储在内存中的内存段:

struct v4l2_buffer bufferinfo;
memset(&bufferinfo, 0, sizeof(bufferinfo));

bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
bufferinfo.index = 0;

if(ioctl(fd, VIDIOC_QUERYBUF, &bufferinfo) < 0){
    perror("VIDIOC_QUERYBUF");
    exit(1);
}

void* buffer_start = mmap(
    NULL,
    bufferinfo.length,
    PROT_READ | PROT_WRITE,
    MAP_SHARED,
    fd,
    bufferinfo.m.offset
);

This memory segment is populated by v4l2 when we send some command : 当我们发送一些命令时,此内存段由v4l2填充:

if(ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0){
    perror("VIDIOC_QBUF");
    exit(1);
}

// The buffer's waiting in the outgoing queue.
if(ioctl(fd, VIDIOC_DQBUF, &bufferinfo) < 0){
    perror("VIDIOC_QBUF");
    exit(1);
}

To finish, the memory is written to the disk using write function : 最后,使用write函数将内存写入磁盘:

int jpgfile;
if((jpgfile = open("/tmp/myimage.jpeg", O_WRONLY | O_CREAT, 0660)) < 0){
    perror("open");
    exit(1);
}
write(jpgfile, buffer_start, bufferinfo.length);
close(jpgfile);

But how can I copy this memory segment into a vector ? 但是如何将这个内存段复制到向量中呢?

Thank you in advance. 先感谢您。

You can reinterpret the void * as a char * to obtain the raw data: 您可以将void *重新解释为char *以获取原始数据:

char *char_buffer = reinterpret_cast<char *>(buffer_start);

std::vector<char> jpegdata{char_buffer, char_buffer + bufferinfo.length};

(This uses the "iterator pair" overload of the vector constructor.) (这使用了向量构造函数的“迭代器对”重载。)

You might consider using std::string instead: 您可以考虑使用std::string代替:

std::string jpegdata{reinterpret_cast<char *>(buffer_start), bufferinfo.length};

(The std::string approach may wind up being faster; the constructor will likely memcpy() or use some other blitting technique to copy data more efficiently than the iterator-based vector template constructor.) std::string方法可能会变得更快;与基于迭代器的矢量模板构造函数相比,构造函数可能会使用memcpy()或使用其他blitting技术更有效地复制数据。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM