Always-on computer music
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

58 lignes
1.5KB

  1. import cv2
  2. import numpy as np
  3. import math
  4. import itertools as it
  5. DENSITY = 5
  6. RED = [0, 0, 255]
  7. N_COLORS = 3
  8. def draw_rectangle(frame, sp, ep):
  9. """ Draw a rectangle on the frame """
  10. return cv2.rectangle(frame, sp, ep, RED)
  11. def analyze_block(frame, sp, ep):
  12. """ Analyze a block """
  13. block = np.float32(frame[sp[1]:ep[1], sp[0]:ep[0], 0:3])
  14. block = block.reshape((-1, 3))
  15. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, .2)
  16. compactness, labels, palette = cv2.kmeans(block, N_COLORS, None, criteria,
  17. 2, cv2.KMEANS_RANDOM_CENTERS)
  18. unique, counts = np.unique(labels.flatten(), return_counts=True)
  19. for index, count in zip(unique, counts):
  20. print(index, count, palette[index])
  21. return frame
  22. def analyze(frame):
  23. """ Analyze the full frame """
  24. height, width, d = frame.shape
  25. n = DENSITY
  26. m = math.ceil(n * (height / width))
  27. dx = width / n
  28. dy = height / m
  29. for x, y in it.product(range(n), range(m)):
  30. sp = (int(x * dx), int(y * dy))
  31. ep = (int(x * dx + dx), int(y * dy + dy))
  32. frame = draw_rectangle(frame, sp, ep)
  33. frame = analyze_block(frame, sp, ep)
  34. return frame
  35. if __name__ == '__main__':
  36. camera = cv2.VideoCapture(0)
  37. while True:
  38. ret, frame = camera.read()
  39. frame = analyze(frame)
  40. cv2.imshow('Input', frame)
  41. c = cv2.waitKey(1)
  42. if c == 27:
  43. break
  44. camera.release()
  45. cv2.destroyAllWindows()