misc.py 6.1 KB

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