misc.py 6.4 KB

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