Created
January 20, 2022 14:21
-
-
Save martymcmodding/5ee690ed5aae0cc338a9302903ccef9f to your computer and use it in GitHub Desktop.
Batch cropping images (black bar removal)
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 | |
import glob | |
for filepath in glob.iglob(r'*.png'): | |
im = Image.open(filepath) | |
#print("Processing: ", filepath, " ", im.format, im.size, im.mode) | |
box = im.convert('RGB').getbbox() | |
#size of black bars in each axis | |
x1 = box[0] | |
x2 = im.size[0] - box[2] | |
y1 = box[1] | |
y2 = im.size[1] - box[3] | |
#first, assert that the bars are symmetric! | |
if x1 != x2 or y1 != y2: | |
print("asymmetric borders, skipping...") | |
continue | |
if x1 == 0 and y1 == 0: | |
print("no borders detected, skipping...") | |
continue | |
box = list(box) #cannot override elements otherwise | |
#then make sure we only trim one axis, e.g. strong vignette | |
#can cause detection of black bars on both sides | |
if y1 > x1: | |
box[0] = 0 | |
box[2] = im.size[0] | |
else: | |
box[1] = 0 | |
box[3] = im.size[1] | |
cropped = im.crop(tuple(box)) | |
print(filepath, im.format, im.mode) | |
print("cropping: ", im.size, "->", cropped.size) | |
cropped.save(filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment