Created
December 22, 2023 18:14
-
-
Save chrisjd20/0ecd8b73b2be00c29790f6e74f59216b to your computer and use it in GitHub Desktop.
Crops out all parts of the image that are not transparent using python and pil. If transparency was the ocean and blobs of opaque pixels were islands, it would create a new image of each island.
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
from PIL import Image | |
def find_islands(image): | |
"""Find islands (cards) in the image.""" | |
width, height = image.size | |
pixels = image.load() | |
visited = set() | |
islands = [] | |
def is_transparent(x, y): | |
return pixels[x, y][3] == 0 | |
for x in range(width): | |
for y in range(height): | |
if not is_transparent(x, y) and (x, y) not in visited: | |
island = {'left': x, 'right': x, 'top': y, 'bottom': y} | |
stack = [(x, y)] | |
while stack: | |
cx, cy = stack.pop() | |
if (cx, cy) in visited: | |
continue | |
visited.add((cx, cy)) | |
island['left'] = min(island['left'], cx) | |
island['right'] = max(island['right'], cx) | |
island['top'] = min(island['top'], cy) | |
island['bottom'] = max(island['bottom'], cy) | |
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: | |
nx, ny = cx + dx, cy + dy | |
if 0 <= nx < width and 0 <= ny < height and not is_transparent(nx, ny): | |
stack.append((nx, ny)) | |
islands.append(island) | |
return islands | |
def crop_islands(image, islands): | |
"""Crop each island (card) from the image.""" | |
cropped_images = [] | |
for island in islands: | |
cropped = image.crop((island['left'], island['top'], island['right'] + 1, island['bottom'] + 1)) | |
cropped_images.append(cropped) | |
return cropped_images | |
# Load the image | |
image_path = "objective_cards.png" # Replace with your image path | |
image = Image.open(image_path) | |
# Find islands (cards) | |
islands = find_islands(image) | |
# Crop islands (cards) | |
cropped_images = crop_islands(image, islands) | |
# Save cropped images | |
for idx, img in enumerate(cropped_images): | |
img.save(f"cropped_card_{idx}.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment