The error you're encountering:
AttributeError: 'ImageDraw' object has no attribute 'textsize'
indicates that the ImageDraw object in your installed version of Pillow doesn't have the textsize method. This can happen due to:
- Pillow Version Differences: In newer versions of Pillow, some methods like
textsize might be deprecated or replaced.
- Typographical Errors: Ensure there are no typos in the method names.
- Missing Imports: Using classes or methods without importing necessary modules.
Let's address these issues step-by-step to help you resolve the error and improve your script.
1. Replace draw.textsize with font.getsize
In recent versions of Pillow, it's recommended to use font.getsize(text) instead of draw.textsize(text, font=font). Here's how you can update your code:
Original Code Snippet:
text_width, text_height = draw.textsize(text, font=font)
Updated Code Snippet:
text_width, text_height = font.getsize(text)
Explanation:
font.getsize(text) returns a tuple containing the width and height of the given text when rendered with the specified font. This method is preferred in newer Pillow versions.
2. Ensure ImageColor is Imported
Your script uses ImageColor.getrgb(font_color) but doesn't import ImageColor. This can lead to a NameError.
Original Code Snippet:
from PIL import Image, ImageDraw, ImageFont
Updated Code Snippet:
from PIL import Image, ImageDraw, ImageFont, ImageColor
3. Fix the Zoom In Animation Block
In the generate_text_animation_frames function, the Zoom In block references scene, which isn't defined within the function's scope. This will lead to a NameError.
Original Zoom In Block:
elif animation_type == "Zoom In":
# Start with smaller text size and increase to final size
initial_size = max(int(font.size * 0.5), 10)
for i in range(TEXT_ANIMATION_FRAMES):
temp_font_size = initial_size + int((font.size - initial_size) * (i + 1) / TEXT_ANIMATION_FRAMES)
temp_font = ImageFont.truetype(scene.get("font_path", DEFAULT_FONT_PATH), size=temp_font_size)
animated_img = base_img.copy()
add_text(animated_img, text, temp_font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
Updated Zoom In Block:
To fix this, you need to pass the font_path as an additional parameter to the generate_text_animation_frames function or handle it differently. Here's one way to modify it:
-
Update the Function Signature:
def generate_text_animation_frames(base_img, text, font, font_color, animation_type, font_path=DEFAULT_FONT_PATH):
-
Modify the Zoom In Block:
elif animation_type == "Zoom In":
# Start with smaller text size and increase to final size
initial_size = max(int(font.size * 0.5), 10)
for i in range(TEXT_ANIMATION_FRAMES):
temp_font_size = initial_size + int((font.size - initial_size) * (i + 1) / TEXT_ANIMATION_FRAMES)
temp_font = ImageFont.truetype(font_path, size=temp_font_size)
animated_img = base_img.copy()
add_text(animated_img, text, temp_font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
-
Update the Function Call in generate_scene_frames:
# Inside generate_scene_frames function
text_animation_frames = generate_text_animation_frames(
base_img,
text,
font,
font_color,
text_animation,
font_path=scene.get("font_path", DEFAULT_FONT_PATH)
)
Explanation:
- Passing
font_path as a Parameter: This ensures that the Zoom In block has access to font_path without directly referencing scene, which is outside its scope.
4. Complete Corrected generate_text_animation_frames Function
Here's the fully corrected generate_text_animation_frames function incorporating all the fixes:
def generate_text_animation_frames(base_img, text, font, font_color, animation_type, font_path=DEFAULT_FONT_PATH):
"""
Generate frames with text animation effects.
Supported animations: Typing Effect, Fade In, Slide In, Zoom In
"""
frames = []
total_chars = len(text)
chars_per_frame = max(total_chars // TEXT_ANIMATION_FRAMES, 1)
if animation_type == "Typing Effect":
for i in range(TEXT_ANIMATION_FRAMES):
visible_chars = min((i + 1) * chars_per_frame, total_chars)
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color, visible_chars=visible_chars)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
# Ensure the entire text is visible in the last frame
while len(frames) < TEXT_ANIMATION_FRAMES:
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
elif animation_type == "Fade In":
# Start with transparent text and gradually increase opacity
for i in range(TEXT_ANIMATION_FRAMES):
animated_img = base_img.copy()
alpha = (i + 1) / TEXT_ANIMATION_FRAMES
# Create a transparent overlay
overlay = Image.new('RGBA', animated_img.size, (0,0,0,0))
draw = ImageDraw.Draw(overlay)
text_width, text_height = font.getsize(text) # Updated line
position = ((FRAME_WIDTH - text_width) // 2, (FRAME_HEIGHT - text_height) // 2)
# Ensure ImageColor is imported
text_color = ImageColor.getrgb(font_color) + (int(255 * alpha),)
draw.text(position, text, font=font, fill=text_color)
animated_img = Image.alpha_composite(animated_img.convert('RGBA'), overlay)
cv_frame = pil_to_cv2(animated_img.convert('RGB'))
frames.append(cv_frame)
elif animation_type == "Slide In":
# Slide text from left to center
for i in range(TEXT_ANIMATION_FRAMES):
animated_img = base_img.copy()
draw = ImageDraw.Draw(animated_img)
text_width, text_height = font.getsize(text) # Updated line
total_slide = (FRAME_WIDTH // 2 - text_width // 2) + (FRAME_WIDTH // 2)
current_slide = int((FRAME_WIDTH - text_width) * (i + 1) / TEXT_ANIMATION_FRAMES) - text_width
position = (current_slide, (FRAME_HEIGHT - text_height) // 2)
draw.text(position, text, font=font, fill=font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
elif animation_type == "Zoom In":
# Start with smaller text size and increase to final size
initial_size = max(int(font.size * 0.5), 10)
for i in range(TEXT_ANIMATION_FRAMES):
temp_font_size = initial_size + int((font.size - initial_size) * (i + 1) / TEXT_ANIMATION_FRAMES)
temp_font = ImageFont.truetype(font_path, size=temp_font_size)
animated_img = base_img.copy()
add_text(animated_img, text, temp_font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
else:
# Default to Typing Effect if unknown animation
for i in range(TEXT_ANIMATION_FRAMES):
visible_chars = min((i + 1) * chars_per_frame, total_chars)
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color, visible_chars=visible_chars)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
return frames
5. Ensuring Compatibility Across Pillow Versions
To make your script more robust across different Pillow versions, consider implementing a helper function to get text size:
def get_text_size(draw, text, font):
"""
Get the size of the text using the most compatible method based on Pillow version.
"""
if hasattr(draw, "textbbox"):
bbox = draw.textbbox((0, 0), text, font=font)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
elif hasattr(font, "getbbox"):
bbox = font.getbbox(text)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
elif hasattr(font, "getsize"):
width, height = font.getsize(text)
else:
width, height = 0, 0 # Fallback if all methods are unavailable
return width, height
Then, replace all instances of font.getsize(text) or draw.textsize(text, font=font) with get_text_size(draw, text, font).
Example Usage:
text_width, text_height = get_text_size(draw, text, font)
6. Complete Corrected and Improved Script
Here's the revised version of your script incorporating all the fixes and improvements:
# video_generator.py
import json
import os
from PIL import Image, ImageDraw, ImageFont, ImageColor
import cv2
import numpy as np
# Define your paths here
JSON_PATH = 'video_data.json' # Path to your JSON file
OUTPUT_DIR = 'output_videos'
VIDEO_OUTPUT = os.path.join(OUTPUT_DIR, 'final_video.mp4')
DEFAULT_FONT_PATH = '/root/mm/vidtext/opensansvar.ttf' # Ensure this path is correct
# Video specifications
FRAME_WIDTH = 1024
FRAME_HEIGHT = 1024
FPS = 24
VIDEO_CODEC = 'mp4v' # FourCC code for mp4
# Scene timings in seconds
FADE_IN_DURATION = 1
DISPLAY_DURATION = 5
TEXT_ANIMATION_DURATION = 3
FADE_OUT_DURATION = 1
# Calculate number of frames for each segment
FADE_IN_FRAMES = FADE_IN_DURATION * FPS
DISPLAY_FRAMES = DISPLAY_DURATION * FPS
TEXT_ANIMATION_FRAMES = TEXT_ANIMATION_DURATION * FPS
FADE_OUT_FRAMES = FADE_OUT_DURATION * FPS
# Total frames per scene
TOTAL_SCENE_FRAMES = FADE_IN_FRAMES + DISPLAY_FRAMES + TEXT_ANIMATION_FRAMES + FADE_OUT_FRAMES
def load_scenes(json_path):
"""
Load scenes from a JSON file.
"""
try:
with open(json_path, 'r') as f:
scenes = json.load(f)
if not isinstance(scenes, list):
raise ValueError("JSON data must be a list of scenes.")
return scenes
except Exception as e:
print(f"Error loading JSON: {e}")
return []
def create_base_image(scene):
"""
Create the base image for a scene with background color.
"""
background_color = scene.get("background_color", "black")
img = Image.new('RGB', (FRAME_WIDTH, FRAME_HEIGHT), color=background_color)
return img
def load_font(scene):
"""
Load the specified font or default font.
"""
try:
font_path = scene.get("font_path", DEFAULT_FONT_PATH)
font_size = scene.get("font_size", 50)
font = ImageFont.truetype(font_path, size=font_size)
except Exception as e:
print(f"Error loading font '{scene.get('font_path', DEFAULT_FONT_PATH)}': {e}. Using default font.")
try:
font = ImageFont.truetype(DEFAULT_FONT_PATH, size=50)
except Exception as e:
print(f"Failed to load default font. {e}")
font = ImageFont.load_default()
return font
def add_text(image, text, font, font_color, visible_chars=None):
"""
Add text to an image. If visible_chars is specified, only that many characters are visible.
"""
draw = ImageDraw.Draw(image)
if visible_chars is not None:
text_to_draw = text[:visible_chars]
else:
text_to_draw = text
# Get text size
text_width, text_height = font.getsize(text_to_draw)
position = ((FRAME_WIDTH - text_width) // 2, (FRAME_HEIGHT - text_height) // 2)
draw.text(position, text_to_draw, font=font, fill=font_color)
return image
def blend_images(img1, img2, alpha):
"""
Blend two PIL images with the given alpha for img2.
"""
return Image.blend(img1, img2, alpha)
def pil_to_cv2(image):
"""
Convert PIL Image to OpenCV image (BGR).
"""
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
def generate_fade_frames(base_img, fade_type='in'):
"""
Generate fade in or fade out frames.
"""
frames = []
black_img = Image.new('RGB', (FRAME_WIDTH, FRAME_HEIGHT), color="black")
total_frames = FADE_IN_FRAMES if fade_type == 'in' else FADE_OUT_FRAMES
for i in range(total_frames):
if fade_type == 'in':
alpha = (i + 1) / total_frames
blended = blend_images(black_img, base_img, alpha)
else:
alpha = 1 - (i + 1) / total_frames
blended = blend_images(base_img, black_img, alpha)
cv_frame = pil_to_cv2(blended)
frames.append(cv_frame)
return frames
def get_text_size(draw, text, font):
"""
Get the size of the text using the most compatible method based on Pillow version.
"""
if hasattr(draw, "textbbox"):
bbox = draw.textbbox((0, 0), text, font=font)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
elif hasattr(font, "getbbox"):
bbox = font.getbbox(text)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
elif hasattr(font, "getsize"):
width, height = font.getsize(text)
else:
width, height = 0, 0 # Fallback if all methods are unavailable
return width, height
def generate_text_animation_frames(base_img, text, font, font_color, animation_type, font_path=DEFAULT_FONT_PATH):
"""
Generate frames with text animation effects.
Supported animations: Typing Effect, Fade In, Slide In, Zoom In
"""
frames = []
total_chars = len(text)
chars_per_frame = max(total_chars // TEXT_ANIMATION_FRAMES, 1)
if animation_type == "Typing Effect":
for i in range(TEXT_ANIMATION_FRAMES):
visible_chars = min((i + 1) * chars_per_frame, total_chars)
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color, visible_chars=visible_chars)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
# Ensure the entire text is visible in the last frame
while len(frames) < TEXT_ANIMATION_FRAMES:
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
elif animation_type == "Fade In":
# Start with transparent text and gradually increase opacity
for i in range(TEXT_ANIMATION_FRAMES):
animated_img = base_img.copy()
alpha = (i + 1) / TEXT_ANIMATION_FRAMES
# Create a transparent overlay
overlay = Image.new('RGBA', animated_img.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay)
text_width, text_height = font.getsize(text) # Updated line
position = ((FRAME_WIDTH - text_width) // 2, (FRAME_HEIGHT - text_height) // 2)
# Convert font_color to RGBA with changing alpha
try:
rgb = ImageColor.getrgb(font_color)
text_color = (*rgb, int(255 * alpha))
except ValueError:
# If font_color is invalid, default to white
text_color = (255, 255, 255, int(255 * alpha))
draw.text(position, text, font=font, fill=text_color)
animated_img = Image.alpha_composite(animated_img.convert('RGBA'), overlay)
cv_frame = pil_to_cv2(animated_img.convert('RGB'))
frames.append(cv_frame)
elif animation_type == "Slide In":
# Slide text from left to center
for i in range(TEXT_ANIMATION_FRAMES):
animated_img = base_img.copy()
draw = ImageDraw.Draw(animated_img)
text_width, text_height = font.getsize(text) # Updated line
# Start off-screen
total_slide_distance = FRAME_WIDTH // 2 - text_width // 2
current_slide = int((total_slide_distance) * (i + 1) / TEXT_ANIMATION_FRAMES)
position = (current_slide, (FRAME_HEIGHT - text_height) // 2)
draw.text(position, text, font=font, fill=font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
elif animation_type == "Zoom In":
# Start with smaller text size and increase to final size
initial_size = max(int(font.size * 0.5), 10)
for i in range(TEXT_ANIMATION_FRAMES):
temp_font_size = initial_size + int((font.size - initial_size) * (i + 1) / TEXT_ANIMATION_FRAMES)
temp_font = ImageFont.truetype(font_path, size=temp_font_size)
animated_img = base_img.copy()
add_text(animated_img, text, temp_font, font_color)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
else:
# Default to Typing Effect if unknown animation
for i in range(TEXT_ANIMATION_FRAMES):
visible_chars = min((i + 1) * chars_per_frame, total_chars)
animated_img = base_img.copy()
add_text(animated_img, text, font, font_color, visible_chars=visible_chars)
cv_frame = pil_to_cv2(animated_img)
frames.append(cv_frame)
return frames
def generate_display_frames(base_img):
"""
Generate static display frames.
"""
cv_frame = pil_to_cv2(base_img)
return [cv_frame] * DISPLAY_FRAMES
def generate_scene_frames(scene):
"""
Generate all frames for a single scene including transitions and animations.
"""
frames = []
base_img = create_base_image(scene)
font = load_font(scene)
text = scene.get("text", "")
font_color = scene.get("font_color", "white")
text_animation = scene.get("text_animation", "Typing Effect")
font_path = scene.get("font_path", DEFAULT_FONT_PATH)
# Fade In
fade_in_frames = generate_fade_frames(base_img, fade_type='in')
frames.extend(fade_in_frames)
# Display
display_frames = generate_display_frames(base_img)
frames.extend(display_frames)
# Text Animation
text_animation_frames = generate_text_animation_frames(
base_img,
text,
font,
font_color,
text_animation,
font_path=font_path
)
frames.extend(text_animation_frames)
# Fade Out
fade_out_frames = generate_fade_frames(base_img, fade_type='out')
frames.extend(fade_out_frames)
return frames
def generate_video(scenes):
"""
Generate the video from the list of scenes.
"""
# Ensure output directory exists
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*VIDEO_CODEC)
out = cv2.VideoWriter(VIDEO_OUTPUT, fourcc, FPS, (FRAME_WIDTH, FRAME_HEIGHT))
for idx, scene in enumerate(scenes):
print(f"Processing scene {idx + 1}/{len(scenes)}: '{scene.get('text', '')}'")
scene_frames = generate_scene_frames(scene)
for frame in scene_frames:
out.write(frame)
# Release everything if job is finished
out.release()
print(f"\nVideo generated successfully at: {VIDEO_OUTPUT}")
def main():
scenes = load_scenes(JSON_PATH)
if not scenes:
print("No scenes to process. Please run the setup script first to create 'video_data.json'.")
return
generate_video(scenes)
if __name__ == "__main__":
main()
7. Additional Recommendations
-
Validate video_data.json: Ensure your JSON file is correctly formatted and contains all necessary fields for each scene, such as text, background_color, font_path, font_size, font_color, and text_animation.
-
Handle Missing Fonts Gracefully: If a specified font path is invalid, ensure your script falls back to a default font without crashing.
-
Optimize Frame Generation: Depending on the number of scenes and frames per scene, video generation can be time-consuming. Consider optimizing the frame generation process or providing progress updates.
-
Error Logging: Implement more robust error handling and logging to capture and diagnose issues effectively.
-
Dependencies: Ensure all required libraries (Pillow, OpenCV, numpy) are installed and up-to-date in your environment.
pip install Pillow opencv-python numpy
-
Test with a Single Scene: Before processing multiple scenes, test the script with a single, simple scene to ensure everything works as expected.
By implementing these changes and recommendations, your script should function correctly without encountering the AttributeError and handle text animations smoothly across different Pillow versions.
If you continue to face issues or have further questions, feel free to ask!