Here is my code:
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)
Error that i got:
OSError: MoviePy Error: creation of None failed because of the following error:
convert.exe: label expected
@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\tmpaf7s7kpu.png' @ error/convert.c/ConvertImageCommand/3362.
.
.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect
Confirm that you have already installed the ImageMagick. And you should also set the env for "IMAGEMAGICK_BINARY"
I tried setting IMAGEMAGICK_BINARY, but had the same problem. In the end, I had to modify the source code directly and hard-code this value.