tjy/RespirationRate/demo.py

105 lines
2.4 KiB
Python
Raw Permalink Normal View History

2024-06-20 18:22:33 +08:00
import queue
import cv2
import numpy as np
from RespirationRateDetector import RespirationRateDetector
from params import args
import matplotlib.pyplot as plt
def main():
cap = cv2.VideoCapture(0) # 使用摄像头
video_fs = cap.get(5)
detector = RespirationRateDetector(args)
frames = []
text = ["calculating..."]
font = cv2.FONT_HERSHEY_SIMPLEX
# face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
resps = queue.Queue()
fig, ax = plt.subplots()
line, = ax.plot([], [])
plt.ion()
plt.show()
xdata = []
ydata = []
last = 0
while True:
ret, frame = cap.read()
frames.append(frame)
if len(frames) == 300:
Resp, RR_FFT, RR_PC, RR_CP, RR_NFCP = detector.detect_respiration_rate(frames, video_fs)
Resp[0] = last
for res in Resp:
resps.put(res)
last = Resp[-1]
text.clear()
text.append('RR-FFT: {:.2f} bpm'.format(RR_FFT))
text.append('RR-PC: {:.2f} bpm'.format(RR_PC))
text.append('RR-CP: {:.2f} bpm'.format(RR_CP))
text.append('RR-NFCP: {:.2f} bpm'.format(RR_NFCP))
frames = []
# 去除列表最前面的100个元素
# frames=frames[50:]
if not resps.empty():
resp = resps.get()
# 更新线的数据
ydata.append(resp)
else:
ydata.append(0)
if len(xdata) == 0:
xdata.append(1)
else:
xdata.append(xdata[-1] + 1)
if len(xdata) > 600:
xdata.pop(0)
ydata.pop(0)
# 生成时间序列
t = np.linspace(xdata[0] / video_fs, xdata[-1] / video_fs, len(ydata))
line.set_data(t, ydata) # 使用时间序列作为x轴
# 更新坐标轴的范围
ax.set_xlim(t[0], t[-1])
ax.set_ylim(min(0, min(ydata)) - 0.5 * abs(min(ydata)), 1.5 * max(ydata))
# 更新图表的显示
plt.draw()
plt.pause(0.01)
for i, t in enumerate(text):
cv2.putText(frame, t, (10, 60 + i * 20), font, 0.6, (0, 255, 0), 2)
cv2.imshow('Respiration Rate Detection', frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
plt.close()
if __name__ == '__main__':
main()