Sure! Below is a Python script that will take a single image, create a parallax effect by animating different layers of the image, and produce a 10-second animated video. This script is designed to produce high-quality output suitable for business advertising.
Script Path: /root/parallax/ps.py
#!/usr/bin/env python3
import cv2
import numpy as np
from moviepy.editor import ImageSequenceClip
def create_parallax_effect(image_path, output_path, duration=10, fps=30):
"""
Creates an animated parallax effect from a single image.
:param image_path: Path to the input image.
:param output_path: Path to save the output video.
:param duration: Duration of the output video in seconds.
:param fps: Frames per second for the output video.
"""
# Load the image with alpha channel if present
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
if image is None:
raise FileNotFoundError(f"Image not found at path: {image_path}")
height, width = image.shape[:2]
# Create layers by scaling the image to simulate depth
foreground = cv2.resize(image, None, fx=1.1, fy=1.1, interpolation=cv2.INTER_LINEAR)
background = cv2.resize(image, None, fx=1.0, fy=1.0, interpolation=cv2.INTER_LINEAR)
# Calculate the number of frames
num_frames = int(duration * fps)
# Initialize a list to store frames
frames = []
for i in range(num_frames):
# Calculate offsets for parallax effect
offset_x = int((i / num_frames) * width * 0.1) # Foreground moves more
offset_bg_x = int((i / num_frames) * width * 0.05) # Background moves less
# Create empty canvas for each frame
frame = np.zeros_like(image)
# Calculate positions
fg_x = -offset_x
bg_x = -offset_bg_x
# Ensure positions are within bounds
fg_x = np.clip(fg_x, -(foreground.shape[1] - width), 0)
bg_x = np.clip(bg_x, -(background.shape[1] - width), 0)
# Overlay background
frame[:, :, :] = background[:, :, :]
# Overlay foreground with proper offsets
frame_fg = frame.copy()
frame_fg[:, :, :] = 0 # Clear frame
y1, y2 = 0, height
x1, x2 = -fg_x, -fg_x + width
frame_fg[y1:y2, :] = foreground[y1:y2, x1:x2]
# Combine background and foreground
alpha_fg = 0.5 # Adjust transparency if needed
cv2.addWeighted(frame_fg, alpha_fg, frame, 1 - alpha_fg, 0, frame)
# Convert BGR to RGB for MoviePy
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame_rgb)
# Create the video clip
clip = ImageSequenceClip(frames, fps=fps)
clip.write_videofile(output_path, codec='libx264')
if __name__ == "__main__":
# Define input and output paths
image_path = "/root/parallax/input_image.jpg" # Replace with your image path
output_path = "/root/parallax/parallax_effect.mp4"
# Create the parallax effect
create_parallax_effect(image_path, output_path)
Instructions:
-
Install Required Libraries:
Open a terminal and install the necessary Python libraries:
pip install opencv-python moviepy numpy
-
Prepare Your Image:
- Place your input image in the directory
/root/parallax/ and name it input_image.jpg.
- For the best effect, use a high-resolution image with distinct foreground and background elements.
-
Run the Script:
-
Output Video:
- The generated video
parallax_effect.mp4 will be saved in /root/parallax/.
- Review the video to ensure it meets your advertising needs.
Explanation:
-
Image Loading:
- The script reads the input image using OpenCV.
- It supports images with alpha channels for transparency.
-
Creating Layers:
- Two layers are created: a slightly zoomed-in foreground and the original background.
- This simulates depth by making the foreground larger than the background.
-
Animating Layers:
- The foreground and background layers are moved horizontally over time.
- The foreground moves faster than the background, enhancing the parallax effect.
- A total of
num_frames frames are generated based on the desired duration and FPS.
-
Combining Layers:
- Each frame overlays the foreground onto the background with calculated offsets.
- Transparency can be adjusted with the
alpha_fg variable.
-
Video Creation:
- Frames are converted from BGR (OpenCV format) to RGB (MoviePy format).
- MoviePy assembles the frames into a video file using the H.264 codec.
Enhancements for Business Advertising:
Tips:
-
Image Selection:
- Choose images with clear separation between foreground and background elements.
- High-resolution images yield better results.
-
Adjust Movement:
- Tweak the
offset_x and offset_bg_x calculations to control the movement speed.
- Experiment with different values to achieve the desired effect.
-
Frame Rate:
- A higher FPS results in smoother animations but increases the file size.
- 30 FPS is standard for most applications.
By following these steps and customizing as needed, you'll have a high-quality parallax effect animation perfect for your business advertising needs!