Last active
December 18, 2019 04:10
-
-
Save edison7500/c2957ff905afcda68334f3bf8d064d9d to your computer and use it in GitHub Desktop.
利用 numpy 删除图片白色边框
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
#!/usr/bin/env python | |
# coding: utf-8 | |
import numpy as np | |
from PIL import Image | |
# 得到需要裁剪边框的距离 | |
def remove_image_rim(np_img, boundary=0.8): | |
_np_img = np_img | |
h, w, c = np_img.shape | |
endpoint = 0 | |
half_h = h - int(h / 2) | |
for i, row in enumerate(np_img[half_h:h]): | |
light = np.count_nonzero(row >= [250, 250, 250]) | |
dark = np.count_nonzero(row <= [5, 5, 5]) | |
if light / w > boundary or dark / w > boundary: | |
endpoint = i | |
break | |
if endpoint == 0: | |
return np_img | |
rim = range(endpoint + half_h, h) | |
np_img = np.delete(np_img, rim, axis=0) | |
return np_img | |
im = Image.open("photo.jpg") | |
np_img = np.array(im) | |
np_img = remove_image_rim(np_img) | |
# 旋转至 90 度 | |
np_img = np.rot90(np_img) | |
np_img = remove_image_rim(np_img) | |
# 旋转至 180 度 | |
np_img = np.rot90(np_img) | |
np_img = remove_image_rim(np_img) | |
# 旋转至 270 度 | |
np_img = np.rot90(np_img) | |
np_img = remove_image_rim(np_img) | |
# 恢复到初始位置 | |
np_img = np.rot90(np_img) | |
im = Image.fromarray(np_img) | |
im.save("photo2.jpg") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment