Last active
March 15, 2021 18:37
-
-
Save blindstitch/9e64ed5a33e1bb78e1590ff31fdb88db to your computer and use it in GitHub Desktop.
Crop white borders from images - numpy, pillow
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
import numpy | |
from PIL import Image | |
from matplotlib.colors import rgb_to_hsv | |
minions = Image.open('minons_test_autocrop_lossy.jpg') | |
def autocrop(image,thresh_v=255,thresh_s=.01,pad=0): | |
a = numpy.asarray(image) | |
hsv = rgb_to_hsv(a.take([0,1,2],axis=2)) | |
white = (hsv.take(1,axis=2) <= thresh_s) * (hsv.take(2,axis=2) >= thresh_v) | |
nonempty_cols = numpy.where(white.min(axis=0) == False)[0] | |
nonempty_rows = numpy.where(white.min(axis=1) == False)[0] | |
bbox = (min(nonempty_rows)-pad, max(nonempty_rows)+pad, min(nonempty_cols)-pad, max(nonempty_cols)+pad) | |
cropped = a[bbox[0]:bbox[1] + 2, bbox[2]:bbox[3] + 0, :] | |
return Image.fromarray(cropped) | |
out = autocrop(minions,thresh_v=240) | |
from matplotlib import pyplot as plt | |
plt.imshow(out) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment