OpenCV Python bindings: How do I capture an image

2020-06-28 05:09发布

问题:

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).

How can I do that?

回答1:

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.

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))


标签: python opencv