43 lines
1.7 KiB
Python
43 lines
1.7 KiB
Python
from PIL import Image
|
|
import numpy as np
|
|
|
|
# Load the GIF
|
|
gif_path = "./garfield-garfield-meme-ezgif.com-added-text.gif"
|
|
gif = Image.open(gif_path)
|
|
|
|
# Define the color you want to replace (original text color) and the new color
|
|
original_text_color = (55, 126, 34) # Replace with the actual color of the text in RGB
|
|
new_text_color = (255, 254, 253) # Desired replacement color, e.g., black
|
|
|
|
# Function to find the indices of the top 5 closest colors in the palette
|
|
def find_closest_palette_color_indices(palette, target_color, num_colors=25):
|
|
palette = np.array(palette).reshape(-1, 3)
|
|
target_color = np.array(target_color)
|
|
distances = np.sqrt(((palette - target_color) ** 2).sum(axis=1))
|
|
# Get the indices of the closest colors
|
|
return distances.argsort()[:num_colors]
|
|
|
|
# Extract frames and modify frame 21
|
|
frames = []
|
|
for i in range(gif.n_frames):
|
|
gif.seek(i)
|
|
new_frame = gif.convert("P", palette=Image.ADAPTIVE) # Convert to palette mode
|
|
|
|
if i == 20:
|
|
# Get the palette and find the closest color indices for the original text color
|
|
palette = new_frame.getpalette()
|
|
closest_color_indices = find_closest_palette_color_indices(palette, original_text_color, num_colors=255)
|
|
|
|
# Modify the palette at each of the closest color indices to the new color
|
|
for idx in closest_color_indices:
|
|
palette[idx*3:idx*3+3] = list(new_text_color)
|
|
new_frame.putpalette(palette)
|
|
|
|
# Append the modified (or unmodified) frame
|
|
frames.append(new_frame)
|
|
|
|
# Save the modified GIF
|
|
output_path = "./modified_gif.gif"
|
|
frames[0].save(output_path, save_all=True, append_images=frames[1:], loop=0, duration=gif.info['duration'])
|
|
print(f"Modified GIF saved as {output_path}")
|