pre_process.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import colorsys
  2. import time
  3. import numpy as np
  4. import cv2
  5. def count_red_pixel(image_np, cnt=1000):
  6. # 红色像素计数
  7. start_time = time.time()
  8. image_hsv = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)
  9. # minus_1 = image_np[:, :, 2].astype('int32') - image_np[:, :, 0].astype('int32')
  10. # minus_2 = image_np[:, :, 2].astype('int32') - image_np[:, :, 1].astype('int32')
  11. # red_mask = (image_np[:, :, 2] >= 180) & (minus_1 >= 60) & (minus_2 >= 60)
  12. red_mask = ((image_hsv[:, :, 0] >= 0) & (image_hsv[:, :, 0] <= 10) | (image_hsv[:, :, 0] <= 180) & (image_hsv[:, :, 0] >= 156)) \
  13. & (image_hsv[:, :, 1] <= 255) & (image_hsv[:, :, 1] >= 43) \
  14. & (image_hsv[:, :, 2] <= 255) & (image_hsv[:, :, 2] >= 100)
  15. red_cnt = np.sum(red_mask != 0)
  16. print("red_cnt", red_cnt, time.time()-start_time)
  17. if red_cnt >= cnt:
  18. return True
  19. else:
  20. return False
  21. def get_classes(classes_path):
  22. """loads the classes"""
  23. with open(classes_path) as f:
  24. class_names = f.readlines()
  25. class_names = [c.strip() for c in class_names]
  26. return class_names
  27. def get_anchors(anchors_path):
  28. """loads the anchors from a file"""
  29. with open(anchors_path) as f:
  30. anchors = f.readline()
  31. anchors = [float(x) for x in anchors.split(',')]
  32. return np.array(anchors).reshape(-1, 2)
  33. def get_colors(number, bright=True):
  34. """
  35. Generate random colors for drawing bounding boxes.
  36. To get visually distinct colors, generate them in HSV space then
  37. convert to RGB.
  38. """
  39. if number <= 0:
  40. return []
  41. brightness = 1.0 if bright else 0.7
  42. hsv_tuples = [(x / number, 1., brightness)
  43. for x in range(number)]
  44. colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
  45. colors = list(
  46. map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
  47. colors))
  48. np.random.seed(10101) # Fixed seed for consistent colors across runs.
  49. np.random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.
  50. np.random.seed(None) # Reset seed to default.
  51. return colors