-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_pulse_temp.py
401 lines (338 loc) · 13.6 KB
/
get_pulse_temp.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""
--------Commands--------
Real-time: python get_pulse_video.py
python get_pulse_video.py --subject[name]
python get_pulse_video.py --subject[name] --init_temp[temperature]
Video: python get_pulse_video.py --video myvid.mp4
------------------------
"""
from lib.device import Camera, Video
from lib.processors_noopenmdao import findFaceGetPulse
from lib.interface import plotXY, imshow, waitKey, destroyWindow
from cv2 import moveWindow
import cv2
import argparse
import numpy as np
import datetime
import time
# TODO: work on serial port comms, if anyone asks for it
# from serial import Serial
import socket
import sys
import pandas as pd
import glob
import os
import csv
from BT import *
# from uploadFile import *
class getPulseApp(object):
"""
Python application that finds a face in a webcam stream, then isolates the
forehead.
Then the average green-light intensity in the forehead region is gathered
over time, and the detected person's pulse is estimated.
"""
def __init__(self, args):
# Imaging device - must be a connected camera (not an ip camera or mjpeg
# stream)
serial = args.serial
baud = args.baud
video = args.video
self.Tx = False
self.environment = []
self.ser = None
self.kill = False
self.vidname = ""
self.send_serial = False
self.send_udp = False
self.question_number = "-1"
if serial:
self.send_serial = True
if not baud:
baud = 9600
else:
baud = int(baud)
self.serial = Serial(port=serial, baudrate=baud)
udp = args.udp
if udp:
self.send_udp = True
if ":" not in udp:
ip = udp
port = 5005
else:
ip, port = udp.split(":")
port = int(port)
self.udp = (ip, port)
self.sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
if video:
self.vidname = video
self.cameras = []
self.selected_cam = 0
if args.url is not None:
camera = Camera(camera=args.url)
self.cameras.append(camera)
elif args.video_dir is None:
# Real-time for camera=0, read from one video
# first camera by default
camera = Camera(camera=0, vid=self.vidname)
if camera.valid or not len(self.cameras):
self.cameras.append(camera)
else:
print('Error: No camera was found')
else:
# read all videos from a directory in a sequence
self.video_names = glob.glob(args.video_dir + '/*.mp4')
self.video_names.sort()
for i in range(len(self.video_names)):
# start from the first video
camera = Video(vid=self.video_names[i])
if camera.valid or not len(self.cameras):
self.cameras.append(camera)
self.w, self.h = 0, 0
# self.record = False
self.sz = (int(self.cameras[self.selected_cam].cam.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self.cameras[self.selected_cam].cam.get(cv2.CAP_PROP_FRAME_HEIGHT)))
self.fourcc = cv2.VideoWriter_fourcc(*'MP4V')
self.fps = 25
self.q = 0
# self.out = None
self.pressed = 0
# Containerized analysis of recieved image frames (an openMDAO assembly)
# is defined next.
# This assembly is designed to handle all image & signal analysis,
# such as face detection, forehead isolation, time series collection,
# heart-beat detection, etc.
# Basically, everything that isn't communication
# to the camera device or part of the GUI
self.processor = findFaceGetPulse(bpm_limits=[50, 160],
data_spike_limit=2500.,
face_detector_smoothness=10.)
self.processor.init_temp = args.init_temp
# Init parameters for the cardiac data plot
self.bpm_plot = False
self.plot_title = "Data display - raw signal (top) and PSD (bottom)"
# Maps keystrokes to specified methods
# (A GUI window must have focus for these to work)
self.key_controls = {"s": self.toggle_search,
"d": self.toggle_display_plot,
"c": self.toggle_cam,
# "g": self.start_record,
# "f": self.stop_record
}
def toggle_cam(self):
if len(self.cameras) > 1:
self.processor.find_faces = True
self.bpm_plot = False
destroyWindow(self.plot_title)
self.selected_cam += 1
self.selected_cam = self.selected_cam % len(self.cameras)
# def start_record(self):
# self.processor.start_record = True
# # self.processor.bpms = []
# # self.processor.temps = []
# # self.processor.ttimes = []
# # self.processor.t1 = time.time()
# self.record = True
# # self.out = cv2.VideoWriter(args.subject + '_' + str(self.q) + '.mp4', self.fourcc, self.fps, self.sz)
# # self.q += 1
# def stop_record(self):
# """
# Writes current data to a csv file
# """
# # fn = str(datetime.datetime.now())
# # fn = fn.replace(":", "_").replace(".", "_")
# fn = os.path.join(args.save_dir, args.subject,
# args.subject + '_recordings')
# # fn = os.path.join(args.save_dir, args.subject, args.subject + '_' + self.question_number)
# data = np.vstack(
# (self.processor.ttimes[::10], self.processor.bpms[::10], self.processor.temps[::10])).T
# df = pd.DataFrame(data=data, columns=['Time', 'BPM', 'TEMP'])
# df.to_csv(fn + ".csv")
# self.processor.start_record = False
# if self.record == True:
# self.record = False
# # self.out.release()
# # print("Saving video: " + fn + '.mp4')
def toggle_search(self):
"""
Toggles a motion lock on the processor's face detection component.
Locking the forehead location in place significantly improves
data quality, once a forehead has been sucessfully isolated.
"""
# state = self.processor.find_faces.toggle()
state = self.processor.find_faces_toggle()
print("face detection lock =", not state)
def toggle_display_plot(self):
"""
Toggles the data display.
"""
if self.bpm_plot:
print("bpm plot disabled")
self.bpm_plot = False
destroyWindow(self.plot_title)
else:
print("bpm plot enabled")
if self.processor.find_faces:
self.toggle_search()
self.bpm_plot = True
self.make_bpm_plot()
moveWindow(self.plot_title, self.w, 0)
def make_bpm_plot(self):
"""
Creates and/or updates the data display
"""
plotXY([[self.processor.ttimes,
self.processor.bpms],
[self.processor.freqs,
self.processor.fft]],
labels=[False, True],
showmax=[False, "bpm"],
label_ndigits=[0, 0],
showmax_digits=[0, 1],
skip=[3, 3],
name=self.plot_title,
bg=self.processor.slices[0])
def key_handler(self):
"""
Handle keystrokes, as set at the bottom of __init__()
A plotting or camera frame window must have focus for keypresses to be
detected.
"""
self.pressed = waitKey(10) & 255 # wait for keypress for 10 ms
if self.pressed == 27: # exit program on 'esc'
print("Exiting")
# if self.record:
# self.stop_record()
# self.record = False
for cam in self.cameras:
cam.cam.release()
if self.send_serial:
self.serial.close()
sys.exit()
for key in self.key_controls.keys():
if chr(self.pressed) == key:
self.key_controls[key]()
# def recordRx(self, read):
# self.environment.append(read)
# if ???:
# data = np.vstack(self.environment[::2], self.environment[1::2]).T
# df = pd.DataFrame(data=data, columns=['temperature', 'humidity'])
# df.to_csv("environment.csv")
# uploadFile("environment.csv")
def main_loop(self):
"""
Single iteration of the application's main loop.
"""
# Get current image frame from the camera
if len(self.processor.temps) and self.Tx:
self.ser.SerialWrite(self.processor.temps[-1])
read = self.ser.SerialReadString()
self.Tx = False
# recordRx(read)
try:
glob_time = self.processor.ttimes[-1]
glob_bpm = self.processor.bpms[-1]
glob_temp = self.processor.temps[-1]
np.save("body_data.npy", np.array(
[glob_time, glob_bpm, glob_temp]))
except:
pass
try:
glob_env_temp = read.split('_')[0]
glob_env_humid = read.split('_')[1]
print('receiving env temp: ', glob_env_temp)
print('receiving env humid: ', glob_env_humid)
np.save('env_data.npy', np.array(
[glob_env_temp, glob_env_humid]))
except:
pass
frame = self.cameras[self.selected_cam].get_frame()
if frame is None:
if args.video_dir is None:
self.kill = True
return
else:
pos = self.video_names[self.selected_cam].find("_q")
self.question_number = self.video_names[self.selected_cam][pos + 2:pos + 4]
self.stop_record()
# Change to the next video (in the next camera)
self.selected_cam += 1
if self.selected_cam >= len(self.video_names):
self.kill = True
return
self.cameras[self.selected_cam].reset_video()
print('Changing to next video...{}'.format(
self.video_names[self.selected_cam]))
self.start_record()
return
self.h, self.w, _c = frame.shape
# if self.record:
# self.out.write(frame)
# else: self.out.release()
# display unaltered frame
# imshow("Original",frame)
# set current image frame to the processor's input
self.processor.frame_in = frame
# process the image frame to perform all needed analysis
try:
self.processor.run(self.selected_cam)
except:
pass
# collect the output frame for display
output_frame = self.processor.frame_out
# show the processed/annotated output frame
imshow("Processed", output_frame)
# create and/or update the raw data display if needed
if self.bpm_plot:
self.make_bpm_plot()
if self.send_serial:
self.serial.write(str(self.processor.bpm) + "\r\n")
if self.send_udp:
self.sock.sendto(str(self.processor.bpm), self.udp)
# handle any key presses
self.key_handler()
def get_pulse(args):
if not os.path.exists(args.save_dir):
os.makedirs(args.save_dir)
if not os.path.exists(os.path.join(args.save_dir, args.subject)):
os.makedirs(os.path.join(args.save_dir, args.subject))
App = getPulseApp(args)
App.ser = bluetooth()
App.ser.do_connect('/dev/cu.HC-06-SPPDev')
with open('recordings.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['','Time', 'BPM', 'TEMP', 'Nothing'])
delay = 0
while App.kill == False:
index = 0
App.main_loop()
if delay % 5 == 0: App.Tx = True
if len(App.processor.ttimes) and len(App.processor.ttimes) % 3 == 0:
with open('recordings.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([index, App.processor.ttimes[-1], App.processor.bpms[-1], App.processor.temps[-1], 0])
index += 1
delay += 1
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Webcam pulse detector.')
parser.add_argument('--serial', default=None,
help='serial port destination for bpm data')
parser.add_argument('--baud', default=None,
help='Baud rate for serial transmission')
parser.add_argument('--udp', default=None,
help='udp address:port destination for bpm data')
parser.add_argument('--subject', default='yph')
parser.add_argument('--init_temp', type=float, default=36.5)
parser.add_argument('--video', default="",
help='video name (only analyze one video)')
parser.add_argument('--video_dir', default=None,
help='directory name of all videos to be analyzed')
parser.add_argument('--save_dir', default='data_pulse',
help='directory to save the csv files')
parser.add_argument('--BT', default=b'98:D3:71:F9:89:EC', type=bytes)
parser.add_argument('--url', default=None, type=str,
help='IP Webcam url (ex: http://192.168.0.101:8080/video)')
args = parser.parse_args()
print(args)
get_pulse(args)