Skip to content

Instantly share code, notes, and snippets.

@JettMonstersGoBoom
Last active May 9, 2023 03:01
import os, sys, platform, string, getopt
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
from PIL import Image, ImageSequence, ImageDraw
# yes hardcoded filenames. whatevs :P
# load image
sourceimage = Image.open("test2.png")
pal = sourceimage.getpalette()
sourceimage = sourceimage.convert('RGBA', colors=255)
# split the channels, we only care about alpha here
red, green, blue, alpha = sourceimage.split()
(w, h) = sourceimage.size
# shrink the alpha by 4
alpha=alpha.resize(((int)(w/4),(int)(h/4)),Image.NEAREST)
#
threshold = 50
# create numpy array
img = np.asarray(alpha)
# label the objects ( anything !=0 is grouped into an object)
labeled, nr_objects = ndimage.label(img > threshold)
# slice this up to give us rectangles
slices = ndimage.find_objects(labeled)
# blank image array for gif
images = []
# max size
MaxWidth = 0
MaxHeight = 0
realcount = 0
for dy, dx in slices:
if dx.stop-dx.start>=2 and dy.stop-dy.start>=2:
realcount+=1
if dx.stop-dx.start>MaxWidth: MaxWidth = dx.stop-dx.start
if dy.stop-dy.start>MaxHeight: MaxHeight = dy.stop-dy.start
MaxWidth=MaxWidth<<2
MaxHeight=MaxHeight<<2
#for 8x8
CellMaxWidth = (int)(((MaxWidth+7)/8))*8
CellMaxHeight = (int)(((MaxHeight+7)/8))*8
#CellMaxWidth = (int)(((MaxWidth+63)/64))*64
#CellMaxHeight = (int)(((MaxHeight+63)/64))*64
print(str(CellMaxWidth) + "," + str(CellMaxHeight))
stripImage = Image.new(mode="RGBA", size=(CellMaxWidth*(int)(realcount/16), CellMaxHeight*16))
draw = ImageDraw.Draw(stripImage)
draw.rectangle([(0,0),stripImage.size], fill = sourceimage.getpixel((0,0)) )
index = 0
# process
for dy, dx in slices:
# get width ( remember to scale back up)
w = (dx.stop-dx.start)<<2
h = (dy.stop-dy.start)<<2
# if it's smaller than a cell, just ignore it
if w>=8 and h>=8:
# make a destination
im = Image.new(mode="RGBA", size=(CellMaxWidth, CellMaxHeight))
# clear it
draw = ImageDraw.Draw(im)
draw.rectangle([(0,0),im.size], fill = sourceimage.getpixel((0,0)) )
# position at the bottom and in the center X
yoff = CellMaxHeight - h
xoff = (int)((CellMaxWidth/2) - (w/2))
# crop from source
im1 = sourceimage.crop((dx.start<<2, dy.start<<2, dx.stop<<2, dy.stop<<2))
# paste to gif frame
Image.Image.paste(im, im1, (xoff, yoff))
im = im.convert("P", 0, pal)
Image.Image.paste(stripImage, im1, ((CellMaxWidth*(index&0xf))+xoff, (CellMaxHeight*(int)(index/16)+yoff)))
index += 1
# append it
images.append(im)
stripImage = stripImage.convert("P", 0, pal)
stripImage.save("strip.png")
# save
images[0].save('draw.gif',
save_all=True, append_images=images[1:], optimize=False, duration=60, loop=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment