-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcam based heart beat.py
180 lines (128 loc) · 4.72 KB
/
webcam based heart beat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import cv2
import sys
# Helper Methods
#https://hbenbel.github.io/blog/evm/
#http://people.csail.mit.edu/mrub/evm/
def buildGauss(frame, levels):
pyramid = [frame]
for level in range(levels):
frame = cv2.pyrDown(frame)
pyramid.append(frame)
return pyramid
def reconstructFrame(pyramid, index, levels):
filteredFrame = pyramid[index]
for level in range(levels):
filteredFrame = cv2.pyrUp(filteredFrame)
filteredFrame = filteredFrame[:videoHeight, :videoWidth]
return filteredFrame
# Webcam Parameters
webcam = None
if len(sys.argv) == 2:
webcam = cv2.VideoCapture(sys.argv[1])
else:
webcam = cv2.VideoCapture(0)
realWidth = 320
realHeight = 240
videoWidth = 160
videoHeight = 120
videoChannels = 3
videoFrameRate = 15
webcam.set(3, realWidth)
webcam.set(4, realHeight)
# Output Videos
#fourcc: 4-character code of codec used to compress the frames
if len(sys.argv) != 2:
originalVideoFilename = "original.mov"
originalVideoWriter = cv2.VideoWriter()
originalVideoWriter.open(originalVideoFilename, cv2.VideoWriter_fourcc('j', 'p', 'e', 'g'), videoFrameRate, (realWidth, realHeight), True)
outputVideoFilename = "output.mov"
outputVideoWriter = cv2.VideoWriter()
outputVideoWriter.open(outputVideoFilename, cv2.VideoWriter_fourcc('j', 'p', 'e', 'g'), videoFrameRate, (realWidth, realHeight), True)
# Color Magnification Parameters
levels = 3
alpha = 170
minFrequency = 1.0
maxFrequency = 2.0
bufferSize = 150
bufferIndex = 0
# Output Display Parameters
font = cv2.FONT_HERSHEY_SIMPLEX
loadingTextLocation = (100, 100)
bpmTextLocation = (videoWidth//2 + 5, 30)
fontScale = 1
fontColor = (0,255,0)
lineType = 2
boxColor = (0, 255, 0)
boxWeight = 3
# Initialize Eulerian video magnification(Gaussian Pyramid)
firstFrame = np.zeros((videoHeight, videoWidth, videoChannels))
firstGauss = buildGauss(firstFrame, levels+1)[levels]
videoGauss = np.zeros((bufferSize, firstGauss.shape[0], firstGauss.shape[1], videoChannels))
fourierTransformAvg = np.zeros((bufferSize))
# Bandpass Filter for Specified Frequencies
frequencies = (1.0*videoFrameRate) * np.arange(bufferSize) / (1.0*bufferSize)
mask = (frequencies >= minFrequency) & (frequencies <= maxFrequency)
# Heart Rate Calculation Variables
bpmCalculationFrequency = 15
bpmBufferIndex = 0
bpmBufferSize = 10
bpmBuffer = np.zeros((bpmBufferSize))
i = 0
while (True):
ret, frame = webcam.read()
if ret == False:
break
if len(sys.argv) != 2:
originalFrame = frame.copy()
originalVideoWriter.write(originalFrame)
detectionFrame = frame[videoHeight//2:realHeight-videoHeight//2, videoWidth//2:realWidth-videoWidth//2, :]
# Construct Gaussian Pyramid and convert image to frequency form using FFT
videoGauss[bufferIndex] = buildGauss(detectionFrame, levels+1)[levels]
fourierTransform = np.fft.fft(videoGauss, axis=0)
# Bandpass Filter
fourierTransform[mask == False] = 0
# Calculate BPM
#To convert the frequency of the peak to bpm multiply by 60.
if bufferIndex % bpmCalculationFrequency == 0:
i = i + 1
for buf in range(bufferSize):
fourierTransformAvg[buf] = np.real(fourierTransform[buf]).mean()
hz = frequencies[np.argmax(fourierTransformAvg)]
bpm = 60.0 * hz
bpmBuffer[bpmBufferIndex] = bpm
bpmBufferIndex = (bpmBufferIndex + 1) % bpmBufferSize
# Amplify
#apply the Inverse Fourier Transform to retrieve a filtered image
#Magnify the colors obtained using alpha
filtered = np.real(np.fft.ifft(fourierTransform, axis=0))
filtered = filtered * alpha
# Reconstruct Resulting Frame
filteredFrame = reconstructFrame(filtered, bufferIndex, levels)
outputFrame = detectionFrame + filteredFrame
outputFrame = cv2.convertScaleAbs(outputFrame)
bufferIndex = (bufferIndex + 1) % bufferSize
frame[videoHeight//2:realHeight-videoHeight//2, videoWidth//2:realWidth-videoWidth//2, :] = outputFrame
cv2.rectangle(frame, (videoWidth//2 , videoHeight//2), (realWidth-videoWidth//2, realHeight-videoHeight//2), boxColor, boxWeight)
if i > bpmBufferSize:
cv2.putText(frame, "BPM: %d" % bpmBuffer.mean(), bpmTextLocation, font, fontScale, fontColor, lineType)
else:
cv2.putText(frame, "Calculating BPM...", loadingTextLocation, font, fontScale, fontColor, lineType)
outputVideoWriter.write(frame)
if len(sys.argv) != 2:
cv2.imshow("Webcam Heart Rate Monitor", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
webcam.release()
cv2.destroyAllWindows()
outputVideoWriter.release()
if len(sys.argv) != 2:
originalVideoWriter.release()
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]: