misc.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import os
  2. import cv2
  3. import khandy
  4. import numpy as np
  5. from PIL import Image
  6. def imread_pil(filename, to_mode='RGB'):
  7. with open(filename, 'rb') as f:
  8. img = Image.open(f)
  9. if to_mode is None:
  10. return img
  11. else:
  12. return img.convert(to_mode)
  13. def imread_cv(filename, flags=-1):
  14. """Improvement on cv2.imread, make it support filename including chinese character.
  15. """
  16. try:
  17. return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), flags)
  18. except Exception as e:
  19. return None
  20. def imwrite_cv(filename, image):
  21. """Improvement on cv2.imwrite, make it support filename including chinese character.
  22. """
  23. cv2.imencode(os.path.splitext(filename)[-1], image)[1].tofile(filename)
  24. def normalize_image_dtype(image, keep_num_channels=False):
  25. """Normalize image dtype to uint8 (usually for visualization).
  26. Args:
  27. image : ndarray
  28. Input image.
  29. keep_num_channels : bool, optional
  30. If this is set to True, the result is an array which has
  31. the same shape as input image, otherwise the result is
  32. an array whose channels number is 3.
  33. Returns:
  34. out: ndarray
  35. Image whose dtype is np.uint8.
  36. """
  37. assert (image.ndim == 3 and image.shape[-1] in [1, 3]) or (image.ndim == 2)
  38. image = image.astype(np.float32)
  39. image = khandy.minmax_normalize(image, axis=None, copy=False)
  40. image = np.array(image * 255, dtype=np.uint8)
  41. if not keep_num_channels:
  42. if image.ndim == 2:
  43. image = np.expand_dims(image, -1)
  44. if image.shape[-1] == 1:
  45. image = np.tile(image, (1,1,3))
  46. return image
  47. def stack_image_list(image_list, dtype=np.float32):
  48. """Join a sequence of image along a new axis before first axis.
  49. References:
  50. `im_list_to_blob` in `py-faster-rcnn-master/lib/utils/blob.py`
  51. """
  52. assert isinstance(image_list, (tuple, list))
  53. max_dimension = np.array([image.ndim for image in image_list]).max()
  54. assert max_dimension in [2, 3]
  55. max_shape = np.array([image.shape[:2] for image in image_list]).max(axis=0)
  56. num_channels = []
  57. for image in image_list:
  58. if image.ndim == 2:
  59. num_channels.append(1)
  60. else:
  61. num_channels.append(image.shape[-1])
  62. assert len(set(num_channels) - set([1])) in [0, 1]
  63. max_num_channels = np.max(num_channels)
  64. blob = np.empty((len(image_list), max_shape[0], max_shape[1], max_num_channels), dtype=dtype)
  65. for k, image in enumerate(image_list):
  66. blob[k, :image.shape[0], :image.shape[1], :] = np.atleast_3d(image).astype(dtype, copy=False)
  67. if max_dimension == 2:
  68. blob = np.squeeze(blob, axis=-1)
  69. return blob
  70. def is_numpy_image(image):
  71. return isinstance(image, np.ndarray) and image.ndim in {2, 3}
  72. def is_gray_image(image, tol=3):
  73. assert is_numpy_image(image)
  74. if image.ndim == 2:
  75. return True
  76. elif image.ndim == 3:
  77. num_channels = image.shape[-1]
  78. if num_channels == 1:
  79. return True
  80. elif num_channels == 4:
  81. rgb = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
  82. gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
  83. gray3 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  84. mae = np.mean(cv2.absdiff(rgb, gray3))
  85. return mae <= tol
  86. elif num_channels == 3:
  87. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  88. gray3 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  89. mae = np.mean(cv2.absdiff(image, gray3))
  90. return mae <= tol
  91. else:
  92. return False
  93. else:
  94. return False