视频检测呼吸频率
- 从视频中提取帧并定义ROI区域。
- 计算ROI中的运动幅度。
- 基于运动幅度检测呼吸频率。
import cv2
import numpy as np
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
def preprocess_and_detect_motion(video_path, initial_roi=(676, 485, 296, 315)):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError("无法打开视频文件,请检查路径是否正确")
fps = cap.get(cv2.CAP_PROP_FPS)
if fps is None or fps <= 0:
raise ValueError("无法获取视频的帧率,请检查视频文件")
ret, frame = cap.read()
if not ret:
raise ValueError("无法读取视频帧,请检查视频文件")
# 初始化 ROI
x_start, y_start, width, height = initial_roi
movements = []
prev_roi_frame = None
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 转换为灰度图像并提取 ROI 区域
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
roi_frame = gray[y_start:y_start+height, x_start:x_start+width]
if prev_roi_frame is not None:
# 确保 ROI 大小匹配
if prev_roi_frame.shape == roi_frame.shape:
diff = cv2.absdiff(prev_roi_frame, roi_frame)
movement = np.mean(diff)
movements.append(movement)
prev_roi_frame = roi_frame
cap.release()
return movements, fps
def calculate_breathing_rate(movements, fps):
if len(movements) == 0:
return 0
# 平滑数据
smooth_movements = gaussian_filter1d(movements, sigma=1)
peaks, _ = find_peaks(smooth_movements, distance=fps / 3)
breath_rate = len(peaks) / (len(smooth_movements) / fps / 60)
# 可视化
time_axis = np.arange(len(smooth_movements)) / fps
plt.plot(time_axis, smooth_movements, label='Smoothed Movement')
plt.plot(time_axis[peaks], smooth_movements[peaks], "x", label='Breaths Detected')
plt.title("Breathing Movement over Time")
plt.xlabel("Time (s)")
plt.ylabel("Smoothed Movement Amplitude")
plt.legend()
plt.show()
return breath_rate
def main():
video_path = 'Sow_fast_breathing.mp4'
initial_roi = (676, 485, 296, 315) # 替换为适当的ROI区域(x_start, y_start, width, height)
movements, fps = preprocess_and_detect_motion(video_path, initial_roi)
if movements:
breath_rate = calculate_breathing_rate(movements, fps)
print(f"Estimated Breathing Rate: {breath_rate:.2f} breaths per minute")
else:
print("未检测到任何运动")
if __name__ == "__main__":
main()
可调整参数:sigma和distance。如sigma=0.5和distance=fps/4 以检测到更多的峰值
手动选择ROI区域
import cv2
video_path = 'Sow_fast_breathing.mp4'
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
if ret:
roi = cv2.selectROI("Select ROI", frame, fromCenter=False, showCrosshair=True)
cv2.destroyAllWindows()
print("Selected ROI:", roi) # 输出格式为 (x, y, width, height)
cap.release()
具体结果如下: