OpenCV Python绑定:如何从内存中捕获图像 [英] OpenCV Python bindings: How do I capture an image from memory

查看:308
本文介绍了OpenCV Python绑定:如何从内存中捕获图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个以字符串形式存储在内存中的jpeg图像.我想从它们生成视频(以便这些图片成为视频中的帧).

I have multiple jpeg images stored as strings in memory. I want to generate a video from them (so those pictures would be the frames in the video).

我该怎么办?

推荐答案

如果有一个字符串集合,每个字符串分别代表一个图像,则可以将StringIOPIL组合以读取它,而无需将它们保存到文件中.然后,您可以使用numpyPIL图像转换为OpenCV.另外,更新代码以使用新的OpenCV绑定.

If you have a collection of strings that individually represents one image each, you can combine StringIO with PIL to read it without saving them to files. Then you convert from a PIL image to OpenCV by using numpy. Also, update your code to use the new OpenCV bindings.

下面是一个示例,该示例复制了您拥有的内容(假定sys.argv [1]为输出视频文件的名称),您可能需要调整视频编解码器:

Here is an example that duplicates what you have (sys.argv[1] assumed to be the name of the output video file), you might need to adjust the video codec:

import sys
import numpy
import cv
import cv2
from cStringIO import StringIO
from PIL import Image

out_video = cv2.VideoWriter()
fourcc = cv.CV_FOURCC('D', 'I', 'V', 'X')
fps = 30
color = True

size = None
for fname in sys.argv[2:]:
    data = open(fname).read() # Your String

    s = StringIO(data)
    img = Image.open(s)
    if size and img.size != size:
        img = img.resize(size)
    else:
        size = img.size
        out_video.open(sys.argv[1], fourcc, fps, size, color)
    out_video.write(cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR))

这篇关于OpenCV Python绑定:如何从内存中捕获图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆