labelColor.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import PIL.Image
  2. import numpy as np
  3. def rgb2hsv(rgb):
  4. # type: (np.ndarray) -> np.ndarray
  5. """Convert rgb to hsv.
  6. Parameters
  7. ----------
  8. rgb: numpy.ndarray, (H, W, 3), np.uint8
  9. Input rgb image.
  10. Returns
  11. -------
  12. hsv: numpy.ndarray, (H, W, 3), np.uint8
  13. Output hsv image.
  14. """
  15. hsv = PIL.Image.fromarray(rgb, mode="RGB")
  16. hsv = hsv.convert("HSV")
  17. hsv = np.array(hsv)
  18. return hsv
  19. def hsv2rgb(hsv):
  20. # type: (np.ndarray) -> np.ndarray
  21. """Convert hsv to rgb.
  22. Parameters
  23. ----------
  24. hsv: numpy.ndarray, (H, W, 3), np.uint8
  25. Input hsv image.
  26. Returns
  27. -------
  28. rgb: numpy.ndarray, (H, W, 3), np.uint8
  29. Output rgb image.
  30. """
  31. rgb = PIL.Image.fromarray(hsv, mode="HSV")
  32. rgb = rgb.convert("RGB")
  33. rgb = np.array(rgb)
  34. return rgb
  35. def label_colormap(n_label=256, value=None):
  36. """Label colormap.
  37. Parameters
  38. ----------
  39. n_label: int
  40. Number of labels (default: 256).
  41. value: float or int
  42. Value scale or value of label color in HSV space.
  43. Returns
  44. -------
  45. cmap: numpy.ndarray, (N, 3), numpy.uint8
  46. Label id to colormap.
  47. """
  48. def bitget(byteval, idx):
  49. return (byteval & (1 << idx)) != 0
  50. cmap = np.zeros((n_label, 3), dtype=np.uint8)
  51. for i in range(0, n_label):
  52. id = i
  53. r, g, b = 0, 0, 0
  54. for j in range(0, 8):
  55. r = np.bitwise_or(r, (bitget(id, 0) << 7 - j))
  56. g = np.bitwise_or(g, (bitget(id, 1) << 7 - j))
  57. b = np.bitwise_or(b, (bitget(id, 2) << 7 - j))
  58. id = id >> 3
  59. cmap[i, 0] = r
  60. cmap[i, 1] = g
  61. cmap[i, 2] = b
  62. if value is not None:
  63. hsv = rgb2hsv(cmap.reshape(1, -1, 3))
  64. if isinstance(value, float):
  65. hsv[:, 1:, 2] = hsv[:, 1:, 2].astype(float) * value
  66. else:
  67. assert isinstance(value, int)
  68. hsv[:, 1:, 2] = value
  69. cmap = hsv2rgb(hsv).reshape(-1, 3)
  70. return cmap