misc.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import os
  2. from io import BytesIO
  3. import cv2
  4. import khandy
  5. import numpy as np
  6. from PIL import Image
  7. def imread_pil(file_or_buffer, to_mode='RGB', formats=None):
  8. try:
  9. if isinstance(file_or_buffer, bytes):
  10. buffer = BytesIO()
  11. buffer.write(file_or_buffer)
  12. buffer.seek(0)
  13. image = Image.open(buffer)
  14. elif hasattr(file_or_buffer, 'read'):
  15. image = Image.open(file_or_buffer)
  16. else:
  17. # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
  18. with open(file_or_buffer, 'rb') as f:
  19. image = Image.open(f)
  20. return image
  21. except Exception as e:
  22. print(e)
  23. return None
  24. def imread_cv(file_or_buffer, flags=-1):
  25. """Improvement on cv2.imread, make it support filename including chinese character.
  26. """
  27. try:
  28. if isinstance(file_or_buffer, bytes):
  29. return cv2.imdecode(np.frombuffer(file_or_buffer, dtype=np.uint8), flags)
  30. else:
  31. # support type: file or str or Path
  32. return cv2.imdecode(np.fromfile(file_or_buffer, dtype=np.uint8), flags)
  33. except Exception as e:
  34. print(e)
  35. return None
  36. def imwrite_cv(filename, image, params=None):
  37. """Improvement on cv2.imwrite, make it support filename including chinese character.
  38. """
  39. cv2.imencode(os.path.splitext(filename)[-1], image, params)[1].tofile(filename)
  40. def normalize_image_dtype(image, keep_num_channels=False):
  41. """Normalize image dtype to uint8 (usually for visualization).
  42. Args:
  43. image : ndarray
  44. Input image.
  45. keep_num_channels : bool, optional
  46. If this is set to True, the result is an array which has
  47. the same shape as input image, otherwise the result is
  48. an array whose channels number is 3.
  49. Returns:
  50. out: ndarray
  51. Image whose dtype is np.uint8.
  52. """
  53. assert (image.ndim == 3 and image.shape[-1] in [1, 3]) or (image.ndim == 2)
  54. image = image.astype(np.float32)
  55. image = khandy.minmax_normalize(image, axis=None, copy=False)
  56. image = np.array(image * 255, dtype=np.uint8)
  57. if not keep_num_channels:
  58. if image.ndim == 2:
  59. image = np.expand_dims(image, -1)
  60. if image.shape[-1] == 1:
  61. image = np.tile(image, (1,1,3))
  62. return image
  63. def normalize_image_shape(image, swap_rb=False):
  64. """Normalize image shape to (h, w, 3).
  65. Args:
  66. image : ndarray
  67. Input image.
  68. swap_rb : bool, optional
  69. whether swap red and blue channel or not
  70. Returns:
  71. out: ndarray
  72. Image whose shape is (h, w, 3).
  73. """
  74. if image.ndim == 2:
  75. image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
  76. elif image.ndim == 3:
  77. num_channels = image.shape[-1]
  78. if num_channels == 1:
  79. image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
  80. elif num_channels == 3:
  81. if swap_rb:
  82. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  83. elif num_channels == 4:
  84. if swap_rb:
  85. image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGB)
  86. else:
  87. image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
  88. else:
  89. raise ValueError('Unsupported!')
  90. else:
  91. raise ValueError('Unsupported!')
  92. return image
  93. def stack_image_list(image_list, dtype=np.float32):
  94. """Join a sequence of image along a new axis before first axis.
  95. References:
  96. `im_list_to_blob` in `py-faster-rcnn-master/lib/utils/blob.py`
  97. """
  98. assert isinstance(image_list, (tuple, list))
  99. max_dimension = np.array([image.ndim for image in image_list]).max()
  100. assert max_dimension in [2, 3]
  101. max_shape = np.array([image.shape[:2] for image in image_list]).max(axis=0)
  102. num_channels = []
  103. for image in image_list:
  104. if image.ndim == 2:
  105. num_channels.append(1)
  106. else:
  107. num_channels.append(image.shape[-1])
  108. assert len(set(num_channels) - set([1])) in [0, 1]
  109. max_num_channels = np.max(num_channels)
  110. blob = np.empty((len(image_list), max_shape[0], max_shape[1], max_num_channels), dtype=dtype)
  111. for k, image in enumerate(image_list):
  112. blob[k, :image.shape[0], :image.shape[1], :] = np.atleast_3d(image).astype(dtype, copy=False)
  113. if max_dimension == 2:
  114. blob = np.squeeze(blob, axis=-1)
  115. return blob
  116. def is_numpy_image(image):
  117. return isinstance(image, np.ndarray) and image.ndim in {2, 3}
  118. def is_gray_image(image, tol=3):
  119. assert is_numpy_image(image)
  120. if image.ndim == 2:
  121. return True
  122. elif image.ndim == 3:
  123. num_channels = image.shape[-1]
  124. if num_channels == 1:
  125. return True
  126. elif num_channels == 4:
  127. rgb = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
  128. gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
  129. gray3 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  130. mae = np.mean(cv2.absdiff(rgb, gray3))
  131. return mae <= tol
  132. elif num_channels == 3:
  133. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  134. gray3 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  135. mae = np.mean(cv2.absdiff(image, gray3))
  136. return mae <= tol
  137. else:
  138. return False
  139. else:
  140. return False