这是我的代码:
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
from moviepy.editor import VideoFileClip, TextClip,
CompositeVideoClip
os.environ["IMAGEMAGICK_BINARY"] = r"C:/Program Files/ImageMagick-7.1.1-Q16-HDRI/magick.exe"
def create_video_with_typewriter_effect(text, output_filename, fontsize=30, video_fps=30):
# Load your video
video = VideoFileClip("D:/video.mp4")
video = video.subclip(0, 2) # Trim the video if needed
# Get video dimensions
video_width = video.w
video_height = video.h
video_size = (video_width, video_height)
# Create a TextClip for the entire text
font = 'Arial-Bold'
text_clip = TextClip(text, fontsize=fontsize, font=font, color='white')
# Calculate the number of frames for the typing effect
num_frames = int(video.duration * video_fps)
# Initialize a list to store each frame
frames = []
# Create individual frames for the typing effect
for frame_idx in range(num_frames):
frame = np.zeros((video_height, video_width, 3), dtype=np.uint8)
frame_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(frame_pil)
current_text = text[:int(len(text) * frame_idx / num_frames)]
text_clip = TextClip(current_text, fontsize=fontsize, font=font, color='white')
text_clip = text_clip.set_duration(1 / video_fps)
text_clip = text_clip.set_position(("center", "center"))
text_clip = text_clip.set_start(frame_idx / video_fps)
frames.append(text_clip.get_frame(frame_idx / video_fps))
# Composite the frames over the video
typewriter_video = CompositeVideoClip([video.set_duration(video.duration), *frames])
# Write the final video to the output file
typewriter_video.write_videofile(output_filename, codec='libx264', fps=video_fps)
text = "Ancient Ruins and Storied History Journey through Sri Lanka's Cultural Triangle"
output_filename = "D:/output_video.mp4"
create_video_with_typewriter_effect(text, output_filename)
我得到的错误: OSError:MoviePy 错误:由于以下错误,创建 None 失败: Convert.exe:预期标签
@C:\Users\hp\AppData\Local\Temp\tmprpxltnkj.txt' @ error/annotate.c/GetMultilineTypeMetrics/804. convert.exe: no images defined
PNG32:C:\Users\hp\AppData\Local\Temp mpaf7s7kpu.png' @ error/convert.c/ConvertImageCommand/3362。
。
此错误可能是由于您的计算机上未安装 ImageMagick,或者(对于 Windows 用户)您没有在文件 conf.py 中指定 ImageMagick 二进制文件的路径,或者您指定的路径不正确
确认您已经安装了ImageMagick。你还应该设置“IMAGEMAGICK_BINARY”的环境