用ffmpeg创建的视频无法在视频播放中播放

2024-10-02 18:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python创建一个使用ffmpeg的视频。下面的代码就是我使用的。。。在

import subprocess as sp
import Image
FFMPEG_BIN = "ffmpeg"

commandWriter = [ FFMPEG_BIN,
              '-y',
              '-f', 'image2pipe',
              '-vcodec','mjpeg',
              '-s', '480x360', # size of one frame
              '-pix_fmt', 'rgb24',
              '-r', '29', # frames per second
              '-i', '-',
              '-an', # Tells FFMPEG not to expect any audio
              '-vcodec', 'mpeg4',
              '-qscale', '5',
              '-r', '29',
              '-b', '250',
              './fire.mp4' ]

pipeWriter = sp.Popen(commandWriter, stdin=sp.PIPE)

fps, duration = 24, 10
for i in range(fps*duration):
   im = Image.new("RGB",(480,360),(i%250,1,1))
   im.save(pipeWriter.stdin, "JPEG")
pipeWriter.stdin.close()
pipeWriter.wait()

pipeWriter.terminate()

运行上述代码后,我得到了一个数据速率为214kbps的输出视频。此视频无法在Windows Media Player中播放。一开始我不知道如何让视频播放,所以我把它与我下载的另一个视频进行了比较。我注意到唯一真正的区别是比特率/数据速率。我从命令行运行这个命令。。。在

^{pr2}$

据我所知火.mp4只需输出一个新的视频和修改的比特率。当我在Windows Media Player中打开它时,这个新的输出可以工作。在

我要问的问题是如何直接从Python中实现这一点?我曾尝试向commandWriter添加-b选项(如图所示),但这不起作用。我还在pipeWriter中添加了bufsize=10**8,但这也不起作用。在

总的来说,我要做的就是拍一段视频输入.mp4,在加载到内存中时修改每个帧,然后将该帧写入新文件输出.mp4. 到目前为止,ffmpeg看起来是最好的工具,因为我根本无法让OpenCV工作。在

所以如果有人有办法水.mp4输出文件能够在Windows Media Player中运行,而不需要运行额外的命令行代码或更好的方法来完成我的全部任务,我将非常感谢。在


Tags: 代码imageimport视频binwindowsstdinmedia
1条回答
网友
1楼 · 发布于 2024-10-02 18:27:24

如果你的问题是如何得到一个播放的视频,正如你的标题所示,那么我发现删除一些多余的参数效果很好。以下代码(出于个人喜好和可读性的考虑,此处有其他更改):

import subprocess
from PIL import Image

FFMPEG_BIN = "ffmpeg"    
movie_duration_seconds = 2
movie_fps = 24

ffmpeg_command = [ FFMPEG_BIN,
              '-y',
              '-f', 'image2pipe',
              '-vcodec','mjpeg',
              '-s', '480x360', # size of one frame
              '-i', 'pipe:0', # take input from stdin
              '-an', # Tells FFMPEG not to expect any audio
              '-r', str(movie_fps),
              #'-pix_fmt', 'yuvj420p',  # works fine without this
              #'-vcodec', 'mpeg4',  # not sure why this is needed
              #'-qscale', '5',  # works fine without this
              #'-b', '250',  # not sure why this is needed
              './fire.mp4' ]

ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE)

for i in range(movie_fps * movie_duration_seconds):
   # each image is a shade of red calculated as a function of time
   im = Image.new("RGB",(480,360),(i%255,1,1))
   im.save(ffmpeg_process.stdin, "JPEG")
   ffmpeg_process.stdin.flush()
ffmpeg_process.stdin.close()
#ffmpeg_process.wait()
#ffmpeg_process.terminate()
ffmpeg_process.communicate()  # not sure if is better than wait but
                              # terminate seems not required in any case.

然而,我认为问题的关键在于指定比特率。我不知道修改python时出现了什么错误,但将此添加到args中对我来说效果很好:

^{pr2}$

相关问题 更多 >