Skip to content

Instantly share code, notes, and snippets.

@antunesleo
Created July 21, 2020 20:25
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 antunesleo/af82334aac8e66ad94ff6ff5ccddc826 to your computer and use it in GitHub Desktop.
Save antunesleo/af82334aac8e66ad94ff6ff5ccddc826 to your computer and use it in GitHub Desktop.
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