arpadboda commented on a change in pull request #627: MINIFICPP-989 - Motion detect for a set of captured frames URL: https://github.com/apache/nifi-minifi-cpp/pull/627#discussion_r314236627
########## File path: extensions/opencv/MotionDetector.cpp ########## @@ -0,0 +1,222 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MotionDetector.h" + +namespace org { +namespace apache { +namespace nifi { +namespace minifi { +namespace processors { + +core::Property MotionDetector::ImageEncoding( // NOLINT + "Image Encoding", + "The encoding that should be applied the the frame images captured from the RTSP stream", + ".jpg"); +core::Property MotionDetector::MinInterestArea( // NOLINT + "Minimum Area", + "We only consider the movement regions with area greater than this.", + "100"); +core::Property MotionDetector::Threshold( // NOLINT + "Threshold for segmentation", + "Pixel greater than this will be white, otherwise black.", + "42"); +core::Property MotionDetector::BackgroundFrame( // NOLINT + "Path to background frame", + "If not provided then the processor will take the first input frame as background", + ""); +core::Property MotionDetector::DilateIter( // NOLINT + "Dilate iteration", + "For image processing", + "3"); + +core::Property MotionDetector::PrevAsBackground( + core::PropertyBuilder::createProperty("Previous frame as Background") + ->withDescription("Whether or not detect motion between 2 consecutive frames (yes/no)") + ->isRequired(false) + ->withAllowableValues<std::string>({"yes", "no"}) + ->withDefaultValue("no")->build()); + +core::Relationship MotionDetector::Success( // NOLINT + "success", + "Successful to detect motion"); +core::Relationship MotionDetector::Failure( // NOLINT + "failure", + "Failure to detect motion"); + +void MotionDetector::initialize() { + std::set<core::Property> properties; + properties.insert(ImageEncoding); + properties.insert(MinInterestArea); + properties.insert(Threshold); + properties.insert(BackgroundFrame); + properties.insert(DilateIter); + properties.insert(PrevAsBackground); + setSupportedProperties(std::move(properties)); + + std::set<core::Relationship> relationships; + relationships.insert(Success); + relationships.insert(Failure); + setSupportedRelationships(std::move(relationships)); +} + +void MotionDetector::onSchedule(core::ProcessContext *context, core::ProcessSessionFactory *sessionFactory) { + std::string value; + + if (context->getProperty(ImageEncoding.getName(), value)) { + image_encoding_ = value; + } + + if (context->getProperty(MinInterestArea.getName(), value)) { + core::Property::StringToInt(value, min_area_); + } + + if (context->getProperty(Threshold.getName(), value)) { + core::Property::StringToInt(value, threshold_); + } + + if (context->getProperty(DilateIter.getName(), value)) { + core::Property::StringToInt(value, dil_iter_); + } + + if (context->getProperty(BackgroundFrame.getName(), value) && !value.empty()) { + bg_img_ = cv::imread(value, cv::IMREAD_GRAYSCALE); + cv::GaussianBlur(bg_img_, bg_img_, cv::Size(21, 21), 0, 0); + bg_img_.convertTo(background_, CV_32F); + } + + if (context->getProperty(PrevAsBackground.getName(), value)) { + update_bg_ = (value == "yes"); + } + + logger_->log_trace("MotionDetector processor scheduled"); +} + +bool MotionDetector::detectAndDraw(cv::Mat &frame, cv::Mat &diff) { + cv::Mat gray; + cv::Mat img_diff, thresh; + std::vector<cv::Mat> contours; + + cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); + cv::GaussianBlur(gray, gray, cv::Size(21, 21), 0, 0); + + // Get difference between current frame and background + cv::absdiff(gray, bg_img_, img_diff); + cv::threshold(img_diff, thresh, threshold_, 255, cv::THRESH_BINARY); + // Image processing. + cv::dilate(thresh, thresh, cv::Mat(), cv::Point(-1, -1), dil_iter_); + cv::findContours(thresh, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); + + // Finish process + thresh.copyTo(diff); + + bool moved = false; + for(const auto &contour : contours) { + auto area = cv::contourArea(contour); + if (area < min_area_) { + continue; + } + // TODO - Nghia: If a contour exists for >n frames, then we should consider it as background + // TODO - Nghia: How? Map<rectangle, cnt>? + moved = true; + cv::Rect bbox = cv::boundingRect(contour); + cv::rectangle(frame, bbox.tl(), bbox.br(), cv::Scalar(0, 255, 0), 1, 8, 0); + } + if (!moved) { + // Adaptive background, update background so that the illumnation does not affect that much. + cv::accumulateWeighted(gray, background_, 0.5); + cv::convertScaleAbs(background_, bg_img_); + } else if (update_bg_) { + // Use the previous frame as background. + gray.copyTo(bg_img_); + } + return moved; +} + +void MotionDetector::onTrigger(const std::shared_ptr<core::ProcessContext> &context, + const std::shared_ptr<core::ProcessSession> &session) { + std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock); + if (!lock.owns_lock()) { + logger_->log_info("Cannot process due to an unfinished onTrigger"); + context->yield(); + return; + } + + auto flow_file = session->get(); + if (!flow_file) { + logger_->log_info("Empty flow file"); + return; + } + cv::Mat frame; + + FrameReadCallback cb(&frame); + session->read(flow_file, &cb); + + if (frame.empty()) { + logger_->log_error("Empty frame."); + session->transfer(flow_file, Failure); + } + + // hardcoded width to 500 + double scale = float(500)/frame.size().width; + cv::resize(frame, frame, cv::Size(0, 0), scale, scale); + + if (background_.empty()) { + logger_->log_info("Background is missing, update and exit."); + cv::cvtColor(frame, bg_img_, cv::COLOR_BGR2GRAY); + cv::GaussianBlur(bg_img_, bg_img_, cv::Size(21, 21), 0, 0); +// cv::equalizeHist(bg_img_, bg_img_); + bg_img_.convertTo(background_, CV_32F); + return; + } + logger_->log_info("Start motion detecting"); + + cv::Mat img_diff; + auto diff_file = session->create(); + + auto t = std::time(nullptr); + auto tm = *std::localtime(&t); + std::ostringstream oss; + oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S"); + auto filename = oss.str(); + auto filename2 = filename + "_diff"; + filename.append(image_encoding_); + filename2.append(image_encoding_); + + detectAndDraw(frame, img_diff); + + FrameWriteCallback write_cb(frame, image_encoding_); + FrameWriteCallback write_cb2(img_diff, image_encoding_); + + session->putAttribute(flow_file, "filename", filename); + session->putAttribute(diff_file, "filename", filename2); + + session->write(flow_file, &write_cb); + session->write(diff_file, &write_cb2); + session->transfer(flow_file, Success); + session->transfer(diff_file, Success); Review comment: I'm not sure if these two should be transferred to the same relationship. Do we need the original FF anyway? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
