├── IOF.py ├── LICENSE ├── README.md ├── RespirationRateCalculationAlgorithm.py ├── lmagesFolderForReadMe ├── Application diagram.png └── test2_result.png ├── main.py ├── params.py ├── test1.avi ├── test2.mp4 └── test3.mp4 /IOF.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from params import args 4 | from scipy import signal 5 | from RespirationRateCalculationAlgorithm import RR_Algorithm 6 | 7 | def FeaturePointSelectionStrategy(Image, FPN=5, QualityLevel=0.3): 8 | Image_gray = Image 9 | feature_params = dict(maxCorners=args.FSS_maxCorners, 10 | qualityLevel=QualityLevel, 11 | minDistance=args.FSS_minDistance) 12 | 13 | p0 = cv2.goodFeaturesToTrack(Image_gray, mask=args.FSS_mask, **feature_params) 14 | 15 | """ Robust checking """ 16 | while(p0 is None): 17 | QualityLevel = QualityLevel - args.FSS_QualityLevelRV 18 | feature_params = dict(maxCorners=args.FSS_maxCorners, 19 | qualityLevel=QualityLevel, 20 | minDistance=args.FSS_minDistance) 21 | p0 = cv2.goodFeaturesToTrack(Image_gray, mask=None, **feature_params) 22 | 23 | if len(p0) < FPN: 24 | FPN = len(p0) 25 | 26 | h = Image_gray.shape[0] / 2 27 | w = Image_gray.shape[1] / 2 28 | 29 | p1 = p0.copy() 30 | p1[:, :, 0] -= w 31 | p1[:, :, 1] -= h 32 | p1_1 = np.multiply(p1, p1) 33 | p1_2 = np.sum(p1_1, 2) 34 | p1_3 = np.sqrt(p1_2) 35 | p1_4 = p1_3[:, 0] 36 | p1_5 = np.argsort(p1_4) 37 | 38 | FPMap = np.zeros((FPN, 1, 2), dtype=np.float32) 39 | for i in range(FPN): 40 | FPMap[i, :, :] = p0[p1_5[i], :, :] 41 | 42 | return FPMap 43 | 44 | 45 | def CorrelationGuidedOpticalFlowMethod(FeatureMtx_Amp, RespCurve): 46 | CGAmp_Mtx = FeatureMtx_Amp.T 47 | CGAmpAugmented_Mtx = np.zeros((CGAmp_Mtx.shape[0] + 1, CGAmp_Mtx.shape[1])) 48 | CGAmpAugmented_Mtx[0, :] = RespCurve 49 | CGAmpAugmented_Mtx[1:, :] = CGAmp_Mtx 50 | 51 | Correlation_Mtx = np.corrcoef(CGAmpAugmented_Mtx) 52 | CM_mean = np.mean(abs(Correlation_Mtx[0, 1:])) 53 | Quality_num = (abs(Correlation_Mtx[0, 1:]) >= CM_mean).sum() 54 | QualityFeaturePoint_arg = (abs(Correlation_Mtx[0, 1:]) >= CM_mean).argsort()[0 - Quality_num:] 55 | 56 | CGOF_Mtx = np.zeros((FeatureMtx_Amp.shape[0], Quality_num)) 57 | 58 | for i in range(Quality_num): 59 | CGOF_Mtx[:, i] = FeatureMtx_Amp[:, QualityFeaturePoint_arg[i]] 60 | 61 | CGOF_Mtx_RespCurve = np.sum(CGOF_Mtx, 1) / Quality_num 62 | 63 | return CGOF_Mtx_RespCurve 64 | 65 | 66 | def ImproveOpticalFlow(video_path, QualityLevel=0.3, FSS=False, CGOF=False, filter=True, Normalization=False, RR_Evaluation=False): 67 | video_filename = video_path 68 | 69 | cap = cv2.VideoCapture(video_filename) 70 | feature_params = dict(maxCorners=args.OFP_maxCorners, 71 | qualityLevel=QualityLevel, 72 | minDistance=args.OFP_minDistance) 73 | 74 | ret, old_frame = cap.read() 75 | old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) 76 | p0 = cv2.goodFeaturesToTrack(old_gray, mask=args.OFP_mask, **feature_params) 77 | 78 | """ Robust Checking """ 79 | while(p0 is None) : 80 | QualityLevel = QualityLevel - args.OFP_QualityLevelRV 81 | feature_params = dict(maxCorners=args.OFP_maxCorners, 82 | qualityLevel=QualityLevel, 83 | minDistance=args.OFP_minDistance) 84 | p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params) 85 | 86 | """ FeaturePoint Selection Strategy """ 87 | if FSS: 88 | p0 = FeaturePointSelectionStrategy(Image=old_gray, FPN=args.FSS_FPN, QualityLevel=args.FSS_qualityLevel) 89 | 90 | else: 91 | p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params) 92 | 93 | lk_params = dict(winSize=args.OFP_winSize, maxLevel=args.OFP_maxLevel) 94 | total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) 95 | 96 | FeatureMtx = np.zeros((int(total_frame), p0.shape[0], 2)) 97 | FeatureMtx[0, :, 0] = p0[:, 0, 0].T 98 | FeatureMtx[0, :, 1] = p0[:, 0, 1].T 99 | frame_num = 1; 100 | 101 | while (frame_num < total_frame): 102 | frame_num += 1 103 | ret, frame = cap.read() 104 | frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 105 | pl, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params) 106 | 107 | old_gray = frame_gray.copy() 108 | p0 = pl.reshape(-1, 1, 2) 109 | FeatureMtx[frame_num - 1, :, 0] = p0[:, 0, 0].T 110 | FeatureMtx[frame_num - 1, :, 1] = p0[:, 0, 1].T 111 | 112 | FeatureMtx_Amp = np.sqrt(FeatureMtx[:, :, 0] ** 2 + FeatureMtx[:, :, 1] ** 2) 113 | RespCurve = np.sum(FeatureMtx_Amp, 1) / p0.shape[0] 114 | 115 | """ CCorrelation-Guided Optical Flow Method """ 116 | if CGOF: 117 | RespCurve = CorrelationGuidedOpticalFlowMethod(FeatureMtx_Amp, RespCurve) 118 | 119 | fs = cap.get(5) 120 | 121 | """" Filter """ 122 | if filter: 123 | original_signal = RespCurve 124 | # 125 | filter_order = args.Filter_order 126 | LowPass = args.Filter_LowPass / 60 127 | HighPass = args.Filter_HighPass / 60 128 | b, a = signal.butter(filter_order, [2 * LowPass / fs, 2 * HighPass / fs], args.Filter_type) 129 | filtedResp = signal.filtfilt(b, a, original_signal) 130 | else: 131 | filtedResp = RespCurve 132 | 133 | """ Normalization """ 134 | if Normalization: 135 | Resp_max = max(filtedResp) 136 | Resp_min = min(filtedResp) 137 | Resp_norm = (filtedResp - Resp_min) / (Resp_max - Resp_min) - 0.5 138 | else: 139 | Resp_norm = filtedResp 140 | 141 | """ RR Evaluation""" 142 | RR_method = RR_Algorithm(Resp_norm, fs) 143 | RR_FFT = RR_method.FFT() 144 | RR_PC = RR_method.PeakCounting() 145 | RR_CP = RR_method.CrossingPoint() 146 | RR_NFCP = RR_method.NegativeFeedbackCrossoverPointMethod() 147 | 148 | if RR_Evaluation: 149 | return 1 - Resp_norm, round(RR_FFT, 2), round(RR_PC, 2), round(RR_CP, 2), round(RR_NFCP, 2) 150 | else: 151 | return 1 - Resp_norm 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lightweight Video-Based Respiration Rate Detection Algorithm: An Application Case on Intensive Care 🪡 (IEEE Transactions on Multimedia 2023) 2 | [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 3 | PyTorch 4 | 5 | By [Menghan Hu](https://faculty.ecnu.edu.cn/_s15/hmh/main.psp), [Xudong Tan](https://scholar.google.com/citations?user=6wfIBLgAAAAJ&hl=zh-CN&oi=sra) 6 | 7 | If you have any questions, please contact Menghan Hu(mhhu@ce.ecnu.edu.cn) or Xudong Tan(shawntannnn@gmail.com). 8 | 9 | ## Important Links 10 | - dataset: [LBRD-IC-Dataset](https://github.com/ShawnTan86/LBRD-IC-Dataset) 🌟🌟🌟 11 | - demo link: [Scene 1](https://www.youtube.com/watch?v=rpBcFdN-Pbw&t=2s), [Scene 2](https://www.youtube.com/watch?v=tb_ixhTzqvs) 🔥🔥🔥 12 | - paper: [Lightweight Video-Based Respiration Rate Detection Algorithm: An Application Case on Intensive Care](https://ieeexplore.ieee.org/abstract/document/10158936) 🎉🎉🎉 13 | 14 | ## A Gentle Introduction 15 | This is a lightweight non-contact respiratory signal detection algorithm suitable for daily use and applicable in ICU scenarios. 16 | ![image](https://github.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/blob/main/lmagesFolderForReadMe/Application%20diagram.png) 17 | 18 | ## Getting Started 19 | ```bash 20 | conda create -n IOF python=3.9 21 | pip install opencv-python==4.8.0 22 | pip install numpy==1.24.1 23 | pip install scipy==1.11.3 24 | pip install matplotlib==3.7.2 25 | ``` 26 | cd [Your installation directory] 27 | 28 | ```bash 29 | python main.py --video-path ./test2.mp4 30 | ``` 31 | ![image](https://github.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/blob/main/lmagesFolderForReadMe/test2_result.png) 32 | 33 | ## Citation 34 | If you use our code for your paper, please cite: 35 | ``` 36 | @ARTICLE{10158936, 37 | author={Tan, Xudong and Hu, Menghan and Zhai, Guangtao and Zhu, Yan and Li, Wenfang and Zhang, Xiao-Ping}, 38 | journal={IEEE Transactions on Multimedia}, 39 | title={Lightweight Video-Based Respiration Rate Detection Algorithm: An Application Case on Intensive Care}, 40 | year={2023}, 41 | volume={}, 42 | number={}, 43 | pages={1-15}, 44 | doi={10.1109/TMM.2023.3286994}} 45 | ``` 46 | -------------------------------------------------------------------------------- /RespirationRateCalculationAlgorithm.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from params import args 3 | from scipy.fftpack import fft 4 | from scipy.signal import find_peaks 5 | 6 | class RR_Algorithm : 7 | def __init__(self, data, fs) : 8 | self.data = data 9 | self.fs = fs 10 | self.N = len(data) 11 | self.Time = self.N / fs 12 | 13 | # # Fast Fourier Transform Method 14 | def FFT(self): 15 | fft_y = fft(self.data) 16 | maxFrequency = self.fs 17 | f = np.linspace(0, maxFrequency, self.N) 18 | abs_y = np.abs(fft_y) 19 | normalization_y = abs_y / self.N 20 | normalization_half_y = normalization_y[range(int(self.N / 2))] 21 | sorted_indices = np.argsort(normalization_half_y) 22 | RR = f[sorted_indices[-2]] * 60 23 | return RR 24 | 25 | # # Peak Counting Method 26 | def PeakCounting(self, Height=args.RR_Algorithm_PC_Height, Threshold=args.RR_Algorithm_PC_Threshold, MaxRR=args.RR_Algorithm_PC_MaxRR): 27 | Distance = 60 / MaxRR * self.fs 28 | peaks, _ = find_peaks(self.data, height=Height, threshold=Threshold, distance=Distance) 29 | RR = len(peaks) / self.Time * 60 30 | return RR 31 | 32 | # # Crossover Point Method 33 | def CrossingPoint(self): 34 | shfit_distance = int(self.fs / 2) 35 | data_shift = np.zeros(self.data.shape) - 1 36 | data_shift[shfit_distance:] = self.data[:-shfit_distance] 37 | cross_curve = self.data - data_shift 38 | 39 | zero_number = 0 40 | zero_index = [] 41 | for i in range(len(cross_curve) - 1) : 42 | if cross_curve[i] == 0 : 43 | zero_number += 1 44 | zero_index.append(i) 45 | else : 46 | if cross_curve[i] * cross_curve[i + 1] < 0 : 47 | zero_number += 1 48 | zero_index.append(i) 49 | 50 | cw = zero_number 51 | N = self.N 52 | fs = self.fs 53 | RR1 = ((cw / 2) / (N / fs)) * 60 54 | 55 | return RR1 56 | 57 | def NegativeFeedbackCrossoverPointMethod(self, QualityLevel=args.RR_Algorithm_NFCP_qualityLevel): 58 | shfit_distance = int(self.fs / 2) 59 | data_shift = np.zeros(self.data.shape) - 1 60 | data_shift[shfit_distance:] = self.data[:-shfit_distance] 61 | cross_curve = self.data - data_shift 62 | 63 | zero_number = 0 64 | zero_index = [] 65 | for i in range(len(cross_curve) - 1) : 66 | if cross_curve[i] == 0 : 67 | zero_number += 1 68 | zero_index.append(i) 69 | else : 70 | if cross_curve[i] * cross_curve[i + 1] < 0 : 71 | zero_number += 1 72 | zero_index.append(i) 73 | 74 | cw = zero_number 75 | N = self.N 76 | fs = self.fs 77 | RR1 = ((cw / 2) / (N / fs)) * 60 78 | 79 | if (len(zero_index) <= 1 ) : 80 | RR2 = RR1 81 | else: 82 | time_span = 60 / RR1 / 2 * fs * QualityLevel 83 | zero_span = [] 84 | for i in range(len(zero_index) - 1) : 85 | zero_span.append(zero_index[i + 1] - zero_index[i]) 86 | 87 | while(min(zero_span) < time_span ) : 88 | doubt_point = np.argmin(zero_span) 89 | zero_index.pop(doubt_point) 90 | zero_index.pop(doubt_point) 91 | if len(zero_index) <= 1: 92 | break 93 | zero_span = [] 94 | for i in range(len(zero_index) - 1): 95 | zero_span.append(zero_index[i + 1] - zero_index[i]) 96 | 97 | zero_number = len(zero_index) 98 | cw = zero_number 99 | N = self.N 100 | fs = self.fs 101 | RR2 = ((cw / 2) / (N / fs)) * 60 102 | 103 | return RR2 104 | -------------------------------------------------------------------------------- /lmagesFolderForReadMe/Application diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/2013584a8cc872ed1bf71b9c5435148a244f73cb/lmagesFolderForReadMe/Application diagram.png -------------------------------------------------------------------------------- /lmagesFolderForReadMe/test2_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/2013584a8cc872ed1bf71b9c5435148a244f73cb/lmagesFolderForReadMe/test2_result.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from params import args 4 | import matplotlib.pyplot as plt 5 | from IOF import ImproveOpticalFlow 6 | 7 | def main(): 8 | video_path = args.video_path 9 | cap = cv2.VideoCapture(video_path) 10 | video_fs = cap.get(5) 11 | 12 | Resp, RR_FFT, RR_PC, RR_CP, RR_NFCP = ImproveOpticalFlow(video_path, 13 | QualityLevel=args.OFP_qualityLevel, 14 | FSS=True, 15 | CGOF=True, 16 | filter=True, 17 | Normalization=True, 18 | RR_Evaluation=True) 19 | print('RR-FFT: {}(bpm)\nRR-PC: {}(bpm)\nRR-CP: {}(bpm)\nRR-NFCP: {}(bpm)'.format(RR_FFT, RR_PC, RR_CP, RR_NFCP)) 20 | t = np.linspace(1, len(Resp) / video_fs, len(Resp)) 21 | plt.plot(t, Resp) 22 | plt.xlabel("Time ( s )") 23 | plt.title('RR-FFT: {}(bpm) RR-PC: {}(bpm)\nRR-CP: {}(bpm) RR-NFCP: {}(bpm)'.format(RR_FFT, RR_PC, RR_CP, RR_NFCP)) 24 | plt.show() 25 | 26 | if __name__ == '__main__': 27 | main() 28 | -------------------------------------------------------------------------------- /params.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | parser = argparse.ArgumentParser('Lightweight Video-based Respiration Rate Detection Algorithm script', add_help=False) 4 | parser.add_argument('--video-path', default='./test2.mp4', help='Video input path') 5 | 6 | # # Optical flow parameters 7 | parser.add_argument('--OFP-maxCorners', default=100, type=int, help='') 8 | parser.add_argument('--OFP-qualityLevel', default=0.1, type=float, help='') 9 | parser.add_argument('--OFP-minDistance', default=7, type=int, help='') 10 | parser.add_argument('--OFP-mask', default=None, help='') 11 | parser.add_argument('--OFP-QualityLevelRV', default=0.05, type=float, help='QualityLeve reduction value') 12 | parser.add_argument('--OFP-winSize', default=(15, 15), help='') 13 | parser.add_argument('--OFP-maxLevel', default=2, type=int, help='') 14 | 15 | # # FeaturePoint Selection Strategy parameters 16 | parser.add_argument('--FSS-switch', action='store_true', dest='FSS_switch') 17 | parser.add_argument('--FSS-maxCorners', default=100, type=int, help='') 18 | parser.add_argument('--FSS-qualityLevel', default=0.1, type=float, help='') 19 | parser.add_argument('--FSS-minDistance', default=7, type=int, help='') 20 | parser.add_argument('--FSS-mask', default=None, help='') 21 | parser.add_argument('--FSS-QualityLevelRV', default=0.05, type=float, help='QualityLeve reduction value') 22 | parser.add_argument('--FSS-FPN', default=5, type=int, help='The number of feature points for the feature point selection strategy') 23 | 24 | # # CCorrelation-Guided Optical Flow Method parameters 25 | parser.add_argument('--CGOF-switch', action='store_true', dest='CGOF_switch') 26 | 27 | # # Filter parameters 28 | parser.add_argument('--Filter-switch', action='store_true', dest='Filter_switch') 29 | parser.add_argument('--Filter-type', default='bandpass', help='') 30 | parser.add_argument('--Filter-order', default=3, type=int, help='') 31 | parser.add_argument('--Filter-LowPass', default=2, type=int, help='') 32 | parser.add_argument('--Filter-HighPass', default=40, type=int, help='') 33 | 34 | # # Normalization parameters 35 | parser.add_argument('--Normalization-switch', action='store_true', dest='Normalization_switch') 36 | 37 | # # RR Evaluation parameters 38 | parser.add_argument('--RR-switch', action='store_true', dest='RR_switch') 39 | 40 | # # RR Algorithm parameters 41 | parser.add_argument('--RR-Algorithm-PC-Height', default=None, help='') 42 | parser.add_argument('--RR-Algorithm-PC-Threshold', default=None, help='') 43 | parser.add_argument('--RR-Algorithm-PC-MaxRR', default=45, type=int, help='') 44 | parser.add_argument('--RR-Algorithm-CP-shfit_distance', default=15, type=int, help='') 45 | parser.add_argument('--RR-Algorithm-NFCP-shfit_distance', default=15, type=int, help='') 46 | parser.add_argument('--RR-Algorithm-NFCP-qualityLevel', default=0.6, type=float, help='') 47 | 48 | args = parser.parse_args() 49 | -------------------------------------------------------------------------------- /test1.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/2013584a8cc872ed1bf71b9c5435148a244f73cb/test1.avi -------------------------------------------------------------------------------- /test2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/2013584a8cc872ed1bf71b9c5435148a244f73cb/test2.mp4 -------------------------------------------------------------------------------- /test3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShawnTan86/Lightweight-Video-based-Respiration-Rate-Detection-Algorithm/2013584a8cc872ed1bf71b9c5435148a244f73cb/test3.mp4 --------------------------------------------------------------------------------