如何使用opencv将一系列图像写入视频? [英] How can I write a series of images into a video using opencv?

查看:815
本文介绍了如何使用opencv将一系列图像写入视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码旨在逐帧循环浏览文件中的现有视频,并在将每个图像帧写入到应该为视频的新文件之前,在每个帧中添加一些文本.此外,我将这些图像添加到循环中(while循环的每个迭代将一个图像写入文件)与在代码末尾一次写入所有图像.

My code is meant to loop through an existing video on file frame by frame and add some text to each frame before writing each image frame to a new file, that should be a video. Additionally, I am adding these images within the loop(one image written to file per iteration of while loop) VS writing all the images at one time at the end of the code.

最终视频将与输入视频相同,但上面带有一些文本.照原样的代码不会崩溃,但是输出的mp4文件显示,当我在Mac上尝试时,QuickTime无法打开它,并且它似乎无法正确写入.这是我的代码:

The final video will be the same as the input video but with some text on them. The code as is does not crash but the output mp4 file says QuickTime cannot open it when I try on my mac and it does not appear to be writing correctly. Here is my code:

cap = cv2.VideoCapture('me_ballin.mov')

fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter('OUTPUT_PLEASE.mp4', fourcc, 20.0, (640, 640))

while cap.isOpened():
     ret, img = cap.read()
     font                   = cv2.FONT_HERSHEY_SIMPLEX
     bottomLeftCornerOfText = (100,250)
     fontScale              = 2
     fontColor              = (255,255,255)
     lineType               = 2
     photo_text = "BALLINNNN"

     cv2.putText(img, photo_text,
                 bottomLeftCornerOfText,
                 font,
                 fontScale,
                 fontColor,
                 lineType)
     out.write(img)

正如我所说,当我运行代码时,它不会崩溃,但是无法打开输出文件OUTPUT_PLEASE.mp4.有想法吗?

As I said, when I run the code it does not crash but the output file OUTPUT_PLEASE.mp4 cannot be opened. Thoughts?

推荐答案

也许您应该将输出大小"设置为等于输入"的大小.

Maybe you should set Output size equal to size of the Input.

#!/usr/bin/python3
import cv2

## opening videocapture
cap = cv2.VideoCapture(0)

## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

fps = 20
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv2.VideoWriter_fourcc(*'mpeg')

## open and set props
vout = cv2.VideoWriter()
vout.open('output.mp4',fourcc,fps,sz,True)

cnt = 0
while cnt<20:
    cnt += 1
    print(cnt)
    _, frame = cap.read()
    cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
    vout.write(frame)

vout.release()
cap.release()


结果:


The result:

这篇关于如何使用opencv将一系列图像写入视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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