#!/usr/bin/env python3 import os import shutil import cv2 import numpy as np from…
- User
#!/usr/bin/env python3
import os import shutil import cv2 import numpy as np from moviepy.editor import ImageSequenceClip from datetime import datetime
class ParallaxLayer: """Class to represent a single parallax layer.""" def init(self, image, factor): self.surface = image self.factor = factor self.scroll = 0
class ParallaxEffect: """Class to manage the parallax effect with multiple layers.""" def init(self, size, orientation='horizontal'): self.size = size self.orientation = orientation self.levels = [] self.scroller = 0
def add_layer(self, image, factor): """Add a layer to the parallax effect.""" layer = ParallaxLayer(image, factor) self.levels.append(layer) def draw(self, surface): """Draw all parallax levels onto the surface.""" s_width, s_height = self.size for lvl in self.levels: if self.orientation == 'vertical': surface.blit(lvl.surface, (0, 0), (0, -lvl.scroll, s_width, s_height)) surface.blit(lvl.surface, (0, lvl.scroll - lvl.surface.shape[0])) else: surface.blit(lvl.surface, (0, 0), (lvl.scroll, 0, s_width, s_height)) surface.blit(lvl.surface, (lvl.surface.shape[1] - lvl.scroll, 0), (0, 0, lvl.scroll, s_height)) def scroll(self, offset, orientation=None): """Scroll the parallax layers by a certain offset.""" if orientation is not None: self.orientation = orientation self.scroller = (self.scroller + offset) for lvl in self.levels: if self.orientation == 'vertical': lvl.scroll = (self.scroller / lvl.factor) % lvl.surface.shape[0] else: lvl.scroll = (self.scroller / lvl.factor) % lvl.surface.shape[1]def clear_processing_folder(folder_path): """Clears the processing folder.""" if os.path.exists(folder_path): shutil.rmtree(folder_path) os.makedirs(folder_path)
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 with different factors 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) # Initialize the ParallaxEffect object parallax = ParallaxEffect(size=(width, height), orientation='horizontal') parallax.add_layer(background, factor=1.0) parallax.add_layer(foreground, factor=0.5) # Calculate the number of frames num_frames = int(duration * fps) # Initialize a list to store frames frames = [] for i in range(num_frames): # Calculate scroll offset offset = i / num_frames * width * 0.1 # Scroll the parallax layers parallax.scroll(offset) # Create empty canvas for each frame frame = np.zeros((height, width, 3), dtype=np.uint8) # Draw the parallax effect parallax.draw(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')def main(): # Paths input_image = "/root/parallax/new.jpeg" output_folder = "/root/parallax/image" processing_folder = "/root/parallax/processing" shared_folder = "/sdcard/Shared" # If you need to copy the output here
# Generate timestamp timestamp = datetime.now().strftime("%Y%m%d%H%M%S") # Prepare filenames input_filename = f"new_{timestamp}.jpeg" output_filename = f"new_{timestamp}.mp4" # Ensure output and processing folders exist os.makedirs(output_folder, exist_ok=True) clear_processing_folder(processing_folder) # Copy and rename the input image to the processing folder processing_image_path = os.path.join(processing_folder, input_filename) shutil.copy2(input_image, processing_image_path) # Prepare the output video path output_video_path = os.path.join(output_folder, output_filename) # Create the parallax effect create_parallax_effect(processing_image_path, output_video_path) # Optionally copy the output to the shared folder if os.path.isdir(shared_folder): shutil.copy2(output_video_path, shared_folder) # Clear the processing folder after completion clear_processing_folder(processing_folder) print(f"Parallax effect video created successfully at {output_video_path}")if name == "main": main()
- Assistant
Hello! It looks like you've provided a Python script intended to create an animated parallax effect from a single image using OpenCV and MoviePy. I'd be happy to help you with this code.
Issues Identified:
-
Usage of
surface.blit:- The
blitmethod is commonly associated with Pygame surfaces, not NumPy arrays. - In your code,
surfaceis a NumPy array (an image), so callingsurface.blitwill result in anAttributeError.
- The
-
Manipulating and Combining NumPy Arrays:
- To manipulate images using NumPy arrays, you need to use slicing and array operations rather than
blit.
- To manipulate images using NumPy arrays, you need to use slicing and array operations rather than
-
Parallax Scrolling Logic:
- The way the offsets and scrolling are calculated might not produce the desired parallax effect.
- There might be issues with how the scroll positions wrap around the image dimensions.
Here's a revised version of your script with modifications to address these issues:
#!/usr/bin/env python3 import os import shutil import cv2 import numpy as np from moviepy.editor import ImageSequenceClip from datetime import datetime class ParallaxLayer: """Class to represent a single parallax layer.""" def __init__(self, image, factor): self.surface = image self.factor = factor self.scroll = 0 class ParallaxEffect: """Class to manage the parallax effect with multiple layers.""" def __init__(self, size, orientation='horizontal'): self.size = size self.orientation = orientation self.levels = [] self.scroller = 0 def add_layer(self, image, factor): """Add a layer to the parallax effect.""" layer = ParallaxLayer(image, factor) self.levels.append(layer) def draw(self): """Draw all parallax levels and return the composite image.""" s_width, s_height = self.size composite = np.zeros((s_height, s_width, 3), dtype=np.uint8) for lvl in self.levels: if self.orientation == 'vertical': scroll_pos = int(lvl.scroll) # Calculate the wrap-around effect part1 = lvl.surface[scroll_pos:, :] part2 = lvl.surface[:scroll_pos, :] layer_image = np.vstack((part1, part2)) else: scroll_pos = int(lvl.scroll) # Calculate the wrap-around effect part1 = lvl.surface[:, scroll_pos:] part2 = lvl.surface[:, :scroll_pos] layer_image = np.hstack((part1, part2)) # Resize layer_image to match the composite size if necessary layer_image = cv2.resize(layer_image, (s_width, s_height), interpolation=cv2.INTER_LINEAR) # Overlay the layer onto the composite image # Assuming simple addition for blending. Modify as needed. composite = cv2.addWeighted(composite, 1.0, layer_image, 1.0, 0) return composite def scroll_layers(self, offset, orientation=None): """Scroll the parallax layers by a certain offset.""" if orientation is not None: self.orientation = orientation self.scroller += offset for lvl in self.levels: if self.orientation == 'vertical': lvl.scroll = (self.scroller / lvl.factor) % lvl.surface.shape[0] else: lvl.scroll = (self.scroller / lvl.factor) % lvl.surface.shape[1] def clear_processing_folder(folder_path): """Clears the processing folder.""" if os.path.exists(folder_path): shutil.rmtree(folder_path) os.makedirs(folder_path) 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 image = cv2.imread(image_path) if image is None: raise FileNotFoundError(f"Image not found at path: {image_path}") height, width = image.shape[:2] # Create layers with different factors # Adjust the scaling factors as needed foreground = cv2.resize(image, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_LINEAR) background = cv2.resize(image, None, fx=1.0, fy=1.0, interpolation=cv2.INTER_LINEAR) # Ensure layers are larger than the output size to allow for scrolling fg_height, fg_width = foreground.shape[:2] bg_height, bg_width = background.shape[:2] # Initialize the ParallaxEffect object parallax = ParallaxEffect(size=(width, height), orientation='horizontal') parallax.add_layer(background, factor=1.0) parallax.add_layer(foreground, factor=0.5) # Calculate the number of frames num_frames = int(duration * fps) # Initialize a list to store frames frames = [] for i in range(num_frames): # Calculate scroll offset offset = width * 0.01 # Adjust scrolling speed as needed # Scroll the parallax layers parallax.scroll_layers(offset) # Draw the parallax effect and get the composite frame frame = parallax.draw() # 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') def main(): # Paths input_image = "/root/parallax/new.jpeg" output_folder = "/root/parallax/image" processing_folder = "/root/parallax/processing" shared_folder = "/sdcard/Shared" # If you need to copy the output here # Generate timestamp timestamp = datetime.now().strftime("%Y%m%d%H%M%S") # Prepare filenames input_filename = f"new_{timestamp}.jpeg" output_filename = f"new_{timestamp}.mp4" # Ensure output and processing folders exist os.makedirs(output_folder, exist_ok=True) clear_processing_folder(processing_folder) # Copy and rename the input image to the processing folder processing_image_path = os.path.join(processing_folder, input_filename) shutil.copy2(input_image, processing_image_path) # Prepare the output video path output_video_path = os.path.join(output_folder, output_filename) # Create the parallax effect create_parallax_effect(processing_image_path, output_video_path) # Optionally copy the output to the shared folder if os.path.isdir(shared_folder): shutil.copy2(output_video_path, shared_folder) # Clear the processing folder after completion clear_processing_folder(processing_folder) print(f"Parallax effect video created successfully at {output_video_path}") if __name__ == "__main__": main()
Explanation of Changes:
-
Removed
surface.blit:- Replaced
surface.blitcalls with NumPy array operations using slicing (np.hstackandnp.vstack) to simulate the scrolling effect.
- Replaced
-
Updated
drawMethod:- The
drawmethod now returns the composite image after layering all parallax levels. - It handles both horizontal and vertical scrolling.
- The
-
Adjusted Scroll Calculation:
- The
scroll_layersmethod updates each layer'sscrollattribute based on thescrollervalue and the layer'sfactor.
- The
-
Layer Image Resizing:
- After combining parts of the layers, the
layer_imageis resized to match the composite image dimensions. - This ensures consistency in frame sizes.
- After combining parts of the layers, the
-
Frame Blending:
- Used
cv2.addWeightedfor blending layers. You can adjust the weights or change the blending method as needed.
- Used
-
Adjusted Scrolling Offset:
- Modified the
offsetcalculation to a fixed value (width * 0.01) for smoother scrolling. - You can adjust this value to control the scrolling speed.
- Modified the
Additional Suggestions:
-
Check Image Sizes:
- Ensure that the foreground and background images are larger than the output frame size to allow for proper scrolling without empty spaces.
-
Adjusting Parallax Factors:
- Experiment with different
factorvalues when adding layers to achieve the desired parallax depth effect.
- Experiment with different
-
Frame Blending Techniques:
- If you require more advanced blending (e.g., alpha blending), you may need to handle transparency and layer masks.
-
Error Handling:
- Add more error handling to manage potential issues, such as image loading failures or mismatched dimensions.
Troubleshooting:
-
Black or Blank Frames:
- If the output video shows black or blank frames, double-check the slicing operations and ensure that layer images are correctly combined.
-
Performance Optimization:
- Processing large images frame by frame can be resource-intensive. Consider optimizing the code or resizing images to a manageable resolution.
-
Testing with Sample Images:
- Test the script with sample images to verify that the parallax effect works as expected before processing large or high-resolution images.
Next Steps:
-
Customize the Effect:
- Modify the scrolling speed, direction, and layer factors to create different parallax animations.
-
Add More Layers:
- Incorporate additional layers (e.g., middle ground) to enhance the depth effect.
-
Implement Vertical Parallax:
- Adjust the orientation to 'vertical' if you want to create a vertical scrolling parallax effect.
I hope this helps you get your parallax effect script working correctly! Let me know if you have any questions or need further assistance.
-