misc.py 6.7 KB

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