Brak opisu

histogram_extraction.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Jul 20 10:28:47 2017
  5. @author: alexdrake
  6. """
  7. import cv2
  8. import numpy as np
  9. from matplotlib import pyplot as plt
  10. import os
  11. # get working directory
  12. loc = os.path.abspath('')
  13. cap = cv2.VideoCapture(loc+'/trafficCounter/inputs/625_201709301058.mp4')
  14. # get frame size
  15. w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  16. h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  17. # create a mask
  18. mask1 = np.zeros((h,w), np.uint8)
  19. mask1[188:258, 30:140] = 255
  20. mask2 = np.zeros((h,w), np.uint8)
  21. mask2[188:258, 190:260] = 255
  22. while(1):
  23. ret, frame = cap.read()
  24. if ret == True:
  25. # convert BGR to HSV
  26. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  27. # add mask to each frame
  28. frame1 = cv2.bitwise_and(frame, frame, mask=mask1)
  29. frame2 = cv2.bitwise_and(frame, frame, mask=mask2)
  30. #hist_full = cv2.calcHist([frame],[2],None,[256],[0, 256])
  31. hist_mask1 = cv2.calcHist([frame1],[2],mask1,[256],[50, 256])
  32. hist_mask2 = cv2.calcHist([frame2],[2],mask2,[256],[50, 256])
  33. # calculate summary stats
  34. stats = np.array([["Count",np.count_nonzero(hist_mask1)],
  35. ["Max",np.max(hist_mask1)],
  36. ["Mean",np.mean(hist_mask1)],
  37. ["Std",np.std(hist_mask1)],
  38. ["25%",np.percentile(hist_mask1,25)],
  39. ["50%",np.percentile(hist_mask1,50)],
  40. ["75%",np.percentile(hist_mask1,75)]])
  41. print(stats)
  42. # create plots
  43. plt.subplot(221), plt.imshow(frame1, 'gray')
  44. plt.subplot(222), plt.plot(hist_mask1)
  45. plt.xlim([0,256]), plt.ylim([0,300])
  46. plt.subplot(223), plt.imshow(frame2, 'gray')
  47. plt.subplot(224), plt.plot(hist_mask2)
  48. plt.xlim([0,256]), plt.ylim([0,300])
  49. # plot histogram
  50. plt.show()
  51. #out.write()
  52. if cv2.waitKey(1) & 0xFF == ord('q'):
  53. break
  54. else:
  55. break
  56. cv2.destroyAllWindows()
  57. cap.release()
  58. out.release()