It seems you're attempting to create a rotating transparent GIF of your logo using Matplotlib and PIL. There are a few issues in your code that might prevent it from working as intended, especially regarding the mapping of the image onto the 3D surface and handling transparency when saving the GIF.
Issues Identified:
-
Mismatch in Array Dimensions for facecolors: The facecolors parameter in ax.plot_surface should have the same dimensions as the surface grid (X, Y, Z). In your code, the surface grid is of size (2, 2), while the logo_array is much larger, causing a mismatch.
-
Transparency Handling in Saved Images: Matplotlib may not preserve transparency correctly when capturing the canvas buffer directly. This can result in a non-transparent background in your frames.
-
Transparency in GIFs: The GIF format supports limited transparency (only one color can be transparent). Preserving full alpha transparency requires careful handling when saving the GIF.
Proposed Solution:
To address these issues, we'll:
- Adjust the surface grid to match the dimensions of the logo image.
- Properly handle transparency when saving frames.
- Convert frames to a format suitable for GIF transparency.
Here's the modified code with explanations:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import art3d
from PIL import Image, ImageSequence
from io import BytesIO
def create_frame(image_path, angle):
# Open and process the logo image
logo = Image.open(image_path).convert("RGBA")
logo_array = np.array(logo)
nrows, ncols = logo_array.shape[0], logo_array.shape[1]
# Create figure with transparent background
fig = plt.figure(figsize=(8, 8))
fig.patch.set_alpha(0.0)
ax = fig.add_subplot(111, projection='3d')
# Set background transparent
ax.patch.set_alpha(0.0)
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
# Remove grid lines
ax.grid(False)
# Create a grid for the rotating surface matching the logo's resolution
x = np.linspace(-0.5, 0.5, ncols)
y = np.linspace(-0.5, 0.5, nrows)
X, Y = np.meshgrid(x, y)
Z = np.zeros_like(X)
# Plot the logo as a surface
ax.plot_surface(X, Y, Z,
rstride=1, cstride=1,
facecolors=logo_array/255.0,
shade=False,
antialiased=False)
# Set the view angle for rotation
ax.view_init(elev=0, azim=angle)
# Set axis limits and remove axes
ax.set_xlim([-0.6, 0.6])
ax.set_ylim([-0.6, 0.6])
ax.set_zlim([-0.6, 0.6])
ax.axis('off')
return fig
def generate_rotation_gif(image_path, output_file="rotating_logo_transparent.gif", num_frames=36):
frames = []
for i in range(num_frames):
angle = i * (360 / num_frames)
fig = create_frame(image_path, angle)
# Save figure to buffer with transparency
buf = BytesIO()
fig.savefig(buf, format='png', transparent=True, bbox_inches='tight', pad_inches=0)
buf.seek(0)
frame = Image.open(buf)
# Ensure frame has an alpha channel
frame = frame.convert('RGBA')
# Replace fully transparent pixels with a color (optional)
datas = frame.getdata()
newData = []
for item in datas:
# If pixel is transparent
if item[3] == 0:
# Replace with transparent (can set a specific color if needed)
newData.append((255, 255, 255, 0))
else:
newData.append(item)
frame.putdata(newData)
frames.append(frame)
plt.close(fig)
buf.close()
# Prepare frames for GIF saving
frames_converted = []
for frame in frames:
frame_p = frame.convert('P', palette=Image.ADAPTIVE, colors=255)
alpha = frame.split()[3]
# Create transparency mask
mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
frame_p.paste(255, mask)
frames_converted.append(frame_p)
# Save as GIF with transparency
frames_converted[0].save(
output_file,
save_all=True,
append_images=frames_converted[1:],
duration=50,
loop=0,
transparency=255,
disposal=2
)
# Example usage
logo_path = "/root/mm/android_final/automated_image_generator/platinum/logo.png"
generate_rotation_gif(logo_path)
print("GIF creation completed. Check rotating_logo_transparent.gif")
Explanation of Changes:
-
Adjusted Surface Grid Dimensions:
- The
x and y arrays in create_frame now match the dimensions of the logo image, ensuring that the facecolors array aligns correctly with the surface.
-
Saving Figures with Transparency:
- Instead of capturing the canvas buffer directly, we save each frame as a PNG to a
BytesIO buffer with transparent=True.
- This method preserves the alpha transparency in the saved image.
-
Converting Frames for GIF Transparency:
- Before saving the GIF, we convert each frame to 'P' mode (paletted) using an adaptive palette.
- We create a mask from the alpha channel to identify transparent pixels.
- We set the transparency index to
255, which corresponds to the last color in the palette.
Note on GIF Transparency:
- GIFs support only binary transparency—pixels are either fully opaque or fully transparent.
- The code above sets pixels with alpha less than or equal to 128 as transparent.
- Adjust the lambda function
lambda a: 255 if a <= 128 else 0 if you need a different threshold.
Alternative Approaches:
-
Using ImageMagick:
- For better results, especially with complex transparency, consider using ImageMagick via subprocess calls to handle GIF creation.
- Save each frame as a PNG and then combine them into a GIF using ImageMagick's
convert command.
-
Using Other Formats:
- If you require partial transparency, consider using APNG (Animated PNG) or a video format like WebM.
- Be aware that support for these formats may vary across different platforms and browsers.
Additional Tips:
Potential Issues and Solutions:
Summary:
- By adjusting the surface grid to match your logo's dimensions and correctly handling the transparency when saving frames and the final GIF, you should achieve the desired rotating transparent logo.
- Remember that GIFs have limitations regarding color and transparency, so the output might not fully match the quality of the original image.
I hope this helps you create the rotating logo GIF with transparency as intended! If you have any further questions or need additional assistance, feel free to ask.