color.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import cv2
  3. import numpy as np
  4. def get_bg(background, img_shape):
  5. # 1、纯色
  6. # 2、通道颜色
  7. # 3、图片
  8. bg = np.zeros(img_shape)
  9. if background is None:
  10. return None
  11. if os.path.exists(background):
  12. bg = cv2.imread(background)
  13. bg = cv2.resize(bg, (img_shape[1], img_shape[0]))
  14. elif background == 'r':
  15. bg[:, :, 2] = 255
  16. elif background == 'g':
  17. bg[:, :, 1] = 255
  18. elif background == 'b':
  19. bg[:, :, 0] = 255
  20. elif background == 'w':
  21. bg[:, :, :] = 255
  22. elif is_color_hex(background):
  23. r, g, b, _ = hex_to_rgb(background)
  24. bg[:, :, 2] = r
  25. bg[:, :, 1] = g
  26. bg[:, :, 0] = b
  27. else:
  28. return None
  29. return bg
  30. def is_color_hex(color: str):
  31. size = len(color)
  32. if color.startswith("#"):
  33. return size == 7 or size == 9
  34. return False
  35. def hex_to_rgb(color: str):
  36. if color.startswith("#"):
  37. color = color[1:len(color)]
  38. r = int(color[0:2], 16)
  39. g = int(color[2:4], 16)
  40. b = int(color[4:6], 16)
  41. a = 100
  42. if len(color) == 8:
  43. a = int(color[6:8], 16)
  44. return r, g, b, a