| 1 | /* |
| 2 | * This source code is free software; you can redistribute it and/or |
| 3 | * modify it under the terms of the GNU Public License as published by |
| 4 | * the Free Software Foundation; either version 3 of the License, or |
| 5 | * (at your option) any later version. |
| 6 | * |
| 7 | * This source code is distributed in the hope that it will be useful, |
| 8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Please refer |
| 10 | * to the GNU Public License for more details. |
| 11 | * |
| 12 | * You should have received a copy of the GNU Public License along |
| 13 | * with this source code; if not, write to: Free Software Foundation, |
| 14 | * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
| 15 | */ |
| 16 | |
| 17 | |
| 18 | #include <stdlib.h> |
| 19 | #include <stdio.h> |
| 20 | #include <string.h> |
| 21 | #include <opencv2/opencv.hpp> |
| 22 | #include "frei0r.hpp" |
| 23 | #include "frei0r/math.h" |
| 24 | |
| 25 | class TrackedObj { |
| 26 | public: |
| 27 | void update_hist(); |
| 28 | void update_hue_image (const cv::Mat& image); |
| 29 | cv::RotatedRect camshift_track_face(); |
| 30 | |
| 31 | cv::Mat hsv; //input image converted to HSV |
| 32 | cv::Mat hue; //hue channel of HSV image |
| 33 | cv::Mat mask; //image for masking pixels |
| 34 | cv::Mat prob; //face probability estimates for each pixel |
| 35 | |
| 36 | cv::Mat hist; //histogram of hue in original face image |
| 37 | static const int hist_bins; //number of histogram bins |
| 38 | static const float hist_range[2]; //histogram range |
| 39 | |
| 40 | cv::Rect prev_rect; //location of face in previous frame |
| 41 | cv::RotatedRect curr_box; //current face location estimate |
| 42 | }; |
| 43 | |
| 44 | const float TrackedObj::hist_range[2] = { 0, 180 }; |
| 45 | const int TrackedObj::hist_bins = 30; |
| 46 | |
| 47 | class FaceBl0r: public frei0r::filter { |
| 48 | |
| 49 | public: |
| 50 | FaceBl0r(int wdt, int hgt); |
| 51 | ~FaceBl0r() = default; |
| 52 | |
| 53 | void update(double time, |
| 54 | uint32_t* out, |
| 55 | const uint32_t* in); |
| 56 | |
| 57 | private: |
| 58 | |
| 59 | //trackface |
| 60 | std::vector<cv::Rect> detect_face(); |
| 61 | |
| 62 | TrackedObj tracked_obj; |
| 63 | |
| 64 | //used by capture_video_frame, so we don't have to keep creating. |
| 65 | cv::Mat image; |
| 66 | |
| 67 | cv::CascadeClassifier cascade; |
| 68 | |
| 69 | // plugin parameters |
| 70 | std::string classifier; |
| 71 | bool ellipse; |
| 72 | double recheck; |
| 73 | double threads; |
| 74 | double search_scale; |
| 75 | double neighbors; |
| 76 | double smallest; |
| 77 | double largest; |
| 78 | |
| 79 | std::string old_classifier; |
| 80 | |
| 81 | unsigned int face_found; |
| 82 | unsigned int face_notfound; |
| 83 | }; |
| 84 | |
| 85 | |
| 86 | frei0r::construct<FaceBl0r> plugin("FaceBl0r", |
| 87 | "automatic face blur", |
| 88 | "ZioKernel, Biilly, Jilt, Jaromil, ddennedy", |
| 89 | 1,1, F0R_COLOR_MODEL_BGRA8888); |
| 90 | |
| 91 | FaceBl0r::FaceBl0r(int wdt, int hgt) { |
| 92 | |
| 93 | face_found = 0; |
| 94 | |
| 95 | classifier = "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"; |
| 96 | register_param(classifier, |
| 97 | "Classifier", |
| 98 | "Full path to the XML pattern model for recognition; look in /usr/share/opencv/haarcascades"); |
| 99 | ellipse = false; |
| 100 | register_param(ellipse, "Ellipse", "Draw a red ellipse around the object"); |
| 101 | recheck = 0.025; |
| 102 | face_notfound = cvRound(recheck * 1000); |
| 103 | register_param(recheck, "Recheck", "How often to detect an object in number of frames, divided by 1000"); |
| 104 | threads = 0.01; //number of CPUs |
| 105 | register_param(threads, "Threads", "How many threads to use divided by 100; 0 uses CPU count"); |
| 106 | search_scale = 0.12; // increase size of search window by 20% on each pass |
| 107 | register_param(search_scale, "Search scale", "The search window scale factor, divided by 10"); |
| 108 | neighbors = 0.02; // require 2 neighbors |
| 109 | register_param(neighbors, "Neighbors", "Minimum number of rectangles that makes up an object, divided by 100"); |
| 110 | smallest = 0.0; // smallest window size is trained default |
| 111 | register_param(smallest, "Smallest", "Minimum window size in pixels, divided by 1000"); |
| 112 | largest = 0.0500; // largest object size shown is 500 px |
| 113 | register_param(largest, "Largest", "Maximum object size in pixels, divided by 10000"); |
| 114 | } |
| 115 | |
| 116 | void FaceBl0r::update(double time, |
| 117 | uint32_t* out, |
| 118 | const uint32_t* in) |
| 119 | { |
| 120 | if (cascade.empty()) { |
| 121 | cv::setNumThreads(cvRound(threads * 100)); |
| 122 | if (classifier.length() == 0 || classifier == old_classifier) { |
| 123 | // same as before, avoid repeating error messages |
| 124 | memcpy(out, in, size * 4); // of course assuming we are RGBA only |
| 125 | return; |
| 126 | } |
| 127 | old_classifier = classifier; |
| 128 | } |
| 129 | |
| 130 | if (!cascade.load(classifier.c_str())) { |
| 131 | fprintf(stderr, "ERROR in filter facebl0r, classifier cascade not found:\n"); |
| 132 | fprintf(stderr, " %s\n", classifier.c_str()); |
| 133 | memcpy(out, in, size * 4); |
| 134 | return; |
| 135 | } |
| 136 | |
| 137 | // sanitize parameters |
| 138 | recheck = CLAMP(recheck, 0.001, 1.0); |
| 139 | search_scale = CLAMP(search_scale, 0.11, 1.0); |
| 140 | neighbors = CLAMP(neighbors, 0.01, 1.0); |
| 141 | |
| 142 | // copy input image to OpenCV |
| 143 | image = cv::Mat(height, width, CV_8UC4, (void*)in); |
| 144 | tracked_obj.update_hue_image(image); |
| 145 | |
| 146 | /* |
| 147 | no face* |
| 148 | - look for (detect_face) |
| 149 | yes face |
| 150 | - track face |
| 151 | - no more face |
| 152 | no face* |
| 153 | */ |
| 154 | if(face_notfound>0) { |
| 155 | std::vector<cv::Rect> faces; |
| 156 | if(face_notfound % cvRound(recheck * 1000) == 0) |
| 157 | faces = detect_face(); |
| 158 | |
| 159 | // if no face detected |
| 160 | if (faces.empty()) { |
| 161 | face_notfound++; |
| 162 | } else { |
| 163 | tracked_obj.prev_rect = faces[0]; |
| 164 | tracked_obj.update_hist(); |
| 165 | face_notfound = 0; |
| 166 | face_found++; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | if (face_found > 0) { |
| 171 | //track the face in the new frame |
| 172 | cv::RotatedRect face_box = tracked_obj.camshift_track_face(); |
| 173 | |
| 174 | int min = cvRound(smallest * 1000); |
| 175 | min = min? min : 10; |
| 176 | int max = cvRound(largest * 10000); |
| 177 | if( ( face_box.size.width < min ) |
| 178 | || (face_box.size.height < min ) |
| 179 | || (face_box.size.width > max ) |
| 180 | || (face_box.size.height > max ) |
| 181 | ) { |
| 182 | face_found = 0; |
| 183 | face_notfound++; |
| 184 | } |
| 185 | else { |
| 186 | cv::Rect blur_region = tracked_obj.prev_rect & cv::Rect({0, 0}, image.size()); |
| 187 | cv::Mat blur(image, blur_region); |
| 188 | cv::blur(blur, blur, {23, 23}, cv::Point(-1, -1)); |
| 189 | |
| 190 | //outline face ellipse |
| 191 | if (ellipse) |
| 192 | cv::ellipse(image, face_box, CV_RGB(255,0,0), 2, cv::LINE_AA); |
| 193 | |
| 194 | face_found++; |
| 195 | if(face_found % cvRound(recheck * 1000) == 0) |
| 196 | face_notfound = cvRound(recheck * 1000); // try recheck |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | memcpy(out, image.data, size * 4); |
| 201 | } |
| 202 | |
| 203 | /* Given an image and a classider, detect and return region. */ |
| 204 | std::vector<cv::Rect> FaceBl0r::detect_face() |
| 205 | { |
| 206 | if (cascade.empty()) { |
| 207 | return std::vector<cv::Rect>(); |
| 208 | } |
| 209 | |
| 210 | //use an equalized gray image for better recognition |
| 211 | cv::Mat gray; |
| 212 | cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY); |
| 213 | cv::equalizeHist(gray, gray); |
| 214 | |
| 215 | //get a sequence of faces in image |
| 216 | int min = cvRound(smallest * 1000); |
| 217 | std::vector<cv::Rect> faces; |
| 218 | cascade.detectMultiScale(gray, faces, |
| 219 | search_scale * 10.0, |
| 220 | cvRound(neighbors * 100), |
| 221 | cv::CASCADE_FIND_BIGGEST_OBJECT|//since we track only the first, get the biggest |
| 222 | cv::CASCADE_DO_CANNY_PRUNING, //skip regions unlikely to contain a face |
| 223 | cv::Size(min, min)); |
| 224 | |
| 225 | return faces; |
| 226 | } |
| 227 | |
| 228 | void TrackedObj::update_hist() |
| 229 | { |
| 230 | //create a histogram representation for the face |
| 231 | cv::Mat hue_roi(hue, prev_rect); |
| 232 | cv::Mat mask_roi(mask, prev_rect); |
| 233 | |
| 234 | const float* range = hist_range; |
| 235 | cv::calcHist(&hue_roi, 1, nullptr, mask_roi, hist, 1, &hist_bins, &range); |
| 236 | normalize(hist, hist, 0, 255, cv::NORM_MINMAX); |
| 237 | } |
| 238 | |
| 239 | /* Given an image and tracked object, return box position. */ |
| 240 | cv::RotatedRect TrackedObj::camshift_track_face() |
| 241 | { |
| 242 | //create a probability image based on the face histogram |
| 243 | const float* range = hist_range; |
| 244 | cv::calcBackProject(&hue, 1, nullptr, hist, prob, &range); |
| 245 | prob &= mask; |
| 246 | |
| 247 | //use CamShift to find the center of the new face probability |
| 248 | cv::RotatedRect curr_box = CamShift(prob, prev_rect, |
| 249 | cv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::MAX_ITER, 10, 1 )); |
| 250 | |
| 251 | //update face location |
| 252 | prev_rect = curr_box.boundingRect(); |
| 253 | |
| 254 | return curr_box; |
| 255 | } |
| 256 | |
| 257 | void TrackedObj::update_hue_image (const cv::Mat& image) { |
| 258 | //limits for calculating hue |
| 259 | int vmin = 65, vmax = 256, smin = 55; |
| 260 | |
| 261 | //convert to HSV color model |
| 262 | cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV); |
| 263 | |
| 264 | //mask out-of-range values |
| 265 | cv::inRange(hsv, //source |
| 266 | cv::Scalar(0, smin, MIN(vmin, vmax)), //lower bound |
| 267 | cv::Scalar(180, 256, MAX(vmin, vmax)), //upper bound |
| 268 | mask); //destination |
| 269 | |
| 270 | //extract the hue channel, split: src, dest channels |
| 271 | cv::extractChannel(hsv, hue, 0); |
| 272 | } |