Skip to content

Instantly share code, notes, and snippets.

@sharkdeng
Created November 2, 2020 05:56
Show Gist options
  • Save sharkdeng/f3f2b4dd8d2b6a78f010c548624bcc3d to your computer and use it in GitHub Desktop.
Save sharkdeng/f3f2b4dd8d2b6a78f010c548624bcc3d to your computer and use it in GitHub Desktop.
crop white background of an image
def crop_white(image: np.ndarray, value: int = 255) -> np.ndarray:
assert image.shape[2] == 3
assert image.dtype == np.uint8
ys, = (image.min((1, 2)) < value).nonzero()
xs, = (image.min(0).min(1) < value).nonzero()
if len(xs) == 0 or len(ys) == 0:
return image
return image[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment