yofardev

before/after animation

Jul 23rd, 2024
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | Source Code | 0 0
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. from matplotlib.animation import FuncAnimation
  5.  
  6. # Load the images
  7. original = Image.open('1.png')
  8. enhanced = Image.open('2.png')
  9.  
  10. # Ensure both images are the same size
  11. assert original.size == enhanced.size, "Images must be the same size"
  12.  
  13. # Get image dimensions
  14. width, height = original.size
  15.  
  16. # Convert images to RGB mode
  17. original = original.convert('RGB')
  18. enhanced = enhanced.convert('RGB')
  19.  
  20. # Convert images to numpy arrays
  21. original_array = np.array(original)
  22. enhanced_array = np.array(enhanced)
  23.  
  24. # Calculate figure size (dividing by 100 to convert pixels to inches)
  25. figsize = (width/100, height/100)
  26.  
  27. # Create the figure and axis
  28. fig, ax = plt.subplots(figsize=figsize)
  29.  
  30. # Remove all margins
  31. plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
  32.  
  33. # Initialize the plot with the original image
  34. im = ax.imshow(original_array, aspect='auto')
  35.  
  36. # Remove axis ticks and labels
  37. ax.set_xticks([])
  38. ax.set_yticks([])
  39. ax.axis('off')
  40.  
  41. # Function to update the frame
  42. def update(frame):
  43.     # Create a mask for the enhanced portion
  44.     mask = np.zeros(original_array.shape[:2], dtype=bool)
  45.     mask[:, :frame] = True
  46.    
  47.     # Combine the original and enhanced images
  48.     combined = np.where(mask[:, :, np.newaxis], enhanced_array, original_array)
  49.    
  50.     # Update the image data
  51.     im.set_array(combined)
  52.    
  53.     # Add a vertical line to show the split
  54.     ax.clear()  # Clear previous lines
  55.     ax.imshow(combined, aspect='auto')
  56.     ax.axvline(x=frame, color='white', linewidth=1)
  57.     ax.set_xticks([])
  58.     ax.set_yticks([])
  59.     ax.axis('off')
  60.    
  61.     return [ax]
  62.  
  63. # Create the animation
  64. anim = FuncAnimation(fig, update, frames=width, interval=50, blit=False)
  65.  
  66. # Save the animation as a gif
  67. anim.save('comparison.gif', writer='pillow', fps=20, dpi=100)
  68.  
  69. plt.close(fig)
  70.  
  71. print("Animation saved as 'comparison.gif'")
Advertisement
Add Comment
Please, Sign In to add comment