else/DeLetterbox/deletterbox.py

61 lines
1.6 KiB
Python
Raw Normal View History

2016-01-24 20:48:39 +00:00
from PIL import Image
import os
import sys
2016-05-10 08:00:29 +00:00
close_enough_threshold = 10
2016-02-21 07:13:50 +00:00
filename = sys.argv[1]
try:
close_enough_threshold = int(sys.argv[2])
except:
pass
2016-01-24 20:48:39 +00:00
def close_enough(a, b):
2016-07-05 07:24:08 +00:00
#print(a, b)
2016-01-24 20:48:39 +00:00
for (a_channel, b_channel) in zip(a, b):
2016-02-21 07:13:50 +00:00
if abs(a_channel - b_channel) > close_enough_threshold:
2016-01-24 20:48:39 +00:00
return False
return True
def deletterbox(filename):
image = Image.open(filename)
2016-07-05 07:24:08 +00:00
(base, ext) = os.path.splitext(filename)
2016-01-24 20:48:39 +00:00
for x in range(4):
image = trim_top(image)
2016-07-05 07:24:08 +00:00
print('size', image.size)
#image.save('%s_%d%s' % (base, x, ext))
rotated = image.rotate(90, expand=True)
# There is currently a bug in PIL which causes rotated images
# to have a 1 px black border on the top and left
if rotated.size != image.size:
rotated = rotated.crop([1, 1, rotated.size[0], rotated.size[1]])
image = rotated
print()
filename = base + '_crop' + ext
2016-02-21 07:13:50 +00:00
image.save(filename, quality=100)
2016-01-24 20:48:39 +00:00
def trim_top(image):
letterbox_color = image.getpixel((0, 0))
2016-07-05 07:24:08 +00:00
print('letterbox color', letterbox_color)
2016-01-24 20:48:39 +00:00
for y in range(image.size[1]):
solid = True
for x in range(image.size[0]):
pixel = image.getpixel((x, y))
2016-02-21 07:13:50 +00:00
#print(pixel)
2016-01-24 20:48:39 +00:00
if not close_enough(letterbox_color, pixel):
solid = False
2016-07-05 07:24:08 +00:00
print('broke at', y,pixel)
2016-01-24 20:48:39 +00:00
break
if not solid:
break
bounds = (0, y, image.size[0], image.size[1])
2016-07-05 07:24:08 +00:00
print('bounds', bounds)
2016-01-24 20:48:39 +00:00
image = image.crop(bounds)
return image
2016-02-21 07:13:50 +00:00
deletterbox(filename)
2016-01-24 20:48:39 +00:00