Advertisement
Skylighty

bpms

Nov 20th, 2020
973
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import cv2
  4.  
  5. # Declare means array
  6. means = []
  7.  
  8. # Declare VideoCapture feature
  9. cap = cv2.VideoCapture("sample8.mp4")
  10.  
  11. # Loop untill the end of the video - frame by frame operations
  12. while (cap.isOpened()):
  13.     ret, frame = cap.read()
  14.     if not ret:
  15.         break
  16.  
  17.     # Extract shape from frame
  18.     (x, y, colors) = frame.shape
  19.  
  20.     # Slicing 350x350 square from the center
  21.     x1 = int((x / 2) - 175)
  22.     x2 = int((x / 2) + 175)
  23.     y1 = int((y / 2) - 175)
  24.     y2 = int((y / 2) + 175)
  25.     square = frame[y1:y2, x1:x2, 0]
  26.  
  27.     # Compute the mean of values in our square and add it to list
  28.     mean = np.mean(square, dtype=np.float64)
  29.     means.append(mean)
  30.  
  31. cap.release()
  32. cv2.destroyAllWindows()
  33.  
  34. # Filtering
  35. filter = [-0.02286961, -0.06362756,  0.57310236,  0.57310236, -0.06362756, -0.02286961]
  36. filtered = np.convolve(means, filter, 'same')
  37.  
  38. # FFT calculation
  39. fourier = abs(np.fft.fft(filtered))
  40. fourier[0] = 0
  41.  
  42. # Plot the means
  43. fig = plt.figure()
  44. plt.plot(filtered)
  45. plt.show()
  46.  
  47. # Raw data is ready, let's plot it:
  48. fig2 = plt.figure()
  49. plt.plot(fourier)
  50. plt.show()
  51.  
  52. # Variables necessary for calculations
  53. fps = 30.0
  54. framecount = len(filtered)
  55. fftmean = np.mean(fourier[:100])
  56. fftpos = []
  57.  
  58. # Create a list of indexes which contain high-value frequencies
  59. for i in range(100):
  60.     if fourier[i] > fftmean:
  61.         fftpos.append(i)
  62.  
  63. # Create a list of frequencies under previously specified indexes
  64. freqs = []
  65. for i in range(len(fftpos)-1):
  66.     freqs.append(round((fftpos[i]*fps)/framecount, 5))
  67.  
  68. # Calculate BPM value for previosuly calculated frequencies
  69. bpms = []
  70. for i in range(len(freqs)-1):
  71.     bpms.append(round(freqs[i]*60, 5))
  72.  
  73.  
  74. # Output - write results to text file
  75. file = open('bpms.txt', 'w')
  76. file.write('FFT pos         Freq[Hz]         BPM\n')
  77. for i in range(len(freqs)-1):
  78.     file.write(str(fftpos[i]) + '               ' + str(freqs[i]) + '             ' + str(bpms[i])+'\n')
  79. try:
  80.     file.close()
  81.     print('File cotaining the results saved successfully')
  82. except:
  83.     print('An error has occured during saving a file')
  84.  
  85.  
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement