我正在使用moviepy导入一些视频,但是应该在纵向模式下导入的视频是横向的。我需要检查旋转是否已更改,如果已更改,请将其旋转回来。
这个功能是内置在moviepy中的吗?如果没有,我还能如何检查它?
我现在已经找到了解决这个问题的办法。
出于某种原因,Moviepy 在导入纵向视频时会将其旋转为横向。为了自动将它们导入回来,您需要找到记录其旋转的视频元数据,然后根据需要旋转视频。我这样做的方法是使用 ffprobe,可以使用这个youtube 教程为 Windows 安装它。请注意,您需要删除 ffmpeg/bin 中的 ffmpeg.exe 文件,因为您只需要 ffprobe.exe。如果你不删除 ffmpeg.exe,moviepy 将使用那个而不是它应该使用的那个。这导致我的系统出现一些奇怪的问题。
安装 ffprobe 后,您可以为正在导入的每个视频运行以下 python 函数:
import subprocess
import shlex
import json
def get_rotation(file_path_with_file_name):
"""
Function to get the rotation of the input video file.
Adapted from gist.github.com/oldo/dc7ee7f28851922cca09/revisions using the ffprobe comamand by Lord Neckbeard from
stackoverflow.com/questions/5287603/how-to-extract-orientation-information-from-videos?noredirect=1&lq=1
Returns a rotation None, 90, 180 or 270
"""
cmd = "ffprobe -loglevel error -select_streams v:0 -show_entries stream_tags=rotate -of default=nw=1:nk=1"
args = shlex.split(cmd)
args.append(file_path_with_file_name)
# run the ffprobe process, decode stdout into utf-8 & convert to JSON
ffprobe_output = subprocess.check_output(args).decode('utf-8')
if len(ffprobe_output) > 0: # Output of cmdis None if it should be 0
ffprobe_output = json.loads(ffprobe_output)
rotation = ffprobe_output
else:
rotation = 0
return rotation
这将调用 ffprobe 命令ffprobe -loglevel error -select_streams v:0 -show_entries stream_tags=rotate -of default=nw=1:nk=1 your_file_name.mp4
,然后返回该文件的轮换元数据。
然后调用调用上述函数的以下函数,并旋转您传递给它的剪辑。请注意,参数clip
是电影 VideoFileClip 对象,参数file_path
是文件的完整路径clip
(例如file_path
,可能是/usr/local/documents/mymovie.mp3
)
from moviepy.editor import *
def rotate_and_resize(clip, file_path):
rotation = get_rotation(file_path)
if rotation == 90: # If video is in portrait
clip = vfx.rotate(clip, -90)
elif rotation == 270: # Moviepy can only cope with 90, -90, and 180 degree turns
clip = vfx.rotate(clip, 90) # Moviepy can only cope with 90, -90, and 180 degree turns
elif rotation == 180:
clip = vfx.rotate(clip, 180)
clip = clip.resize(height=720) # You may want this line, but it is not necessary
return clip