├── .gitignore ├── 3rd.7z ├── Dll_And_Exe.7z ├── LICENSE ├── LandmarkTracking.h ├── MNN_FaceTrack.sln ├── MNN_FaceTrack.vcxproj ├── MNN_FaceTrack.vcxproj.filters ├── MNN_FaceTrack.vcxproj.user ├── README.md ├── main.cpp ├── models.7z ├── mtcnn.cpp └── mtcnn.h /.gitignore: -------------------------------------------------------------------------------- 1 | Release 2 | 3rd 3 | models 4 | .vs 5 | # Prerequisites 6 | *.d 7 | 8 | # Compiled Object files 9 | *.slo 10 | *.lo 11 | *.o 12 | *.obj 13 | 14 | # Precompiled Headers 15 | *.gch 16 | *.pch 17 | *.opendb 18 | *.db 19 | 20 | # Compiled Dynamic libraries 21 | *.so 22 | *.dylib 23 | *.dll 24 | 25 | # Fortran module files 26 | *.mod 27 | *.smod 28 | 29 | # Compiled Static libraries 30 | *.lai 31 | *.la 32 | *.a 33 | *.lib 34 | 35 | # Executables 36 | *.exe 37 | *.out 38 | *.app 39 | -------------------------------------------------------------------------------- /3rd.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qaz734913414/MNN_FaceTrack/f1dbccdd89d9e82f4ffdfbbf3d9d14c62bbd1ce4/3rd.7z -------------------------------------------------------------------------------- /Dll_And_Exe.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qaz734913414/MNN_FaceTrack/f1dbccdd89d9e82f4ffdfbbf3d9d14c62bbd1ce4/Dll_And_Exe.7z -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LandmarkTracking.h: -------------------------------------------------------------------------------- 1 | #ifndef ZEUSEESFACETRACKING_H 2 | #define ZEUSEESFACETRACKING_H 3 | 4 | #include 5 | #include "mtcnn.h" 6 | #include "time.h" 7 | 8 | cv::Rect boundingRect(const std::vector& pts) { 9 | if (pts.size() > 1) 10 | { 11 | int xmin = pts[0].x; 12 | int ymin = pts[0].y; 13 | int xmax = pts[0].x; 14 | int ymax = pts[0].y; 15 | for (int i = 1; i < pts.size(); i++) 16 | { 17 | if (pts[i].x < xmin) 18 | xmin = pts[i].x; 19 | if (pts[i].y < ymin) 20 | ymin = pts[i].y; 21 | if (pts[i].x > xmax) 22 | xmax = pts[i].x; 23 | if (pts[i].y > ymax) 24 | ymax = pts[i].y; 25 | } 26 | return cv::Rect(xmin, ymin, xmax - xmin, ymax - ymin); 27 | } 28 | } 29 | 30 | 31 | //typedef int T; 32 | //T i = 1; 33 | 34 | 35 | class Face { 36 | public: 37 | 38 | Face(int instance_id,cv::Rect loc_t) { 39 | face_id = instance_id; 40 | isCanShow = false; //追踪一次后待框稳定后即可显示 41 | loc = loc_t; 42 | } 43 | 44 | Face() { 45 | 46 | isCanShow = false; //追踪一次后待框稳定后即可显示 47 | } 48 | 49 | FaceInfo faceBbox; 50 | 51 | int face_id = -1; 52 | long frameId = 0; 53 | int ptr_num = 0; 54 | 55 | bool isCanShow; 56 | cv::Mat frame_face_prev; 57 | cv::Rect loc; 58 | //int loseNum = 0; 59 | 60 | static cv::Rect SquarePadding(cv::Rect facebox, int margin_rows, int margin_cols, bool max_b) 61 | { 62 | int c_x = facebox.x + facebox.width / 2; 63 | int c_y = facebox.y + facebox.height / 2; 64 | int large = 0; 65 | if (max_b) 66 | large = max(facebox.height, facebox.width) / 2; 67 | else 68 | large = min(facebox.height, facebox.width) / 2; 69 | cv::Rect rectNot(c_x - large, c_y - large, c_x + large, c_y + large); 70 | rectNot.x = max(0, rectNot.x); 71 | rectNot.y = max(0, rectNot.y); 72 | rectNot.height = min(rectNot.height, margin_rows - 1); 73 | rectNot.width = min(rectNot.width, margin_cols - 1); 74 | if (rectNot.height - rectNot.y != rectNot.width - rectNot.x) 75 | return SquarePadding(cv::Rect(rectNot.x, rectNot.y, rectNot.width - rectNot.x, rectNot.height - rectNot.y), margin_rows, margin_cols, false); 76 | 77 | return cv::Rect(rectNot.x, rectNot.y, rectNot.width - rectNot.x, rectNot.height - rectNot.y); 78 | } 79 | 80 | static cv::Rect SquarePadding(cv::Rect facebox, int padding) 81 | { 82 | 83 | int c_x = facebox.x - padding; 84 | int c_y = facebox.y - padding; 85 | return cv::Rect(facebox.x - padding, facebox.y - padding, facebox.width + padding * 2, facebox.height + padding * 2);; 86 | } 87 | 88 | static double getDistance(cv::Point x, cv::Point y) 89 | { 90 | return sqrt((x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y)); 91 | } 92 | 93 | 94 | }; 95 | 96 | 97 | 98 | class FaceTracking { 99 | public: 100 | FaceTracking(std::string modelPath) 101 | { 102 | this->detector = new MTCNN(); 103 | this->detector->init(modelPath); 104 | this->detector->setIsMaxFace(isMaxFace); 105 | faceMinSize = 80; 106 | this->detector->setMinFace(faceMinSize); 107 | detection_Time = -1; 108 | 109 | } 110 | 111 | ~FaceTracking() { 112 | delete this->detector; 113 | 114 | } 115 | 116 | void detecting(cv::Mat& image) { 117 | 118 | std::vector finalBbox; 119 | detector->Detect_T(image, finalBbox); 120 | 121 | const int num_box = finalBbox.size(); 122 | std::vector bbox; 123 | bbox.resize(num_box); 124 | candidateFaces_lock = 1; 125 | for (int i = 0; i < num_box; i++) { 126 | bbox[i] = cv::Rect(finalBbox[i].bbox.xmin, finalBbox[i].bbox.ymin, finalBbox[i].bbox.xmax - finalBbox[i].bbox.xmin + 1, 127 | finalBbox[i].bbox.ymax - finalBbox[i].bbox.ymin + 1); 128 | bbox[i] = Face::SquarePadding(bbox[i], image.rows, image.cols, true); 129 | 130 | std::shared_ptr face(new Face(trackingID, bbox[i])); 131 | 132 | image(bbox[i]).copyTo(face->frame_face_prev); 133 | 134 | trackingID = trackingID + 1; 135 | candidateFaces.push_back(*face); 136 | } 137 | candidateFaces_lock = 0; 138 | } 139 | 140 | void Init(cv::Mat& image) { 141 | ImageHighDP = image.clone(); 142 | trackingID = 0; 143 | detection_Interval = 150; //detect faces every 200 ms 144 | detecting(image); 145 | stabilization = false; 146 | 147 | } 148 | 149 | void doingLandmark_onet(cv::Mat& img, FaceInfo& faceBbox, cv::Rect &face_roi, int stable_state = 0) { 150 | 151 | faceBbox = detector->onet(img, face_roi); 152 | 153 | } 154 | 155 | 156 | 157 | void tracking_corrfilter(const cv::Mat& frame, const cv::Mat& model, cv::Rect& trackBox, float scale) 158 | { 159 | trackBox.x /= scale; 160 | trackBox.y /= scale; 161 | trackBox.height /= scale; 162 | trackBox.width /= scale; 163 | int zeroadd_x = 0; 164 | int zeroadd_y = 0; 165 | cv::Mat frame_; 166 | cv::Mat model_; 167 | cv::resize(frame, frame_, cv::Size(), 1 / scale, 1 / scale); 168 | cv::resize(model, model_, cv::Size(), 1 / scale, 1 / scale); 169 | cv::Mat gray; 170 | cvtColor(frame_, gray, cv::COLOR_RGB2GRAY); 171 | cv::Mat gray_model; 172 | cvtColor(model_, gray_model, cv::COLOR_RGB2GRAY); 173 | cv::Rect searchWindow; 174 | searchWindow.width = trackBox.width * 3; 175 | searchWindow.height = trackBox.height * 3; 176 | searchWindow.x = trackBox.x + trackBox.width * 0.5 - searchWindow.width * 0.5; 177 | searchWindow.y = trackBox.y + trackBox.height * 0.5 - searchWindow.height * 0.5; 178 | searchWindow &= cv::Rect(0, 0, frame_.cols, frame_.rows); 179 | cv::Mat similarity; 180 | matchTemplate(gray(searchWindow), gray_model, similarity, cv::TM_CCOEFF_NORMED); 181 | double mag_r; 182 | cv::Point point; 183 | minMaxLoc(similarity, 0, &mag_r, 0, &point); 184 | trackBox.x = point.x + searchWindow.x; 185 | trackBox.y = point.y + searchWindow.y; 186 | trackBox.x *= scale; 187 | trackBox.y *= scale; 188 | trackBox.height *= scale; 189 | trackBox.width *= scale; 190 | } 191 | 192 | bool tracking(cv::Mat& image, Face& face) 193 | { 194 | cv::Rect faceROI = face.loc; 195 | //cv::Mat faceROI_Image; 196 | tracking_corrfilter(image, face.frame_face_prev, faceROI, tpm_scale); 197 | 198 | //image(faceROI).copyTo(faceROI_Image); 199 | 200 | FaceInfo temp; 201 | 202 | doingLandmark_onet(image, temp, faceROI, face.frameId > 1); 203 | 204 | //float sim = detector->rnet(image, faceROI); 205 | 206 | float sim = temp.bbox.score; 207 | 208 | if (sim > 0.1) { 209 | //stablize 210 | //float diff_x = 0; 211 | //float diff_y = 0; 212 | cv::Rect bdbox; 213 | 214 | bdbox.x = temp.bbox.xmin; 215 | bdbox.y = temp.bbox.ymin; 216 | bdbox.width = temp.bbox.xmax - temp.bbox.xmin; 217 | bdbox.height = temp.bbox.ymax - temp.bbox.ymin; 218 | 219 | //bdbox = Face::SquarePadding(bdbox, static_cast(bdbox.height * -0.05)); 220 | bdbox = Face::SquarePadding(bdbox, image.rows, image.cols, 1); 221 | 222 | face.faceBbox = temp; 223 | 224 | face.loc = bdbox; 225 | //face.loseNum = 0; 226 | image(face.loc).copyTo(face.frame_face_prev); 227 | face.frameId += 1; 228 | face.isCanShow = true; 229 | 230 | return true; 231 | } 232 | else 233 | { 234 | //face.loseNum++; 235 | return false; 236 | } 237 | 238 | 239 | 240 | } 241 | void setMask(cv::Mat& image, cv::Rect& rect_mask) 242 | { 243 | 244 | int height = image.rows; 245 | int width = image.cols; 246 | cv::Mat subImage = image(rect_mask); 247 | subImage.setTo(0); 248 | } 249 | 250 | void update(cv::Mat& image) 251 | { 252 | ImageHighDP = image.clone(); 253 | //std::cout << trackingFace.size() << std::endl; 254 | if (candidateFaces.size() > 0 && !candidateFaces_lock) 255 | { 256 | for (int i = 0; i < candidateFaces.size(); i++) 257 | { 258 | trackingFace.push_back(candidateFaces[i]); 259 | } 260 | candidateFaces.clear(); 261 | } 262 | for (std::vector::iterator iter = trackingFace.begin(); iter != trackingFace.end();) 263 | { 264 | if (!tracking(image, *iter) /*&& iter->loseNum == 5*/) 265 | { 266 | iter = trackingFace.erase(iter); //追踪失败 则删除此人脸 267 | } 268 | else { 269 | iter++; 270 | } 271 | } 272 | 273 | if (detection_Time < 0) 274 | { 275 | detection_Time = (double)cv::getTickCount(); 276 | } 277 | else { 278 | double diff = (double)(cv::getTickCount() - detection_Time) * 1000 / cv::getTickFrequency(); 279 | if (diff > detection_Interval) 280 | { 281 | //set Mask to protect the tracking face not to be detected. 282 | for (auto& face : trackingFace) 283 | { 284 | setMask(ImageHighDP, face.loc); 285 | } 286 | detection_Time = (double)cv::getTickCount(); 287 | // do detection in thread 288 | detecting(ImageHighDP); 289 | } 290 | 291 | } 292 | } 293 | 294 | 295 | 296 | std::vector trackingFace; //跟踪中的人脸 297 | 298 | private: 299 | 300 | //int isLostDetection; 301 | //int isTracking; 302 | //int isDetection; 303 | cv::Mat ImageHighDP; 304 | 305 | int faceMinSize; 306 | MTCNN* detector; 307 | std::vector candidateFaces; // 将检测到的人脸放入此列队 待跟踪的人脸 308 | bool candidateFaces_lock; 309 | double detection_Time; 310 | double detection_Interval; 311 | int trackingID; 312 | bool stabilization; 313 | int tpm_scale = 2; 314 | bool isMaxFace = true; 315 | }; 316 | #endif //ZEUSEESFACETRACKING_H 317 | -------------------------------------------------------------------------------- /MNN_FaceTrack.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MNN_FaceTrack", "MNN_FaceTrack.vcxproj", "{3B42A14B-6FFE-4CF1-881B-720C2F693394}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Debug|x64.ActiveCfg = Debug|x64 17 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Debug|x64.Build.0 = Debug|x64 18 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Debug|x86.ActiveCfg = Debug|Win32 19 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Debug|x86.Build.0 = Debug|Win32 20 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Release|x64.ActiveCfg = Release|x64 21 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Release|x64.Build.0 = Release|x64 22 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Release|x86.ActiveCfg = Release|Win32 23 | {3B42A14B-6FFE-4CF1-881B-720C2F693394}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /MNN_FaceTrack.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {3B42A14B-6FFE-4CF1-881B-720C2F693394} 23 | Win32Proj 24 | MNN_FaceTrack 25 | 10.0.14393.0 26 | 27 | 28 | 29 | Application 30 | true 31 | v140 32 | Unicode 33 | 34 | 35 | Application 36 | false 37 | v140 38 | true 39 | Unicode 40 | 41 | 42 | Application 43 | true 44 | v141 45 | Unicode 46 | 47 | 48 | Application 49 | false 50 | v141 51 | true 52 | Unicode 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | true 74 | 75 | 76 | true 77 | 78 | 79 | false 80 | 81 | 82 | false 83 | 84 | 85 | 86 | 87 | 88 | Level3 89 | Disabled 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | 92 | 93 | Console 94 | true 95 | 96 | 97 | 98 | 99 | 100 | 101 | Level3 102 | Disabled 103 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 104 | 105 | 106 | Console 107 | true 108 | 109 | 110 | 111 | 112 | Level3 113 | 114 | 115 | MaxSpeed 116 | true 117 | true 118 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 119 | %(AdditionalIncludeDirectories) 120 | 121 | 122 | Console 123 | true 124 | true 125 | true 126 | %(AdditionalLibraryDirectories) 127 | %(AdditionalDependencies) 128 | 129 | 130 | 131 | 132 | Level3 133 | 134 | 135 | MaxSpeed 136 | true 137 | true 138 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 139 | 3rd/opencv/include;3rd/MNN/include;%(AdditionalIncludeDirectories) 140 | 141 | 142 | Console 143 | true 144 | true 145 | true 146 | 3rd/opencv/lib;3rd/MNN/lib;%(AdditionalLibraryDirectories) 147 | MNN.lib;opencv_world411.lib;%(AdditionalDependencies) 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /MNN_FaceTrack.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | 头文件 20 | 21 | 22 | 头文件 23 | 24 | 25 | 26 | 27 | 源文件 28 | 29 | 30 | 源文件 31 | 32 | 33 | -------------------------------------------------------------------------------- /MNN_FaceTrack.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MNN_FaceTrack 2 | 3 | MNN基于mtcnn人脸检测+onet人脸跟踪,在i7-9700k的cpu检测速度可高达500fps。 4 | 5 | # 开发环境 6 | 7 | win7 8 | 9 | vs2015 10 | 11 | 12 | # 开源框架 13 | 14 | + [MNN](https://github.com/alibaba/MNN) 15 | 16 | + [opencv](https://github.com/opencv/opencv) 17 | 18 | # 引用 19 | 20 | [HyperFT](https://github.com/zeusees/HyperFT) 21 | 22 | 这是一个移动端快速视频多人脸跟踪的开源项目,这个项目是基于mtcnn人脸检测加上最简单的模板匹配进行人脸跟踪的,算法简单但效果显著,移动端速度可以达到250帧以上,该项目的特点是可实现多人脸跟踪。 23 | 24 | # 代码算法解析 25 | 26 | HyperFT项目的多人脸跟踪算法分三大部分: 27 | 28 | 第一部分是初始化,通过mtcnn的人脸检测找出第一帧的人脸位置然后将其结果对人脸跟踪进行初始化; 29 | 30 | 第二部分是更新,利用模板匹配进行人脸目标位置的初步预判,再结合mtcnn中的onet来对人脸位置进行更加精细的定位,最后通过mtcnn中的rnet的置信度来判断跟踪是否为人脸,防止当有手从面前慢慢挥过去的话,框会跟着手走而无法跟踪到真正的人脸; 31 | 32 | 第三部分是定时检测,通过在更新的部分中加入一个定时器来做定时人脸检测,从而判断中途是否有新人脸的加入,本项目在定时人脸检测中使用了一个trick就是将已跟踪的人脸所在位置利用蒙版遮蔽起来,避免了人脸检测的重复检测,减少其计算量,从而提高了检测速度。 33 | 34 | # 算法改进的思路(加入五个关键点的跟踪) 35 | 36 | 1、在HyperFT项目中的Face类中仅定义了人脸矩形的变量,如若需要加入五个关键点的跟踪则需要在Face类中需要定义一个Bbox类faceBbox,这样Face即能保存人脸位置又能保存人脸关键点。 37 | 38 | 2、在原来的doingLandmark_onet函数的基础上重载函数,将传入的std::vector &pts改为传入Bbox& faceBbox。 39 | 40 | 3、在tracking函数中修改doingLandmark_onet函数的调用 41 | 42 | 4、通过人脸跟踪中Face类中的faceBbox即可获得人脸的位置及其五个人脸关键点(main.cpp) 43 | 44 | # 相关文章 45 | 46 | 1、[快速目标跟踪方法总结](https://blog.csdn.net/study_all/article/details/102543500) 47 | 48 | 2、[人脸跟踪开源项目HyperFT代码算法解析及改进](https://blog.csdn.net/study_all/article/details/102543847) 49 | 50 | 3、[HyperFT项目安卓端的环境搭建及编译的图解教程](https://blog.csdn.net/study_all/article/details/102544113) 51 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qaz734913414/MNN_FaceTrack/f1dbccdd89d9e82f4ffdfbbf3d9d14c62bbd1ce4/main.cpp -------------------------------------------------------------------------------- /models.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qaz734913414/MNN_FaceTrack/f1dbccdd89d9e82f4ffdfbbf3d9d14c62bbd1ce4/models.7z -------------------------------------------------------------------------------- /mtcnn.cpp: -------------------------------------------------------------------------------- 1 | #include "mtcnn.h" 2 | 3 | 4 | 5 | static uint8_t* get_img(cv::Mat img) { 6 | uchar * colorData = new uchar[img.total() * 4]; 7 | cv::Mat MatTemp(img.size(), CV_8UC4, colorData); 8 | cv::cvtColor(img, MatTemp, cv::COLOR_BGR2RGBA, 4); 9 | //cv::cvtColor(img, MatTemp, type, 4); 10 | return (uint8_t *)MatTemp.data; 11 | } 12 | 13 | static bool CompareBBox(const FaceInfo & a, const FaceInfo & b) { 14 | return a.bbox.score > b.bbox.score; 15 | } 16 | 17 | 18 | static float IoU(float xmin, float ymin, float xmax, float ymax, 19 | float xmin_, float ymin_, float xmax_, float ymax_, bool is_iom) { 20 | float iw = std::min(xmax, xmax_) - std::max(xmin, xmin_) + 1; 21 | float ih = std::min(ymax, ymax_) - std::max(ymin, ymin_) + 1; 22 | if (iw <= 0 || ih <= 0) 23 | return 0; 24 | float s = iw*ih; 25 | if (is_iom) { 26 | float ov = s / std::min((xmax - xmin + 1)*(ymax - ymin + 1), (xmax_ - xmin_ + 1)*(ymax_ - ymin_ + 1)); 27 | return ov; 28 | } 29 | else { 30 | float ov = s / ((xmax - xmin + 1)*(ymax - ymin + 1) + (xmax_ - xmin_ + 1)*(ymax_ - ymin_ + 1) - s); 31 | return ov; 32 | } 33 | } 34 | 35 | static float IoU(FaceInfo f1, FaceInfo f2, bool is_iom) { 36 | float iw = std::min(f1.bbox.xmax, f2.bbox.xmax) - std::max(f1.bbox.xmin, f2.bbox.xmin) + 1; 37 | float ih = std::min(f1.bbox.ymax, f2.bbox.ymax) - std::max(f1.bbox.ymin, f2.bbox.ymin) + 1; 38 | if (iw <= 0 || ih <= 0) 39 | return 0; 40 | float s = iw*ih; 41 | if (is_iom) { 42 | float ov = s / std::min((f1.bbox.xmax - f1.bbox.xmin + 1)*(f1.bbox.ymax - f1.bbox.ymin + 1), (f2.bbox.xmax - f2.bbox.xmin + 1)*(f2.bbox.ymax - f2.bbox.ymin + 1)); 43 | return ov; 44 | } 45 | else { 46 | float ov = s / ((f1.bbox.xmax - f1.bbox.xmin + 1)*(f1.bbox.ymax - f1.bbox.ymin + 1) + (f2.bbox.xmax - f2.bbox.xmin + 1)*(f2.bbox.ymax - f2.bbox.ymin + 1) - s); 47 | return ov; 48 | } 49 | } 50 | 51 | static std::vector NMS(std::vector& bboxes, 52 | float thresh, char methodType) { 53 | std::vector bboxes_nms; 54 | if (bboxes.size() == 0) { 55 | return bboxes_nms; 56 | } 57 | std::sort(bboxes.begin(), bboxes.end(), CompareBBox); 58 | 59 | int32_t select_idx = 0; 60 | int32_t num_bbox = static_cast(bboxes.size()); 61 | std::vector mask_merged(num_bbox, 0); 62 | bool all_merged = false; 63 | 64 | while (!all_merged) { 65 | while (select_idx < num_bbox && mask_merged[select_idx] == 1) 66 | select_idx++; 67 | if (select_idx == num_bbox) { 68 | all_merged = true; 69 | continue; 70 | } 71 | bboxes_nms.push_back(bboxes[select_idx]); 72 | mask_merged[select_idx] = 1; 73 | 74 | FaceBox select_bbox = bboxes[select_idx].bbox; 75 | float area1 = static_cast((select_bbox.xmax - select_bbox.xmin + 1) * (select_bbox.ymax - select_bbox.ymin + 1)); 76 | float x1 = static_cast(select_bbox.xmin); 77 | float y1 = static_cast(select_bbox.ymin); 78 | float x2 = static_cast(select_bbox.xmax); 79 | float y2 = static_cast(select_bbox.ymax); 80 | 81 | select_idx++; 82 | //#ifdef _OPENMP 83 | //#pragma omp parallel for num_threads(threads_num) 84 | //#endif 85 | for (int32_t i = select_idx; i < num_bbox; i++) { 86 | if (mask_merged[i] == 1) 87 | continue; 88 | 89 | FaceBox & bbox_i = bboxes[i].bbox; 90 | float x = std::max(x1, static_cast(bbox_i.xmin)); 91 | float y = std::max(y1, static_cast(bbox_i.ymin)); 92 | float w = std::min(x2, static_cast(bbox_i.xmax)) - x + 1; 93 | float h = std::min(y2, static_cast(bbox_i.ymax)) - y + 1; 94 | if (w <= 0 || h <= 0) 95 | continue; 96 | 97 | float area2 = static_cast((bbox_i.xmax - bbox_i.xmin + 1) * (bbox_i.ymax - bbox_i.ymin + 1)); 98 | float area_intersect = w * h; 99 | 100 | switch (methodType) { 101 | case 'u': 102 | if (static_cast(area_intersect) / (area1 + area2 - area_intersect) > thresh) 103 | mask_merged[i] = 1; 104 | break; 105 | case 'm': 106 | if (static_cast(area_intersect) / std::min(area1, area2) > thresh) 107 | mask_merged[i] = 1; 108 | break; 109 | default: 110 | break; 111 | } 112 | } 113 | } 114 | return bboxes_nms; 115 | } 116 | static void BBoxRegression(vector& bboxes) { 117 | //#ifdef _OPENMP 118 | //#pragma omp parallel for num_threads(threads_num) 119 | //#endif 120 | for (int i = 0; i < bboxes.size(); ++i) { 121 | FaceBox &bbox = bboxes[i].bbox; 122 | float *bbox_reg = bboxes[i].bbox_reg; 123 | float w = bbox.xmax - bbox.xmin + 1; 124 | float h = bbox.ymax - bbox.ymin + 1; 125 | bbox.xmin += bbox_reg[0] * w; 126 | bbox.ymin += bbox_reg[1] * h; 127 | bbox.xmax += bbox_reg[2] * w; 128 | bbox.ymax += bbox_reg[3] * h; 129 | } 130 | } 131 | static void BBoxPad(vector& bboxes, int width, int height) { 132 | //#ifdef _OPENMP 133 | //#pragma omp parallel for num_threads(threads_num) 134 | //#endif 135 | for (int i = 0; i < bboxes.size(); ++i) { 136 | FaceBox &bbox = bboxes[i].bbox; 137 | bbox.xmin = round(std::max(bbox.xmin, 0.f)); 138 | bbox.ymin = round(std::max(bbox.ymin, 0.f)); 139 | bbox.xmax = round(std::min(bbox.xmax, width - 1.f)); 140 | bbox.ymax = round(std::min(bbox.ymax, height - 1.f)); 141 | } 142 | } 143 | static void BBoxPadSquare(vector& bboxes, int width, int height) { 144 | //#ifdef _OPENMP 145 | //#pragma omp parallel for num_threads(threads_num) 146 | //#endif 147 | for (int i = 0; i < bboxes.size(); ++i) { 148 | FaceBox &bbox = bboxes[i].bbox; 149 | float w = bbox.xmax - bbox.xmin + 1; 150 | float h = bbox.ymax - bbox.ymin + 1; 151 | float side = h>w ? h : w; 152 | bbox.xmin = round(std::max(bbox.xmin + (w - side)*0.5f, 0.f)); 153 | bbox.ymin = round(std::max(bbox.ymin + (h - side)*0.5f, 0.f)); 154 | bbox.xmax = round(std::min(bbox.xmin + side - 1, width - 1.f)); 155 | bbox.ymax = round(std::min(bbox.ymin + side - 1, height - 1.f)); 156 | } 157 | } 158 | 159 | 160 | void MTCNN::GenerateBBox(float * confidence_data, float *reg_box, int feature_map_w_, int feature_map_h_, float scale, float thresh) { 161 | 162 | int spatical_size = feature_map_w_*feature_map_h_; 163 | 164 | candidate_boxes_.clear(); 165 | float v_scale = 1.0 / scale; 166 | for (int i = 0; i= thresh) { 169 | int y = i / feature_map_w_; 170 | int x = i - feature_map_w_ * y; 171 | FaceInfo faceInfo; 172 | FaceBox &faceBox = faceInfo.bbox; 173 | 174 | faceBox.xmin = (float)(x * pnet_stride) * v_scale; 175 | faceBox.ymin = (float)(y * pnet_stride) * v_scale; 176 | faceBox.xmax = (float)(x * pnet_stride + pnet_cell_size - 1.f) * v_scale; 177 | faceBox.ymax = (float)(y * pnet_stride + pnet_cell_size - 1.f) * v_scale; 178 | 179 | faceInfo.bbox_reg[0] = reg_box[stride]; 180 | faceInfo.bbox_reg[1] = reg_box[stride + 1]; 181 | faceInfo.bbox_reg[2] = reg_box[stride + 2]; 182 | faceInfo.bbox_reg[3] = reg_box[stride + 3]; 183 | 184 | faceBox.score = confidence_data[stride + 1]; 185 | candidate_boxes_.push_back(faceInfo); 186 | } 187 | } 188 | } 189 | 190 | MTCNN::MTCNN() { 191 | } 192 | 193 | void MTCNN::init(const string& proto_model_dir){ 194 | 195 | PNet_ = std::shared_ptr(MNN::Interpreter::createFromFile((proto_model_dir + "/det1.mnn").c_str())); 196 | 197 | RNet_ = std::shared_ptr(MNN::Interpreter::createFromFile((proto_model_dir + "/det2.mnn").c_str())); 198 | 199 | ONet_ = std::shared_ptr(MNN::Interpreter::createFromFile((proto_model_dir + "/det3-half.mnn").c_str())); 200 | 201 | 202 | MNN::ScheduleConfig config; 203 | config.type = (MNNForwardType)0; 204 | config.numThread = 1; // 1 faster 205 | 206 | BackendConfig backendConfig; 207 | backendConfig.precision = BackendConfig::Precision_Low; 208 | backendConfig.power = BackendConfig::Power_High; 209 | config.backendConfig = &backendConfig; 210 | 211 | sess_p = PNet_->createSession(config); 212 | sess_r = RNet_->createSession(config); 213 | sess_o = ONet_->createSession(config); 214 | 215 | 216 | p_input = PNet_->getSessionInput(sess_p, NULL); 217 | p_out_pro = PNet_->getSessionOutput(sess_p, "prob1"); 218 | p_out_reg = PNet_->getSessionOutput(sess_p, "conv4-2"); 219 | 220 | r_input = RNet_->getSessionInput(sess_r, NULL); 221 | r_out_pro = RNet_->getSessionOutput(sess_r, "prob1"); 222 | r_out_reg = RNet_->getSessionOutput(sess_r, "conv5-2"); 223 | 224 | o_input = ONet_->getSessionInput(sess_o, NULL); 225 | o_out_pro = ONet_->getSessionOutput(sess_o, "prob1"); 226 | o_out_reg = ONet_->getSessionOutput(sess_o, "conv6-2"); 227 | o_out_lank = ONet_->getSessionOutput(sess_o, "conv6-3"); 228 | 229 | ImageProcess::Config config_data; 230 | config_data.filterType = BILINEAR; 231 | const float mean_vals[3] = { mean_val, mean_val, mean_val }; 232 | const float norm_vals[3] = { std_val, std_val, std_val }; 233 | ::memcpy(config_data.mean, mean_vals, sizeof(mean_vals)); 234 | ::memcpy(config_data.normal, norm_vals, sizeof(norm_vals)); 235 | config_data.sourceFormat = RGBA; 236 | config_data.destFormat = RGB; 237 | 238 | pretreat_data = std::shared_ptr(ImageProcess::create(config_data)); 239 | } 240 | 241 | 242 | MTCNN::~MTCNN() { 243 | PNet_->releaseModel(); 244 | RNet_->releaseModel(); 245 | ONet_->releaseModel(); 246 | candidate_boxes_.clear(); 247 | total_boxes_.clear(); 248 | } 249 | 250 | void MTCNN::SetSmooth(bool smooth1) 251 | { 252 | smooth = smooth1; 253 | } 254 | 255 | bool MTCNN::GetSmooth() 256 | { 257 | return smooth; 258 | } 259 | 260 | 261 | void MTCNN::setThrehold(float threhold[3]) 262 | { 263 | threhold_p = threhold[0]; 264 | threhold_r = threhold[1]; 265 | threhold_o = threhold[2]; 266 | } 267 | 268 | void MTCNN::setFactor(float factor1) 269 | { 270 | factor = factor1; 271 | } 272 | 273 | void MTCNN::setThreadNum(int threads_num1) 274 | { 275 | threads_num = threads_num1; 276 | } 277 | 278 | void MTCNN::setIsMaxFace(bool isMaxFace1) 279 | { 280 | isMaxFace = isMaxFace1; 281 | } 282 | 283 | void MTCNN::setMinFace(int min_face1) 284 | { 285 | min_face = min_face1; 286 | } 287 | 288 | vector MTCNN::ProposalNet(const cv::Mat& img, int minSize, float threshold, float factor) { 289 | 290 | int width = img.cols; 291 | int height = img.rows; 292 | float scale = 12.0f / minSize; 293 | float minWH = std::min(height, width) *scale; 294 | std::vector scales; 295 | while (minWH >= 12) { 296 | scales.push_back(scale); 297 | minWH *= factor; 298 | scale *= factor; 299 | } 300 | total_boxes_.clear(); 301 | 302 | uint8_t *pImg = get_img(img); 303 | for (int i = 0; i < scales.size(); i++) { 304 | int ws = (int)std::ceil(width*scales[i]); 305 | int hs = (int)std::ceil(height*scales[i]); 306 | 307 | 308 | std::vector inputDims = { 1, 3, hs, ws }; 309 | PNet_->resizeTensor(p_input, inputDims); 310 | PNet_->resizeSession(sess_p); 311 | 312 | MNN::CV::Matrix trans; 313 | trans.postScale(1.0f / ws, 1.0f / hs); 314 | trans.postScale(width, height); 315 | pretreat_data->setMatrix(trans); 316 | pretreat_data->convert(pImg, width, height, 0, p_input); 317 | 318 | 319 | PNet_->runSession(sess_p); 320 | float * confidence = p_out_pro->host(); 321 | float * reg = p_out_reg->host(); 322 | 323 | int feature_w = p_out_pro->width(); 324 | int feature_h = p_out_pro->height(); 325 | 326 | GenerateBBox(confidence, reg, feature_w, feature_h, scales[i], threshold); 327 | std::vector bboxes_nms = NMS(candidate_boxes_, 0.5f, 'u'); 328 | if (bboxes_nms.size() > 0) { 329 | total_boxes_.insert(total_boxes_.end(), bboxes_nms.begin(), bboxes_nms.end()); 330 | } 331 | } 332 | 333 | int num_box = (int)total_boxes_.size(); 334 | vector res_boxes; 335 | if (num_box != 0) { 336 | res_boxes = NMS(total_boxes_, 0.5f, 'u'); 337 | BBoxRegression(res_boxes); 338 | BBoxPadSquare(res_boxes, width, height); 339 | } 340 | delete pImg; 341 | return res_boxes; 342 | } 343 | 344 | std::vector MTCNN::NextStage(const cv::Mat& image, vector &pre_stage_res, int input_w, int input_h, int stage_num, const float threshold) { 345 | vector res; 346 | int batch_size = pre_stage_res.size(); 347 | 348 | switch (stage_num) { 349 | case 2: { 350 | 351 | for (int n = 0; n < batch_size; ++n) 352 | { 353 | FaceBox &box = pre_stage_res[n].bbox; 354 | cv::Mat roi = image(cv::Rect(cv::Point((int)box.xmin, (int)box.ymin), cv::Point((int)box.xmax, (int)box.ymax))).clone(); 355 | 356 | //cv::imshow("face", roi); 357 | //cv::waitKey(0); 358 | 359 | MNN::CV::Matrix trans; 360 | trans.postScale(1.0 / input_w, 1.0 / input_h); 361 | trans.postScale(roi.cols, roi.rows); 362 | pretreat_data->setMatrix(trans); 363 | 364 | uint8_t *pImg = get_img(roi); 365 | pretreat_data->convert(pImg, roi.cols, roi.rows, 0, r_input); 366 | delete pImg; 367 | RNet_->runSession(sess_r); 368 | 369 | float * confidence = r_out_pro->host(); 370 | float * reg_box = r_out_reg->host(); 371 | 372 | float conf = confidence[1]; 373 | if (conf >= threshold) { 374 | FaceInfo info; 375 | info.bbox.score = conf; 376 | info.bbox.xmin = pre_stage_res[n].bbox.xmin; 377 | info.bbox.ymin = pre_stage_res[n].bbox.ymin; 378 | info.bbox.xmax = pre_stage_res[n].bbox.xmax; 379 | info.bbox.ymax = pre_stage_res[n].bbox.ymax; 380 | for (int i = 0; i < 4; ++i) { 381 | info.bbox_reg[i] = reg_box[i]; 382 | } 383 | res.push_back(info); 384 | 385 | } 386 | } 387 | break; 388 | } 389 | case 3: { 390 | //#ifdef _OPENMP 391 | //#pragma omp parallel for num_threads(threads_num) 392 | //#endif 393 | for (int n = 0; n < batch_size; ++n) 394 | { 395 | FaceBox &box = pre_stage_res[n].bbox; 396 | cv::Mat roi = image(cv::Rect(cv::Point((int)box.xmin, (int)box.ymin), cv::Point((int)box.xmax, (int)box.ymax))).clone(); 397 | 398 | //cv::imshow("face", roi); 399 | //cv::waitKey(0); 400 | 401 | MNN::CV::Matrix trans; 402 | trans.postScale(1.0f / input_w, 1.0f / input_h); 403 | trans.postScale(roi.cols, roi.rows); 404 | pretreat_data->setMatrix(trans); 405 | uint8_t *pImg = get_img(roi); 406 | pretreat_data->convert(pImg, roi.cols, roi.rows, 0, o_input); 407 | delete pImg; 408 | ONet_->runSession(sess_o); 409 | float * confidence = o_out_pro->host(); 410 | float * reg_box = o_out_reg->host(); 411 | float * reg_landmark = o_out_lank->host(); 412 | 413 | float conf = confidence[1]; 414 | //std::cout<<"stage three:"<= threshold) { 416 | FaceInfo info; 417 | info.bbox.score = conf; 418 | info.bbox.xmin = pre_stage_res[n].bbox.xmin; 419 | info.bbox.ymin = pre_stage_res[n].bbox.ymin; 420 | info.bbox.xmax = pre_stage_res[n].bbox.xmax; 421 | info.bbox.ymax = pre_stage_res[n].bbox.ymax; 422 | for (int i = 0; i < 4; ++i) { 423 | info.bbox_reg[i] = reg_box[i]; 424 | } 425 | float w = info.bbox.xmax - info.bbox.xmin + 1.f; 426 | float h = info.bbox.ymax - info.bbox.ymin + 1.f; 427 | for (int i = 0; i < 5; ++i) { 428 | info.landmark[i] = reg_landmark[2 * i] * w + info.bbox.xmin; 429 | info.landmark[5 + i] = reg_landmark[2 * i + 1] * h + info.bbox.ymin; 430 | } 431 | res.push_back(info); 432 | } 433 | } 434 | break; 435 | } 436 | default: 437 | return res; 438 | break; 439 | } 440 | return res; 441 | } 442 | 443 | 444 | static void SmoothBbox(std::vector& finalBbox) 445 | { 446 | static std::vector preBbox_; 447 | for (int i = 0; i < finalBbox.size(); i++) { 448 | for (int j = 0; j < preBbox_.size(); j++) { 449 | //if (IoU(finalBbox[i], preBbox_[j], false) > 0.9) 450 | // finalBbox[i] = preBbox_[j]; 451 | //else if (IoU(finalBbox[i], preBbox_[j], false) > 0.6) { 452 | if (IoU(finalBbox[i], preBbox_[j], false) > 0.85) { 453 | finalBbox[i].bbox.xmin = (finalBbox[i].bbox.xmin + preBbox_[j].bbox.xmin) / 2; 454 | finalBbox[i].bbox.ymin = (finalBbox[i].bbox.ymin + preBbox_[j].bbox.ymin) / 2; 455 | finalBbox[i].bbox.xmax = (finalBbox[i].bbox.xmax + preBbox_[j].bbox.xmax) / 2; 456 | finalBbox[i].bbox.ymax = (finalBbox[i].bbox.ymax + preBbox_[j].bbox.ymax) / 2; 457 | //finalBbox[i].area = (finalBbox[i].x2 - finalBbox[i].x1)*(finalBbox[i].y2 - finalBbox[i].y1); 458 | for (int k = 0; k < 10; k++) 459 | { 460 | finalBbox[i].landmark[k] = (finalBbox[i].landmark[k] + preBbox_[j].landmark[k]) / 2; 461 | } 462 | } 463 | } 464 | } 465 | preBbox_ = finalBbox; 466 | 467 | } 468 | 469 | void MTCNN::Detect_T(const cv::Mat & img, std::vector& result) 470 | { 471 | if (isMaxFace) 472 | { 473 | result = Detect_MaxFace(img); 474 | } 475 | else 476 | { 477 | result = Detect(img); 478 | } 479 | } 480 | 481 | vector MTCNN::Detect(const cv::Mat& image, const int stage) { 482 | 483 | vector pnet_res; 484 | vector rnet_res; 485 | vector onet_res; 486 | 487 | if (stage >= 1) { 488 | pnet_res = ProposalNet(image, min_face, threhold_p, factor); 489 | } 490 | //std::cout<<"p size is:"<= 2 && pnet_res.size()>0) { 492 | if (pnet_max_detect_num < (int)pnet_res.size()) { 493 | pnet_res.resize(pnet_max_detect_num); 494 | } 495 | rnet_res = NextStage(image, pnet_res, 24, 24, 2, threhold_r); 496 | rnet_res = NMS(rnet_res, iou_threhold, 'u'); 497 | BBoxRegression(rnet_res); 498 | BBoxPadSquare(rnet_res, image.cols, image.rows); 499 | } 500 | //std::cout<<"r size is:"<= 3 && rnet_res.size()>0) { 502 | onet_res = NextStage(image, rnet_res, 48, 48, 3, threhold_o); 503 | BBoxRegression(onet_res); 504 | onet_res = NMS(onet_res, iou_threhold, 'm'); 505 | BBoxPad(onet_res, image.cols, image.rows); 506 | } 507 | if (stage == 1) { 508 | if (smooth) 509 | SmoothBbox(pnet_res); 510 | return pnet_res; 511 | } 512 | else if (stage == 2) { 513 | if (smooth) 514 | SmoothBbox(pnet_res); 515 | return rnet_res; 516 | } 517 | else if (stage == 3) { 518 | if (smooth) 519 | SmoothBbox(onet_res); 520 | return onet_res; 521 | } 522 | else { 523 | if (smooth) 524 | SmoothBbox(onet_res); 525 | return onet_res; 526 | } 527 | } 528 | 529 | 530 | static std::vector extractMaxFace(std::vector boundingBox_) 531 | { 532 | if (boundingBox_.empty()) { 533 | return std::vector{}; 534 | } 535 | /* 536 | sort(boundingBox_.begin(), boundingBox_.end(), CompareBBox); 537 | for (std::vector::iterator itx = boundingBox_.begin() + 1; itx != boundingBox_.end();) { 538 | itx = boundingBox_.erase(itx); 539 | } 540 | */ 541 | float max_area = 0; 542 | int index = 0; 543 | for (int i = 0; i < boundingBox_.size(); ++i) { 544 | FaceBox select_bbox = boundingBox_[i].bbox; 545 | float area1 = static_cast((select_bbox.xmax - select_bbox.xmin + 1) * (select_bbox.ymax - select_bbox.ymin + 1)); 546 | if (area1 > max_area) { 547 | max_area = area1; 548 | index = i; 549 | } 550 | } 551 | return std::vector{boundingBox_[index]}; 552 | } 553 | 554 | std::vector MTCNN::Detect_MaxFace(const cv::Mat& img, const int stage) { 555 | vector pnet_res; 556 | vector rnet_res; 557 | vector onet_res; 558 | 559 | //total_boxes_.clear(); 560 | //candidate_boxes_.clear(); 561 | 562 | int width = img.cols; 563 | int height = img.rows; 564 | float scale = 12.0f / min_face; 565 | float minWH = std::min(height, width) *scale; 566 | std::vector scales; 567 | while (minWH >= 12) { 568 | scales.push_back(scale); 569 | minWH *= factor; 570 | scale *= factor; 571 | } 572 | 573 | //sort(scales.begin(), scales.end()); 574 | std::reverse(scales.begin(), scales.end()); 575 | 576 | uint8_t *pImg = get_img(img); 577 | for (int i = 0; i < scales.size(); i++) { 578 | int ws = (int)std::ceil(width*scales[i]); 579 | int hs = (int)std::ceil(height*scales[i]); 580 | std::vector inputDims = { 1, 3, hs, ws }; 581 | PNet_->resizeTensor(p_input, inputDims); 582 | PNet_->resizeSession(sess_p); 583 | 584 | MNN::CV::Matrix trans; 585 | trans.postScale(1.0f / ws, 1.0f / hs); 586 | trans.postScale(width, height); 587 | pretreat_data->setMatrix(trans); 588 | pretreat_data->convert(pImg, width, height, 0, p_input); 589 | 590 | PNet_->runSession(sess_p); 591 | float * confidence = p_out_pro->host(); 592 | float * reg = p_out_reg->host(); 593 | 594 | int feature_w = p_out_pro->width(); 595 | int feature_h = p_out_pro->height(); 596 | 597 | GenerateBBox(confidence, reg, feature_w, feature_h, scales[i], threhold_p); 598 | std::vector bboxes_nms = NMS(candidate_boxes_, 0.5f, 'u'); 599 | 600 | //nmsTwoBoxs(bboxes_nms, pnet_res, 0.5); 601 | if (bboxes_nms.size() > 0) { 602 | pnet_res.insert(pnet_res.end(), bboxes_nms.begin(), bboxes_nms.end()); 603 | } 604 | else { 605 | continue; 606 | } 607 | BBoxRegression(pnet_res); 608 | BBoxPadSquare(pnet_res, width, height); 609 | 610 | bboxes_nms.clear(); 611 | bboxes_nms = NextStage(img, pnet_res, 24, 24, 2, threhold_r); 612 | bboxes_nms = NMS(bboxes_nms, iou_threhold, 'u'); 613 | //nmsTwoBoxs(bboxes_nms, rnet_res, 0.5) 614 | if (bboxes_nms.size() > 0) { 615 | rnet_res.insert(rnet_res.end(), bboxes_nms.begin(), bboxes_nms.end()); 616 | } 617 | else { 618 | pnet_res.clear(); 619 | continue; 620 | } 621 | BBoxRegression(rnet_res); 622 | BBoxPadSquare(rnet_res, img.cols, img.rows); 623 | 624 | 625 | onet_res = NextStage(img, rnet_res, 48, 48, 3, threhold_r); 626 | 627 | BBoxRegression(onet_res); 628 | onet_res = NMS(onet_res, iou_threhold, 'm'); 629 | BBoxPad(onet_res, img.cols, img.rows); 630 | 631 | if (onet_res.size() < 1) { 632 | pnet_res.clear(); 633 | rnet_res.clear(); 634 | continue; 635 | } 636 | else { 637 | onet_res = extractMaxFace(onet_res); 638 | delete pImg; 639 | if (smooth) 640 | SmoothBbox(onet_res); 641 | return onet_res; 642 | } 643 | } 644 | delete pImg; 645 | return std::vector{}; 646 | } 647 | 648 | float MTCNN::rnet(cv::Mat & image, cv::Rect & face_) 649 | { 650 | face_ = cv::Rect(0, 0, image.cols, image.rows)&face_; 651 | cv::Mat roi = image(face_).clone(); 652 | 653 | //cv::imshow("face", roi); 654 | //cv::waitKey(0); 655 | 656 | MNN::CV::Matrix trans; 657 | trans.postScale(1.0 / 24, 1.0 / 24); 658 | trans.postScale(roi.cols, roi.rows); 659 | pretreat_data->setMatrix(trans); 660 | 661 | uint8_t *pImg = get_img(roi); 662 | pretreat_data->convert(pImg, roi.cols, roi.rows, 0, r_input); 663 | delete pImg; 664 | RNet_->runSession(sess_r); 665 | 666 | float * confidence = r_out_pro->host(); 667 | //float * reg_box = r_out_reg->host(); 668 | 669 | float conf = confidence[1]; 670 | return conf; 671 | } 672 | 673 | FaceInfo MTCNN::onet(cv::Mat & image, cv::Rect & face_) 674 | { 675 | FaceInfo faceInfos; 676 | 677 | face_ = cv::Rect(0, 0, image.cols, image.rows)&face_; 678 | cv::Mat roi = image(face_).clone(); 679 | 680 | //cv::imshow("face", roi); 681 | //cv::waitKey(0); 682 | 683 | MNN::CV::Matrix trans; 684 | trans.postScale(1.0 / 48, 1.0 / 48); 685 | trans.postScale(roi.cols, roi.rows); 686 | pretreat_data->setMatrix(trans); 687 | 688 | uint8_t *pImg = get_img(roi); 689 | pretreat_data->convert(pImg, roi.cols, roi.rows, 0, o_input); 690 | delete pImg; 691 | ONet_->runSession(sess_o); 692 | float * confidence = o_out_pro->host(); 693 | float * reg_box = o_out_reg->host(); 694 | float * reg_landmark = o_out_lank->host(); 695 | 696 | float conf = confidence[1]; 697 | //std::cout<<"stage three:"<= threhold_o) { 699 | 700 | faceInfos.bbox.score = conf; 701 | faceInfos.bbox.xmin = face_.x; 702 | faceInfos.bbox.ymin = face_.y; 703 | faceInfos.bbox.xmax = face_.x + face_.width; 704 | faceInfos.bbox.ymax = face_.y + face_.height; 705 | for (int i = 0; i < 4; ++i) { 706 | faceInfos.bbox_reg[i] = reg_box[i]; 707 | } 708 | float w = faceInfos.bbox.xmax - faceInfos.bbox.xmin + 1.f; 709 | float h = faceInfos.bbox.ymax - faceInfos.bbox.ymin + 1.f; 710 | for (int i = 0; i < 5; ++i) { 711 | faceInfos.landmark[i] = reg_landmark[2 * i] * w + faceInfos.bbox.xmin; 712 | faceInfos.landmark[5 + i] = reg_landmark[2 * i + 1] * h + faceInfos.bbox.ymin; 713 | } 714 | //} 715 | return faceInfos; 716 | } 717 | -------------------------------------------------------------------------------- /mtcnn.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qaz734913414/MNN_FaceTrack/f1dbccdd89d9e82f4ffdfbbf3d9d14c62bbd1ce4/mtcnn.h --------------------------------------------------------------------------------