g_diffuser_bot.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import cv2
  2. import numpy as np
  3. def expand_image(cv2_img, top: int, right: int, bottom: int, left: int):
  4. assert cv2_img.shape[2] == 3
  5. origin_h, origin_w = cv2_img.shape[:2]
  6. # TODO: which is better?
  7. # new_img = np.ones((new_height, new_width, 3), np.uint8) * 255
  8. new_img = cv2.copyMakeBorder(
  9. cv2_img, top, bottom, left, right, cv2.BORDER_REPLICATE
  10. )
  11. inner_padding_left = 0 if left > 0 else 0
  12. inner_padding_right = 0 if right > 0 else 0
  13. inner_padding_top = 0 if top > 0 else 0
  14. inner_padding_bottom = 0 if bottom > 0 else 0
  15. mask_image = np.zeros(
  16. (
  17. origin_h - inner_padding_top - inner_padding_bottom,
  18. origin_w - inner_padding_left - inner_padding_right,
  19. ),
  20. np.uint8,
  21. )
  22. mask_image = cv2.copyMakeBorder(
  23. mask_image,
  24. top + inner_padding_top,
  25. bottom + inner_padding_bottom,
  26. left + inner_padding_left,
  27. right + inner_padding_right,
  28. cv2.BORDER_CONSTANT,
  29. value=255,
  30. )
  31. # k = 2*int(min(origin_h, origin_w) // 6)+1
  32. # k = 7
  33. # mask_image = cv2.GaussianBlur(mask_image, (k, k), 0)
  34. return new_img, mask_image
  35. if __name__ == "__main__":
  36. from pathlib import Path
  37. current_dir = Path(__file__).parent.absolute().resolve()
  38. image_path = "/Users/cwq/code/github/IOPaint/iopaint/tests/bunny.jpeg"
  39. init_image = cv2.imread(str(image_path))
  40. init_image, mask_image = expand_image(
  41. init_image,
  42. top=0,
  43. right=0,
  44. bottom=0,
  45. left=100,
  46. softness=20,
  47. space=20,
  48. )
  49. print(mask_image.dtype, mask_image.min(), mask_image.max())
  50. print(init_image.dtype, init_image.min(), init_image.max())
  51. mask_image = mask_image.astype(np.uint8)
  52. init_image = init_image.astype(np.uint8)
  53. cv2.imwrite("expanded_image.png", init_image)
  54. cv2.imwrite("expanded_mask.png", mask_image)