Skip to content

Instantly share code, notes, and snippets.

@lorenzob
Created September 19, 2019 10:35
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 lorenzob/887869d4e5ef02a06f1f75cb339705d5 to your computer and use it in GitHub Desktop.
Save lorenzob/887869d4e5ef02a06f1f75cb339705d5 to your computer and use it in GitHub Desktop.
def trim_border(base_img, th=255, m=(1, 1, 1, 1)):
if not isinstance(m, tuple):
m = (m, m, m, m)
if base_img.size == 0:
return base_img, [0,0,0,0]
img = base_img
# trim without threshold
# white_rows = np.all(white_pixels, axis=1)
# white_cols = np.all(white_pixels, axis=0)
white_pixels = img >= th
white_rows = np.count_nonzero(white_pixels, axis=1) >= img.shape[1]
white_cols = np.count_nonzero(white_pixels, axis=0) >= img.shape[0]
good_rows = np.where(white_rows == False)[0]
good_cols = np.where(white_cols == False)[0]
# empty result
if len(good_rows) == 0 or len(good_cols) == 0:
if len(base_img.shape) == 2:
return base_img[0:1, 0:1]
else:
return base_img[0:1, 0:1, :]
y_min = good_rows[0] if len(good_rows) > 0 else 0
y_max = good_rows[-1] if len(good_rows) > 0 else 0
x_min = good_cols[0] if len(good_cols) > 0 else 0
x_max = good_cols[-1] if len(good_cols) > 0 else 0
# add margin
h, w, *_ = base_img.shape
y_min = max(0, y_min - m[0])
y_max = min(h, y_max + m[1] + 1)
x_min = max(0, x_min - m[2])
x_max = min(w, x_max + m[3] + 1)
return base_img[y_min:y_max, x_min:x_max]
if __name__ == '__main__':
img_name = sys.argv[1]
img = cv2.imread(img_name, 0)
trimmed = trim_border(img, th=250, m=2)
cv2.imshow("in", img)
cv2.imshow("aaa", trimmed)
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment