Skip to content

Instantly share code, notes, and snippets.

@ftp27
Last active Aug 29, 2015
Embed
What would you like to do?
Crop Image By Transparent Spaces
from PIL import Image, ImageDraw
def checkX(image, x):
pixels = image.load()
sum = 0;
for i in range(image.size[1]):
if (pixels[x,i][3] == 0):
sum += 1
return (sum == image.size[1])
def checkY(image, y):
pixels = image.load()
sum = 0;
for i in range(image.size[0]):
if (pixels[i,y][3] == 0):
sum += 1
return (sum == image.size[0])
image = Image.open('icons02_36-01.png')
x = []
y = []
icon_width = 40
width = image.size[0]
height = image.size[1]
pix = image.load()
for i in range(width):
if (checkX(image,i)):
x.append(i)
for j in range(height):
if (checkY(image,j)):
y.append(j)
count = 0;
print x,y
for i in range(1,len(x)):
for j in range(1,len(y)):
if ((1 < x[i]-x[i-1] < icon_width) and (1 < y[j]-y[j-1] < icon_width)):
print (x[i-1], y[j-1], x[i], y[j])
croped_image = image.crop((x[i-1], y[j-1], x[i], y[j]))
croped_pixels = croped_image.load()
cx = cw = cy = ch = None
for ci in range(croped_image.size[0]):
check = checkX(croped_image,ci)
if (check == False and cx == None):
cx = ci
elif (check == True and cx != None):
break
if (cx == None):
continue
cw = ci - cx
for cj in range(croped_image.size[1]):
check = checkY(croped_image,cj)
if (check == False and cy == None):
cy = cj
elif (check == True and cy != None):
break
ch = cj - cy
print (cx,cy,cw,ch,(ci,cj),croped_image.size)
croped_image.crop((cx,cy,ci+1,cj+1)).save(str(count)+".png")
count+=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment