Created
July 21, 2020 20:25
-
-
Save antunesleo/af82334aac8e66ad94ff6ff5ccddc826 to your computer and use it in GitHub Desktop.
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
def crop_image_borders(image_path): | |
image = Image.open(image_path) | |
image.load() | |
ndarray_image = np.asarray(image) | |
ndarray_image_mask = ndarray_image.max(axis=2) | |
non_empty_columns = np.where(ndarray_image_mask.max(axis=0) > 0)[0] | |
non_empty_rows = np.where(ndarray_image_mask.max(axis=1) > 0)[0] | |
image_bbox = (min(non_empty_rows), max(non_empty_rows), | |
min(non_empty_columns), max(non_empty_columns)) | |
cropped_ndarray_image = ndarray_image[image_bbox[0]:image_bbox[1] + 1, | |
image_bbox[2]:image_bbox[3] + 1, :] | |
cropped_image = Image.fromarray(cropped_ndarray_image) | |
cropped_image.save(image_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment