Skip to content

Instantly share code, notes, and snippets.

@zborowa
Last active August 29, 2015 14:22
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 zborowa/4d06fc46e6f3e5ded4c8 to your computer and use it in GitHub Desktop.
Save zborowa/4d06fc46e6f3e5ded4c8 to your computer and use it in GitHub Desktop.
Python center array image
def center_image(img):
"""Return a centered image.
:param img:
"""
col_sum = np.where(np.sum(img, axis=0) > 0)
row_sum = np.where(np.sum(img, axis=1) > 0)
y1, y2 = row_sum[0][0], row_sum[0][-1]
x1, x2 = col_sum[0][0], col_sum[0][-1]
cropped_image = img[y1:y2, x1:x2]
zero_axis_fill = (img.shape[0] - cropped_image.shape[0])
one_axis_fill = (img.shape[1] - cropped_image.shape[1])
top = zero_axis_fill / 2
bottom = zero_axis_fill - top
left = one_axis_fill / 2
right = one_axis_fill - left
padded_image = pad_image(cropped_image, top, left, bottom, right)
return padded_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment