-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGUI5.py
More file actions
775 lines (670 loc) · 29.9 KB
/
GUI5.py
File metadata and controls
775 lines (670 loc) · 29.9 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# GUI5.py
import cv2
import numpy as np
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QFont, QImage, QPixmap
from PyQt5.QtWidgets import (QPushButton, QApplication, QComboBox, QLabel,
QFileDialog, QStatusBar, QMessageBox, QMainWindow,
QGridLayout, QVBoxLayout, QHBoxLayout, QWidget)
import pyqtgraph as pg
import sys
from process import Process
from webcam import Webcam
from video import Video
from interface import waitKey
import os
import imutils
import scipy.signal as signal
import scipy.fftpack as fftpack
import time
from collections import deque
from scipy.signal import butter, filtfilt
import torch
from PIL import Image, ImageDraw
from torchvision import transforms
from facenet_pytorch import MTCNN
import torch.nn as nn
from torchvision import models
# 设置 DeepFace 权重目录,避免自动下载
os.environ['DEEPFACE_HOME'] = r"D:\1-main\ces\deepface\weights"
from deepface import DeepFace
# ------------------- DeepFace 线程 -------------------
class DeepFaceThread(QThread):
result_ready = pyqtSignal(dict)
def __init__(self):
super().__init__()
self.frame_queue = deque(maxlen=2)
self.running = True
def run(self):
while self.running:
if self.frame_queue:
frame = self.frame_queue.popleft()
try:
# 将 OpenCV 格式的 BGR 图像转换为 RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
#result = DeepFace.analyze(frame_rgb, actions=['age','gender','emotion','race'], enforce_detection=False)
result = DeepFace.analyze(frame_rgb, actions=['gender'], enforce_detection=False)
if isinstance(result, list) and len(result) > 0:
result = result[0]
self.result_ready.emit(result)
except Exception as e:
print("[DeepFaceThread] 分析失败:", e)
else:
self.msleep(50)
def add_frame(self, frame):
if len(self.frame_queue) == self.frame_queue.maxlen:
self.frame_queue.popleft()
self.frame_queue.append(frame)
def stop(self):
self.running = False
self.wait()
# ------------------- BMI 预测线程 -------------------
# 从 testcode.py 复制 BMI_ResNet 类
class BMI_ResNet(nn.Module):
def __init__(self):
super(BMI_ResNet, self).__init__()
self.resnet = models.resnet18(pretrained=True)
self.resnet.fc = nn.Linear(self.resnet.fc.in_features, 1)
def forward(self, x):
return self.resnet(x)
class BMIPredictionThread(QThread):
prediction_ready = pyqtSignal(float)
def __init__(self, model_path, device):
super().__init__()
self.frame_queue = deque(maxlen=2)
self.running = True
self.device = device
self.last_face = None # 用于缓存上一帧成功检测到的人脸
# 加载模型和 MTCNN
self.model = BMI_ResNet().to(self.device)
try:
self.model.load_state_dict(torch.load(model_path, map_location=self.device))
self.model.eval()
print("BMI 模型加载成功。")
except Exception as e:
print(f"BMI 模型加载失败: {e}")
self.model = None
self.mtcnn = MTCNN(device=self.device)
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
def run(self):
while self.running:
if self.frame_queue:
frame = self.frame_queue.popleft()
if self.model:
try:
# 从 numpy 数组转换为 PIL 图像
pil_image = Image.fromarray(frame).convert('RGB')
# 尝试裁剪人脸
face_image = self.detect_and_crop_face(pil_image)
if face_image:
# 如果检测成功,更新缓存的人脸
self.last_face = face_image
# 如果当前帧未检测到人脸,但有缓存,则使用缓存
if face_image is None and self.last_face is not None:
face_image = self.last_face
if face_image:
# 预处理并预测
tensor_image = self.transform(face_image).unsqueeze(0).to(self.device)
with torch.no_grad():
output = self.model(tensor_image)
predicted_bmi = output.item()
self.prediction_ready.emit(predicted_bmi)
print(f"[BMIThread] 预测 BMI: {predicted_bmi:.4f}")
else:
print("[BMIThread] 未检测到人脸,无法预测 BMI。")
except Exception as e:
print(f"[BMIThread] 预测失败: {e}")
else:
self.msleep(100)
def add_frame(self, frame):
if len(self.frame_queue) == self.frame_queue.maxlen:
self.frame_queue.popleft()
self.frame_queue.append(frame)
def stop(self):
self.running = False
self.wait()
# 从 testcode.py 复制 detect_and_crop_face 函数
def detect_and_crop_face(self, image, target_size=(240, 320)):
boxes, _ = self.mtcnn.detect(image)
if boxes is not None and len(boxes) > 0:
x1, y1, x2, y2 = boxes[0]
width, height = x2 - x1, y2 - y1
offset_x = width * 0.3
offset_y = height * 0.3
# 扩展边界并确保不超出图像范围
x1_new = max(int(x1 - offset_x), 0)
y1_new = max(int(y1 - offset_y), 0)
x2_new = int(x2 + offset_x)
y2_new = int(y2 + offset_y)
face = image.crop((x1_new, y1_new, x2_new, y2_new))
# 调整尺寸并填充
scale = min(target_size[0] / face.width, target_size[1] / face.height)
new_size = (int(face.width * scale), int(face.height * scale))
face = face.resize(new_size, Image.Resampling.LANCZOS)
new_face = Image.new("RGB", target_size, (0, 0, 0))
new_face.paste(face, ((target_size[0] - face.width) // 2, (target_size[1] - face.height) // 2))
return new_face
else:
return None
# ------------------- VidMag 线程 -------------------
class VidMagThread(QThread):
# ... (VidMagThread, VidMag 类不变)
magnified_frame_ready = pyqtSignal(np.ndarray)
def __init__(self):
super().__init__()
self.vidmag = VidMag()
self.frame_queue = deque(maxlen=40)
self.running = False
def run(self):
self.vidmag.running = True
while self.running:
if self.frame_queue:
frame = self.frame_queue.popleft()
magnified_frame = self.vidmag.run_magnification_internal(frame)
if magnified_frame is not None:
self.magnified_frame_ready.emit(magnified_frame)
else:
self.msleep(1)
self.vidmag.running = False
def add_frame(self, frame):
if len(self.frame_queue) == self.frame_queue.maxlen:
self.frame_queue.popleft()
self.frame_queue.append(frame)
def start_magnification(self):
self.running = True
self.start()
def stop_magnification(self):
self.running = False
self.wait()
# ------------------- VidMag 类 -------------------
class VidMag():
def __init__(self):
self.buffer_size = 40
self.fps = 0
self.times = []
self.t0 = time.time()
self.data_buffer = []
self.frame_out = np.zeros((10,10,3),np.uint8)
self.running = False
def build_gaussian_pyramid(self,src,level=3):
s=src.copy()
pyramid=[s]
for i in range(level):
s=cv2.pyrDown(s)
pyramid.append(s)
return pyramid
def gaussian_video(self,video_tensor,levels=3):
vid_data = np.zeros((video_tensor.shape[0],
video_tensor.shape[1] // (2**levels),
video_tensor.shape[2] // (2**levels), 3))
for i in range(video_tensor.shape[0]):
frame = video_tensor[i]
pyr = self.build_gaussian_pyramid(frame, level=levels)
gaussian_frame = pyr[-1]
vid_data[i] = gaussian_frame
return vid_data
def temporal_ideal_filter(self,tensor,low,high,fps,axis=0):
fft=fftpack.fft(tensor,axis=axis)
frequencies = fftpack.fftfreq(tensor.shape[0], d=1.0 / fps)
bound_low = (np.abs(frequencies - low)).argmin()
bound_high = (np.abs(frequencies - high)).argmin()
fft[:bound_low] = 0
fft[bound_high:-bound_high] = 0
fft[-bound_low:] = 0
iff=fftpack.ifft(fft, axis=axis)
return np.abs(iff)
def amplify_video(self,gaussian_vid,amplification=70):
return gaussian_vid*amplification
def reconstract_video(self,amp_video,origin_video,levels=3):
final_video=np.zeros(origin_video.shape)
for i in range(0,amp_video.shape[0]):
img = amp_video[i]
for x in range(levels):
img=cv2.pyrUp(img)
img=img+origin_video[i]
final_video[i]=img
return final_video
def magnify_color(self,data_buffer,fps,low=0.4,high=2,levels=3,amplification=30):
if not data_buffer.shape[0]: return np.zeros(10)
gau_video=self.gaussian_video(data_buffer,levels=levels)
filtered_tensor=self.temporal_ideal_filter(gau_video,low,high,fps)
amplified_video=self.amplify_video(filtered_tensor,amplification=amplification)
final_video = self.reconstract_video(amplified_video,data_buffer,levels=levels)
return final_video
def buffer_to_tensor(self, buffer):
if not buffer: return np.zeros((0,10,10,3))
resized_frames = [imutils.resize(f, height=240) for f in buffer]
h, w, c = resized_frames[0].shape
tensor = np.zeros((len(resized_frames), h, w, c), dtype="float")
for i, frame in enumerate(resized_frames):
tensor[i] = frame
return tensor
def run_magnification_internal(self, frame):
if not self.running:
self.data_buffer = []
self.times = []
self.t0 = time.time()
return None
resized_frame = imutils.resize(frame, height=240)
self.data_buffer.append(resized_frame)
self.times.append(time.time() - self.t0)
L = len(self.data_buffer)
if L > self.buffer_size:
self.data_buffer = self.data_buffer[-self.buffer_size:]
self.times = self.times[-self.buffer_size:]
L = self.buffer_size
delta_t = self.times[-1] - self.times[0]
self.fps = float(L) / delta_t if L > 1 and delta_t > 0 else 0
if L == self.buffer_size:
tensor = self.buffer_to_tensor(self.data_buffer)
final_vid = self.magnify_color(data_buffer=tensor, fps=self.fps)
if final_vid is not None and final_vid.shape[0] > 0:
self.frame_out = cv2.convertScaleAbs(final_vid[-1])
return self.frame_out
return None
# ------------------- 主 GUI -------------------
class GUI(QMainWindow):
def __init__(self):
super(GUI,self).__init__()
font = QFont()
font.setFamily("SimHei")
font.setPointSize(16)
QApplication.setFont(font)
# 增加一个标志来控制 BMI 预测的频率
self.bmi_predict_counter = 0
self.deepface_done = False
self.initUI()
# 获取可用 GPU
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Using device: {self.device}")
self.webcam = Webcam()
self.video = Video()
self.input = self.webcam
self.dirname = ""
print("Input: webcam")
self.statusBar.showMessage("Input: webcam", 5000)
self.btnOpen.setEnabled(False)
self.process = Process()
self.vidmag_thread = VidMagThread()
self.vidmag_thread.magnified_frame_ready.connect(self.update_magnified_display)
# 初始化 BMI 预测线程
model_save_path = r'D:\1-main\ces\model1211-2-18.pth' # 确保路径正确
self.bmi_thread = BMIPredictionThread(model_save_path, self.device)
self.bmi_thread.prediction_ready.connect(self.update_bmi_result)
self.bmi_thread.start()
self.status = False
self.frame = np.zeros((10,10,3),np.uint8)
self.bpm = 0
self.terminate = False
self.rr = 0
self.hrv = 0
self.spo2 = 0
self.hr_history = []
self.red_signal, self.blue_signal = [], []
self.bpm_history, self.rr_history, self.spo2_history = [], [], []
self.age = None
self.gender = None
self.emotion = None
self.race = None
self.bmi = None # 新增 BMI 变量
self.deepface_thread = DeepFaceThread()
self.deepface_thread.result_ready.connect(self.update_deepface_result)
self.deepface_thread.start()
def initUI(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QGridLayout(central_widget)
main_layout.setSpacing(10)
font = QFont()
font.setPointSize(16)
# 控制布局
control_layout = QHBoxLayout()
control_layout.setSpacing(10)
self.cbbInput = QComboBox()
self.cbbInput.addItem("Webcam")
self.cbbInput.addItem("Video")
self.cbbInput.setCurrentIndex(0)
self.cbbInput.setFixedHeight(50)
self.cbbInput.setFont(font)
self.cbbInput.activated.connect(self.selectInput)
control_layout.addWidget(self.cbbInput, 1)
self.btnOpen = QPushButton("Open")
self.btnOpen.setFixedHeight(50)
self.btnOpen.setFont(font)
self.btnOpen.clicked.connect(self.openFileDialog)
control_layout.addWidget(self.btnOpen, 1)
self.btnStart = QPushButton("Start")
self.btnStart.setFixedHeight(50)
self.btnStart.setFont(font)
self.btnStart.clicked.connect(self.run)
control_layout.addWidget(self.btnStart, 1)
self.btnDeepFace = QPushButton("再次分析")
self.btnDeepFace.setFixedHeight(50)
self.btnDeepFace.setFont(font)
self.btnDeepFace.clicked.connect(self.reanalyze_frame)
control_layout.addWidget(self.btnDeepFace, 1)
# 视频显示
self.lblDisplay = QLabel()
self.lblDisplay.setStyleSheet("background-color: #000000")
self.lblDisplay.setScaledContents(True)
self.lblROI = QLabel()
self.lblROI.setStyleSheet("background-color: #000000")
self.lblROI.setAlignment(QtCore.Qt.AlignCenter)
# 新增的放大视频显示
self.lblMagnified = QLabel("Magnified Video")
self.lblMagnified.setStyleSheet("background-color: #000000")
self.lblMagnified.setAlignment(QtCore.Qt.AlignCenter)
self.lblMagnified.setScaledContents(True)
# 放大功能控制
magnify_layout = QHBoxLayout()
self.cbbMagnify = QComboBox()
self.cbbMagnify.addItem("Color Magnification")
self.cbbMagnify.setCurrentIndex(0)
self.btnMagnify = QPushButton("开始放大")
self.btnMagnify.clicked.connect(self.toggleMagnification)
magnify_layout.addWidget(self.cbbMagnify)
magnify_layout.addWidget(self.btnMagnify)
# 信息显示
info_layout = QVBoxLayout()
info_layout.setSpacing(15)
self.lblHR = QLabel("频率: ")
self.lblHR.setFont(font)
self.lblHR2 = QLabel("心率: ")
self.lblHR2.setFont(font)
self.lblRR = QLabel("呼吸率: ")
self.lblRR.setFont(font)
self.lblHRV = QLabel("心率变异性: ")
self.lblHRV.setFont(font)
self.lblSpO2 = QLabel("血氧饱和度: ")
self.lblSpO2.setFont(font)
self.lblGender = QLabel("性别: ")
self.lblGender.setFont(font)
#self.lblAge = QLabel("年龄: ")
#self.lblAge.setFont(font)
#self.lblEmotion = QLabel("情绪: ")
#self.lblEmotion.setFont(font)
#self.lblRace = QLabel("种族: ")
#self.lblRace.setFont(font)
self.lblBMI = QLabel("BMI: ") # 新增 BMI 标签
self.lblBMI.setFont(font)
#for w in [self.lblHR, self.lblHR2, self.lblRR, self.lblHRV, self.lblSpO2,
#self.lblGender, self.lblAge, self.lblEmotion, self.lblRace, self.lblBMI]:
for w in [self.lblHR, self.lblHR2, self.lblRR, self.lblHRV, self.lblSpO2,
self.lblGender,self.lblBMI]:
info_layout.addWidget(w)
info_layout.addStretch(1)
# 图形显示
self.signal_Plt = pg.PlotWidget()
self.signal_Plt.setLabel('bottom', "Signal")
self.fft_Plt = pg.PlotWidget()
self.fft_Plt.setLabel('bottom', "FFT")
plot_layout = QVBoxLayout()
plot_layout.addWidget(self.signal_Plt)
plot_layout.addWidget(self.fft_Plt)
right_layout = QVBoxLayout()
right_layout.addLayout(info_layout, 1)
right_layout.addLayout(plot_layout, 3)
main_layout.addLayout(control_layout, 1, 0, 1, 4)
main_layout.addWidget(self.lblDisplay, 0, 0, 1, 2)
main_layout.addWidget(self.lblROI, 0, 2)
main_layout.addLayout(right_layout, 0, 3)
# 将新布局和部件添加到主网格布局中
main_layout.addWidget(self.lblMagnified, 2, 0, 1, 2)
main_layout.addLayout(magnify_layout, 2, 2, 1, 2)
main_layout.setRowStretch(0, 4)
main_layout.setRowStretch(1, 1)
main_layout.setRowStretch(2, 4)
main_layout.setColumnStretch(0, 2)
main_layout.setColumnStretch(1, 1)
main_layout.setColumnStretch(2, 1)
main_layout.setColumnStretch(3, 2)
self.timer = pg.QtCore.QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(200)
self.statusBar = QStatusBar()
self.statusBar.setFont(font)
self.setStatusBar(self.statusBar)
self.setGeometry(100, 100, 1600, 900)
self.setWindowTitle("心率监测与视频放大系统")
self.show()
def reanalyze_frame(self):
if self.frame is not None and len(self.frame) > 0:
print("[INFO] 再次分析当前帧")
self.deepface_thread.add_frame(self.frame.copy())
def toggleMagnification(self):
if self.vidmag_thread.running:
self.vidmag_thread.stop_magnification()
self.btnMagnify.setText("开始放大")
self.lblMagnified.clear()
self.statusBar.showMessage(f"已停止色彩放大", 3000)
else:
self.vidmag_thread.start_magnification()
self.btnMagnify.setText("停止放大")
self.statusBar.showMessage(f"已开始色彩放大", 3000)
def selectMagnifyMode(self, index):
# 只有一个选项,不需要做任何事情
pass
def update_magnified_display(self, magnified_frame):
if magnified_frame is not None and magnified_frame.size > 0:
magnified_frame = cv2.cvtColor(magnified_frame, cv2.COLOR_RGB2BGR)
mag_img = QImage(magnified_frame, magnified_frame.shape[1], magnified_frame.shape[0],
magnified_frame.strides[0], QImage.Format_RGB888)
self.lblMagnified.setPixmap(QPixmap.fromImage(mag_img))
def update(self):
self.signal_Plt.clear()
if len(self.process.samples) > 0:
self.signal_Plt.plot(self.process.samples[20:], pen='g')
self.fft_Plt.clear()
if len(self.process.fft) > 0:
self.fft_Plt.plot(np.column_stack((self.process.freqs, self.process.fft)), pen='g')
def closeEvent(self, event):
reply = QMessageBox.question(self, "提示", "确定要退出吗?",
QMessageBox.Yes|QMessageBox.No, QMessageBox.Yes)
if reply == QMessageBox.Yes:
event.accept()
self.input.stop()
self.deepface_thread.stop()
self.vidmag_thread.stop_magnification()
self.bmi_thread.stop() # 停止 BMI 线程
self.terminate = True
sys.exit()
else:
event.ignore()
def selectInput(self):
self.reset()
if self.cbbInput.currentIndex() == 0:
self.input = self.webcam
print("Input: webcam")
self.btnOpen.setEnabled(False)
elif self.cbbInput.currentIndex() == 1:
self.input = self.video
print("Input: video")
self.btnOpen.setEnabled(True)
def key_handler(self):
self.pressed = waitKey(1) & 255
if self.pressed == 27:
print("[INFO] 退出程序")
self.webcam.stop()
sys.exit()
def openFileDialog(self):
self.dirname = QFileDialog.getOpenFileName(self, '打开文件')[0]
def reset(self):
self.process.reset()
self.lblDisplay.clear()
self.lblDisplay.setStyleSheet("background-color: #000000")
self.rr = 0
self.hrv = 0
self.spo2 = 0
self.hr_history = []
self.red_signal, self.blue_signal = [], []
self.bpm_history, self.rr_history, self.spo2_history = [], [], []
def calculate_physiological_indices(self):
# ---------- 心率 ----------
if len(self.red_signal) > 150:
signal = np.array(self.red_signal[-300:])
signal = signal - np.mean(signal)
b, a = butter(3, [0.8/(self.process.fps/2), 3.0/(self.process.fps/2)], btype='band')
filtered = filtfilt(b, a, signal)
freqs = np.fft.rfftfreq(len(filtered), d=1/self.process.fps)
fft_mag = np.abs(np.fft.rfft(filtered))
mask = (freqs >= 0.8) & (freqs <= 3.0)
if np.any(mask):
top_idx = np.argsort(fft_mag[mask])[-3:]
top_freqs = freqs[mask][top_idx]
top_mag = fft_mag[mask][top_idx]
self.bpm = np.sum(top_freqs*top_mag)/np.sum(top_mag) * 60
self.bpm_history.append(self.bpm)
if len(self.bpm_history) > 5:
self.bpm = np.mean(self.bpm_history[-5:])
else:
self.bpm = 0
# ---------- HRV ----------
if len(self.process.bpms) > 10:
rr_intervals = 60.0 / np.array(self.process.bpms)
diff_rr = np.diff(rr_intervals)
self.hrv = np.sqrt(np.mean(diff_rr**2)) * 1000
else:
self.hrv = 0
# ---------- 呼吸率 ----------
if len(self.process.samples) > 50:
signal = np.array(self.process.samples[-200:])
signal = signal - np.mean(signal)
try:
b, a = butter(2, [0.1/(self.process.fps/2), 0.5/(self.process.fps/2)], btype='band')
filtered = filtfilt(b, a, signal)
freqs = np.fft.rfftfreq(len(filtered), d=1/self.process.fps)
fft_mag = np.abs(np.fft.rfft(filtered))
mask = (freqs >= 0.1) & (freqs <= 0.5)
if np.any(mask):
peak_freq = freqs[mask][np.argmax(fft_mag[mask])]
rr_inst = peak_freq * 60
else:
rr_inst = 0
self.rr_history.append(rr_inst)
if len(self.rr_history)>5:
self.rr = np.mean(self.rr_history[-5:])
except:
self.rr = 0
else:
self.rr = 0
# ---------- SpO2 ----------
if len(self.red_signal) > 150 and len(self.blue_signal) > 150:
red = np.array(self.red_signal[-300:])
blue = np.array(self.blue_signal[-300:])
red = np.convolve(red, np.ones(5)/5, mode='valid')
blue = np.convolve(blue, np.ones(5)/5, mode='valid')
ac_red, dc_red = np.std(red), np.mean(red)
ac_blue, dc_blue = np.std(blue), np.mean(blue)
if dc_red>0 and dc_blue>0:
R = (ac_red/dc_red) / (ac_blue/dc_blue)
spo2_inst = 100 - 5*(R - 0.4)
spo2_inst = np.clip(spo2_inst, 90, 100)
self.spo2_history.append(spo2_inst)
if len(self.spo2_history) > 5:
self.spo2 = np.mean(self.spo2_history[-5:])
else:
self.spo2 = 0
def update_deepface_result(self, result):
self.age = result.get('age', None)
self.gender = result.get('dominant_gender', None)
self.emotion = result.get('dominant_emotion', None)
self.race = result.get('dominant_race', None)
def update_bmi_result(self, bmi_value):
self.bmi = bmi_value
def main_loop(self):
frame = self.input.get_frame()
self.process.frame_in = frame
if not self.terminate:
ret = self.process.run()
if ret:
self.frame = self.process.frame_out
self.f_fr = self.process.frame_ROI
self.bpm = self.process.bpm
else:
self.frame = frame
self.f_fr = np.zeros((10,10,3),np.uint8)
self.bpm = 0
# 将帧发送给放大线程和 BMI 预测线程
self.vidmag_thread.add_frame(frame.copy())
# 每隔一定帧数发送一次给 BMI 线程,以减少计算压力
self.bmi_predict_counter += 1
if self.bmi_predict_counter % 20 == 0: # 每20帧预测一次
self.bmi_thread.add_frame(frame.copy())
self.bmi_predict_counter = 0
if self.f_fr is not None and self.f_fr.size>0:
roi_mean = np.mean(self.f_fr, axis=(0,1))
b,g,r = roi_mean
self.red_signal.append(r)
self.blue_signal.append(b)
self.calculate_physiological_indices()
if self.frame is not None and self.frame.size>0:
self.frame = cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)
img = QImage(self.frame, self.frame.shape[1], self.frame.shape[0],
self.frame.strides[0], QImage.Format_RGB888)
self.lblDisplay.setPixmap(QPixmap.fromImage(img))
if not self.deepface_done:
self.deepface_thread.add_frame(self.frame.copy())
self.deepface_done = True
if self.f_fr is not None and self.f_fr.size>0:
self.f_fr = cv2.cvtColor(self.f_fr, cv2.COLOR_RGB2BGR)
f_img = QImage(self.f_fr, self.f_fr.shape[1], self.f_fr.shape[0],
self.f_fr.strides[0], QImage.Format_RGB888)
QtWidgets.QApplication.processEvents()
f_pixmap = QPixmap.fromImage(f_img)
roi_label_size = self.lblROI.size()
scaled_pixmap = f_pixmap.scaled(
roi_label_size,
QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation
)
self.lblROI.setPixmap(scaled_pixmap)
self.lblHR.setText(f"频率: {self.bpm:.2f}")
if len(self.process.bpms) > 50:
if max(self.process.bpms - np.mean(self.process.bpms)) < 5:
self.lblHR2.setText(f"心率: {np.mean(self.process.bpms):.2f} bpm")
self.lblRR.setText(f"呼吸率: {self.rr:.1f} bpm")
self.lblHRV.setText(f"心率变异性: {self.hrv:.1f} ms")
self.lblSpO2.setText(f"血氧饱和度: {self.spo2:.1f} %")
if self.gender:
self.lblGender.setText(f"性别: {self.gender}")
if self.age:
self.lblAge.setText(f"年龄: {self.age}")
if self.emotion:
self.lblEmotion.setText(f"情绪: {self.emotion}")
if self.race:
self.lblRace.setText(f"种族: {self.race}")
if self.bmi:
self.lblBMI.setText(f"BMI: {self.bmi:.2f}") # 更新 BMI 标签
self.key_handler()
def run(self, input=None):
print("运行中")
self.reset()
input = self.input
self.input.dirname = self.dirname
if self.input.dirname == "" and self.input==self.video:
print("请先选择一个视频文件")
return
if not self.status:
self.status = True
input.start()
self.btnStart.setText("停止")
self.cbbInput.setEnabled(False)
self.btnOpen.setEnabled(False)
self.lblHR2.clear()
while self.status:
self.main_loop()
else:
self.status = False
input.stop()
self.btnStart.setText("开始")
self.cbbInput.setEnabled(True)
if self.cbbInput.currentIndex()==1:
self.btnOpen.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = GUI()
sys.exit(app.exec_())