Skip to content

Instantly share code, notes, and snippets.

@ftp27
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftp27/7363e6b05b7beaa47745 to your computer and use it in GitHub Desktop.
Save ftp27/7363e6b05b7beaa47745 to your computer and use it in GitHub Desktop.
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