Created
December 15, 2023 20:24
-
-
Save PeterHindes/18161b04446cac9e28a72fcdba1fd83b to your computer and use it in GitHub Desktop.
PNG Image Separator/Island Isolator (useful for after effects animating png logos)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
def save_components(image_path): | |
# Load the image with alpha channel | |
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) | |
# Create a binary image where 0 indicates transparent pixels | |
_, alpha_bin = cv2.threshold(img[:,:,3], 0, 255, cv2.THRESH_BINARY) | |
# Find all connected components in the binary image | |
num_labels, labels = cv2.connectedComponents(alpha_bin) | |
for label in range(1, num_labels): | |
# Create an empty image to store this component | |
component_img = np.zeros_like(img) | |
# Find pixels of this component and copy them from the original image | |
component_img[labels == label] = img[labels == label] | |
# Save the component image | |
cv2.imwrite(f'component_{label}.png', component_img) | |
# Call the function with your image path | |
save_components('logo.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment