color_histogram.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. '''
  3. Video histogram sample to show live histogram of video
  4. Keys:
  5. ESC - exit
  6. '''
  7. # Python 2/3 compatibility
  8. from __future__ import print_function
  9. import numpy as np
  10. import cv2 as cv
  11. # built-in modules
  12. import sys
  13. # local modules
  14. import video
  15. class App():
  16. def set_scale(self, val):
  17. self.hist_scale = val
  18. def run(self):
  19. hsv_map = np.zeros((180, 256, 3), np.uint8)
  20. h, s = np.indices(hsv_map.shape[:2])
  21. hsv_map[:,:,0] = h
  22. hsv_map[:,:,1] = s
  23. hsv_map[:,:,2] = 255
  24. hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
  25. cv.imshow('hsv_map', hsv_map)
  26. cv.namedWindow('hist', 0)
  27. self.hist_scale = 10
  28. cv.createTrackbar('scale', 'hist', self.hist_scale, 32, self.set_scale)
  29. try:
  30. fn = sys.argv[1]
  31. except:
  32. fn = 0
  33. cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05')
  34. while True:
  35. _flag, frame = cam.read()
  36. cv.imshow('camera', frame)
  37. small = cv.pyrDown(frame)
  38. hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
  39. dark = hsv[...,2] < 32
  40. hsv[dark] = 0
  41. h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
  42. h = np.clip(h*0.005*self.hist_scale, 0, 1)
  43. vis = hsv_map*h[:,:,np.newaxis] / 255.0
  44. cv.imshow('hist', vis)
  45. ch = cv.waitKey(1)
  46. if ch == 27:
  47. break
  48. print('Done')
  49. if __name__ == '__main__':
  50. print(__doc__)
  51. App().run()
  52. cv.destroyAllWindows()