centerArrayImage.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. def pad_image(img, pad_t, pad_r, pad_b, pad_l):
  2. """Add padding of zeroes to an image.
  3. Add padding to an array image.
  4. :param img:
  5. :param pad_t:
  6. :param pad_r:
  7. :param pad_b:
  8. :param pad_l:
  9. """
  10. height, width = img.shape
  11. # Adding padding to the left side.
  12. pad_left = np.zeros((height, pad_l), dtype = np.int)
  13. img = np.concatenate((pad_left, img), axis = 1)
  14. # Adding padding to the top.
  15. pad_up = np.zeros((pad_t, pad_l + width))
  16. img = np.concatenate((pad_up, img), axis = 0)
  17. # Adding padding to the right.
  18. pad_right = np.zeros((height + pad_t, pad_r))
  19. img = np.concatenate((img, pad_right), axis = 1)
  20. # Adding padding to the bottom
  21. pad_bottom = np.zeros((pad_b, pad_l + width + pad_r))
  22. img = np.concatenate((img, pad_bottom), axis = 0)
  23. return img
  24. def center_image(img):
  25. """Return a centered image.
  26. :param img:
  27. """
  28. col_sum = np.where(np.sum(img, axis=0) > 0)
  29. row_sum = np.where(np.sum(img, axis=1) > 0)
  30. y1, y2 = row_sum[0][0], row_sum[0][-1]
  31. x1, x2 = col_sum[0][0], col_sum[0][-1]
  32. cropped_image = img[y1:y2, x1:x2]
  33. zero_axis_fill = (images[0].shape[0] - cropped_image.shape[0])
  34. one_axis_fill = (images[0].shape[1] - cropped_image.shape[1])
  35. top = zero_axis_fill / 2
  36. bottom = zero_axis_fill - top
  37. left = one_axis_fill / 2
  38. right = one_axis_fill - left
  39. padded_image = pad_image(cropped_image, top, left, bottom, right)
  40. return padded_image