It looks like you're attempting to add an animated electric border around a logo using Python's PIL library. However, as you've noted, the current implementation doesn't perform edge detection, resulting in the lightning not conforming to the logo's actual shape. Instead, it creates a uniform electric frame around the entire image.
To achieve an electric border that follows the contours of your logo, you'll need to incorporate edge detection. This can be accomplished using libraries such as OpenCV or Pillow's built-in filters. Below, I'll provide a comprehensive guide to modifying your script to include edge detection and generate lightning effects along those edges.
Step 1: Install Required Libraries
First, ensure you have all the necessary libraries installed. While you're already using PIL (Pillow), we'll also use OpenCV for more robust edge detection.
pip install pillow opencv-python numpy
Step 2: Modify the Script to Include Edge Detection
Here's an updated version of your script that incorporates edge detection using OpenCV. The approach involves detecting the edges of the logo and then generating lightning effects along those edges to create an electric border.
import os
import math
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance, ImageChops
import random
import cv2
import numpy as np
def create_lightning_along_edges(draw, edge_points, branches=3, depth=4):
"""
Draw lightning effects between random points along the detected edges.
"""
if len(edge_points) < 2:
return
# Select random pairs of points to draw lightning between
num_lightnings = len(edge_points) // 10 # Adjust density as needed
for _ in range(num_lightnings):
p1, p2 = random.sample(edge_points, 2)
draw_lightning(draw, p1, p2, branches, depth)
def draw_lightning(draw, start, end, branches, depth):
"""
Recursively draw lightning from start to end points.
"""
if depth == 0:
draw.line([start, end], fill=(255, 255, 255), width=2)
return
mid = (
(start[0] + end[0]) / 2 + random.randint(-20, 20),
(start[1] + end[1]) / 2 + random.randint(-20, 20)
)
draw.line([start, mid], fill=(255, 255, 255), width=2)
draw.line([mid, end], fill=(255, 255, 255), width=2)
if branches > 0:
draw_lightning(draw, mid, start, branches - 1, depth - 1)
draw_lightning(draw, mid, end, branches - 1, depth - 1)
def detect_edges(input_path):
"""
Detect edges in the image using OpenCV and return a list of edge pixels.
"""
# Open the image and convert to grayscale
image = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
if image is None:
raise FileNotFoundError(f"Cannot find or open the image: {input_path}")
# Handle transparency if present
if image.shape[2] == 4:
alpha_channel = image[:, :, 3]
_, thresh = cv2.threshold(alpha_channel, 1, 255, cv2.THRESH_BINARY)
image = cv2.bitwise_and(image, image, mask=thresh)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Use Canny edge detection
edges = cv2.Canny(gray, threshold1=50, threshold2=150)
# Get edge points
edge_points = np.argwhere(edges != 0)
# Convert from (row, col) to (x, y)
edge_points = [(int(col), int(row)) for row, col in edge_points]
return edge_points
def create_electric_border_with_edges(width, height, edge_points):
"""
Create an electric border image based on the detected edges.
"""
electric = Image.new("RGBA", (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(electric)
if not edge_points:
return electric
create_lightning_along_edges(draw, edge_points)
# Apply effects
electric = electric.filter(ImageFilter.GaussianBlur(radius=2))
enhancer = ImageEnhance.Brightness(electric)
electric = enhancer.enhance(1.5)
return electric
def add_animated_electric_border(input_path, output_path, num_frames=10):
# Open the original image
original = Image.open(input_path).convert("RGBA")
width, height = original.size
# Detect edges
edge_points = detect_edges(input_path)
frames = []
for _ in range(num_frames):
electric = create_electric_border_with_edges(width, height, edge_points)
frame = Image.new("RGBA", (width, height), (0, 0, 0, 0))
frame.paste(original, (0, 0), original)
frame = Image.alpha_composite(frame, electric)
frames.append(frame)
# Save the result as an animated GIF
frames[0].save(
output_path,
save_all=True,
append_images=frames[1:],
duration=100,
loop=0,
disposal=2
)
if __name__ == "__main__":
input_path = "/root/mm/android_final/automated_image_generator/logo.png"
output_dir = "/root/mm/android_final/automated_image_generator/plat_sub/electric"
output_path = os.path.join(output_dir, "logo_with_animated_electric_border.gif")
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
add_animated_electric_border(input_path, output_path)
print(f"Animated electric border added. Result saved to {output_path}")
Step 3: Explanation of Changes
-
Edge Detection with OpenCV:
- The
detect_edges function uses OpenCV's Canny edge detection to identify the edges of the logo.
- It handles images with transparency by considering the alpha channel.
- The detected edge points are converted into a list of
(x, y) tuples for further processing.
-
Drawing Lightning Along Edges:
- The
create_lightning_along_edges function selects random pairs of edge points and draws lightning between them using the draw_lightning recursive function.
- The
draw_lightning function draws the main lightning and recursively adds branches to simulate a realistic electric effect.
-
Creating the Electric Border:
- The
create_electric_border_with_edges function creates a transparent image and draws the lightning effects based on the detected edges.
- It applies a Gaussian blur and enhances brightness to make the electric effects more pronounced.
-
Integrating with Animated GIF Creation:
- The
add_animated_electric_border function now incorporates the edge detection process and generates frames with electric borders that follow the logo's contours.
- It compiles these frames into an animated GIF.
Step 4: Additional Enhancements (Optional)
1. Improving Lightning Appearance:
To make the lightning appear more dynamic and varied across frames, you can introduce randomness in the brightness, color, or the number of branches.
def create_lightning_along_edges(draw, edge_points, branches=3, depth=4):
"""
Draw lightning effects between random points along the detected edges.
"""
if len(edge_points) < 2:
return
num_lightnings = max(1, len(edge_points) // 100) # Adjust density as needed
for _ in range(num_lightnings):
p1, p2 = random.sample(edge_points, 2)
color = (
random.randint(200, 255),
random.randint(200, 255),
random.randint(200, 255),
random.randint(150, 255) # Allow some transparency
)
draw_lightning_custom(draw, p1, p2, color, branches, depth)
def draw_lightning_custom(draw, start, end, color, branches, depth):
"""
Recursively draw lightning from start to end points with a specific color.
"""
if depth == 0:
draw.line([start, end], fill=color, width=2)
return
mid = (
(start[0] + end[0]) / 2 + random.randint(-20, 20),
(start[1] + end[1]) / 2 + random.randint(-20, 20)
)
draw.line([start, mid], fill=color, width=2)
draw.line([mid, end], fill=color, width=2)
if branches > 0:
draw_lightning_custom(draw, mid, start, color, branches - 1, depth - 1)
draw_lightning_custom(draw, mid, end, color, branches - 1, depth - 1)
2. Animating Effects:
To make the electric border appear animated (like flickering or moving), you can vary the lightning patterns across frames by modifying random seeds or altering parameters slightly for each frame.
Step 5: Testing and Fine-Tuning
After implementing the changes:
-
Run the Script:
Execute your script to generate the animated GIF with the electric border.
-
Review the Output:
Check the logo_with_animated_electric_border.gif to see if the electric border aligns with your logo's edges.
-
Adjust Parameters:
- Edge Detection Thresholds: Modify the
threshold1 and threshold2 in the cv2.Canny function to better capture your logo's edges.
- Lightning Density: Adjust
num_lightnings calculation to increase or decrease the electric effects.
- Branching and Depth: Tweak
branches and depth in draw_lightning for more complex or simpler lightning patterns.
-
Optimize Performance:
If processing large images or generating many frames, consider optimizing the edge detection and lightning generation steps to improve performance.
Conclusion
By incorporating edge detection, the electric border now follows the contours of your logo, creating a more integrated and visually appealing effect. You can further enhance and customize the appearance by adjusting parameters and adding more sophisticated animation techniques. If you encounter any issues or have further questions, feel free to ask!