Path: blob/master/modules/videostab/src/stabilizer.cpp
16354 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.13// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "precomp.hpp"43#include "opencv2/videostab/stabilizer.hpp"44#include "opencv2/videostab/ring_buffer.hpp"4546// for debug purposes47#define SAVE_MOTIONS 04849namespace cv50{51namespace videostab52{5354StabilizerBase::StabilizerBase()55{56setLog(makePtr<LogToStdout>());57setFrameSource(makePtr<NullFrameSource>());58setMotionEstimator(makePtr<KeypointBasedMotionEstimator>(makePtr<MotionEstimatorRansacL2>()));59setDeblurer(makePtr<NullDeblurer>());60setInpainter(makePtr<NullInpainter>());61setRadius(15);62setTrimRatio(0);63setCorrectionForInclusion(false);64setBorderMode(BORDER_REPLICATE);65curPos_ = 0;66doDeblurring_ = false;67doInpainting_ = false;68processingStartTime_ = 0;69curStabilizedPos_ = 0;70}717273void StabilizerBase::reset()74{75frameSize_ = Size(0, 0);76frameMask_ = Mat();77curPos_ = -1;78curStabilizedPos_ = -1;79doDeblurring_ = false;80preProcessedFrame_ = Mat();81doInpainting_ = false;82inpaintingMask_ = Mat();83frames_.clear();84motions_.clear();85blurrinessRates_.clear();86stabilizedFrames_.clear();87stabilizedMasks_.clear();88stabilizationMotions_.clear();89processingStartTime_ = 0;90}919293Mat StabilizerBase::nextStabilizedFrame()94{95// check if we've processed all frames already96if (curStabilizedPos_ == curPos_ && curStabilizedPos_ != -1)97{98logProcessingTime();99return Mat();100}101102bool processed;103do processed = doOneIteration();104while (processed && curStabilizedPos_ == -1);105106// check if the frame source is empty107if (curStabilizedPos_ == -1)108{109logProcessingTime();110return Mat();111}112113return postProcessFrame(at(curStabilizedPos_, stabilizedFrames_));114}115116117bool StabilizerBase::doOneIteration()118{119Mat frame = frameSource_->nextFrame();120if (!frame.empty())121{122curPos_++;123124if (curPos_ > 0)125{126at(curPos_, frames_) = frame;127128if (doDeblurring_)129at(curPos_, blurrinessRates_) = calcBlurriness(frame);130131at(curPos_ - 1, motions_) = estimateMotion();132133if (curPos_ >= radius_)134{135curStabilizedPos_ = curPos_ - radius_;136stabilizeFrame();137}138}139else140setUp(frame);141142log_->print(".");143return true;144}145146if (curStabilizedPos_ < curPos_)147{148curStabilizedPos_++;149at(curStabilizedPos_ + radius_, frames_) = at(curPos_, frames_);150at(curStabilizedPos_ + radius_ - 1, motions_) = Mat::eye(3, 3, CV_32F);151stabilizeFrame();152153log_->print(".");154return true;155}156157return false;158}159160161void StabilizerBase::setUp(const Mat &firstFrame)162{163InpainterBase *inpaint = inpainter_.get();164doInpainting_ = dynamic_cast<NullInpainter*>(inpaint) == 0;165if (doInpainting_)166{167inpainter_->setMotionModel(motionEstimator_->motionModel());168inpainter_->setFrames(frames_);169inpainter_->setMotions(motions_);170inpainter_->setStabilizedFrames(stabilizedFrames_);171inpainter_->setStabilizationMotions(stabilizationMotions_);172}173174DeblurerBase *deblurer = deblurer_.get();175doDeblurring_ = dynamic_cast<NullDeblurer*>(deblurer) == 0;176if (doDeblurring_)177{178blurrinessRates_.resize(2*radius_ + 1);179float blurriness = calcBlurriness(firstFrame);180for (int i = -radius_; i <= 0; ++i)181at(i, blurrinessRates_) = blurriness;182deblurer_->setFrames(frames_);183deblurer_->setMotions(motions_);184deblurer_->setBlurrinessRates(blurrinessRates_);185}186187log_->print("processing frames");188processingStartTime_ = clock();189}190191192void StabilizerBase::stabilizeFrame()193{194Mat stabilizationMotion = estimateStabilizationMotion();195if (doCorrectionForInclusion_)196stabilizationMotion = ensureInclusionConstraint(stabilizationMotion, frameSize_, trimRatio_);197198at(curStabilizedPos_, stabilizationMotions_) = stabilizationMotion;199200if (doDeblurring_)201{202at(curStabilizedPos_, frames_).copyTo(preProcessedFrame_);203deblurer_->deblur(curStabilizedPos_, preProcessedFrame_);204}205else206preProcessedFrame_ = at(curStabilizedPos_, frames_);207208// apply stabilization transformation209210if (motionEstimator_->motionModel() != MM_HOMOGRAPHY)211warpAffine(212preProcessedFrame_, at(curStabilizedPos_, stabilizedFrames_),213stabilizationMotion(Rect(0,0,3,2)), frameSize_, INTER_LINEAR, borderMode_);214else215warpPerspective(216preProcessedFrame_, at(curStabilizedPos_, stabilizedFrames_),217stabilizationMotion, frameSize_, INTER_LINEAR, borderMode_);218219if (doInpainting_)220{221if (motionEstimator_->motionModel() != MM_HOMOGRAPHY)222warpAffine(223frameMask_, at(curStabilizedPos_, stabilizedMasks_),224stabilizationMotion(Rect(0,0,3,2)), frameSize_, INTER_NEAREST);225else226warpPerspective(227frameMask_, at(curStabilizedPos_, stabilizedMasks_),228stabilizationMotion, frameSize_, INTER_NEAREST);229230erode(at(curStabilizedPos_, stabilizedMasks_), at(curStabilizedPos_, stabilizedMasks_),231Mat());232233at(curStabilizedPos_, stabilizedMasks_).copyTo(inpaintingMask_);234235inpainter_->inpaint(236curStabilizedPos_, at(curStabilizedPos_, stabilizedFrames_), inpaintingMask_);237}238}239240241Mat StabilizerBase::postProcessFrame(const Mat &frame)242{243// trim frame244int dx = static_cast<int>(floor(trimRatio_ * frame.cols));245int dy = static_cast<int>(floor(trimRatio_ * frame.rows));246return frame(Rect(dx, dy, frame.cols - 2*dx, frame.rows - 2*dy));247}248249250void StabilizerBase::logProcessingTime()251{252clock_t elapsedTime = clock() - processingStartTime_;253log_->print("\nprocessing time: %.3f sec\n", static_cast<double>(elapsedTime) / CLOCKS_PER_SEC);254}255256257OnePassStabilizer::OnePassStabilizer()258{259setMotionFilter(makePtr<GaussianMotionFilter>());260reset();261}262263264void OnePassStabilizer::reset()265{266StabilizerBase::reset();267}268269270void OnePassStabilizer::setUp(const Mat &firstFrame)271{272frameSize_ = firstFrame.size();273frameMask_.create(frameSize_, CV_8U);274frameMask_.setTo(255);275276int cacheSize = 2*radius_ + 1;277frames_.resize(cacheSize);278stabilizedFrames_.resize(cacheSize);279stabilizedMasks_.resize(cacheSize);280motions_.resize(cacheSize);281stabilizationMotions_.resize(cacheSize);282283for (int i = -radius_; i < 0; ++i)284{285at(i, motions_) = Mat::eye(3, 3, CV_32F);286at(i, frames_) = firstFrame;287}288289at(0, frames_) = firstFrame;290291StabilizerBase::setUp(firstFrame);292}293294295Mat OnePassStabilizer::estimateMotion()296{297return motionEstimator_->estimate(at(curPos_ - 1, frames_), at(curPos_, frames_));298}299300301Mat OnePassStabilizer::estimateStabilizationMotion()302{303return motionFilter_->stabilize(curStabilizedPos_, motions_, std::make_pair(0, curPos_));304}305306307Mat OnePassStabilizer::postProcessFrame(const Mat &frame)308{309return StabilizerBase::postProcessFrame(frame);310}311312313TwoPassStabilizer::TwoPassStabilizer()314{315setMotionStabilizer(makePtr<GaussianMotionFilter>());316setWobbleSuppressor(makePtr<NullWobbleSuppressor>());317setEstimateTrimRatio(false);318reset();319}320321322void TwoPassStabilizer::reset()323{324StabilizerBase::reset();325frameCount_ = 0;326isPrePassDone_ = false;327doWobbleSuppression_ = false;328motions2_.clear();329suppressedFrame_ = Mat();330}331332333Mat TwoPassStabilizer::nextFrame()334{335runPrePassIfNecessary();336return StabilizerBase::nextStabilizedFrame();337}338339340#if SAVE_MOTIONS341static void saveMotions(342int frameCount, const std::vector<Mat> &motions, const std::vector<Mat> &stabilizationMotions)343{344std::ofstream fm("log_motions.csv");345for (int i = 0; i < frameCount - 1; ++i)346{347Mat_<float> M = at(i, motions);348fm << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "349<< M(1,0) << " " << M(1,1) << " " << M(1,2) << " "350<< M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;351}352std::ofstream fo("log_orig.csv");353for (int i = 0; i < frameCount; ++i)354{355Mat_<float> M = getMotion(0, i, motions);356fo << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "357<< M(1,0) << " " << M(1,1) << " " << M(1,2) << " "358<< M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;359}360std::ofstream fs("log_stab.csv");361for (int i = 0; i < frameCount; ++i)362{363Mat_<float> M = stabilizationMotions[i] * getMotion(0, i, motions);364fs << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "365<< M(1,0) << " " << M(1,1) << " " << M(1,2) << " "366<< M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;367}368}369#endif370371372void TwoPassStabilizer::runPrePassIfNecessary()373{374if (!isPrePassDone_)375{376// check if we must do wobble suppression377378WobbleSuppressorBase *wobble = wobbleSuppressor_.get();379doWobbleSuppression_ = dynamic_cast<NullWobbleSuppressor*>(wobble) == 0;380381// estimate motions382383clock_t startTime = clock();384log_->print("first pass: estimating motions");385386Mat prevFrame, frame;387bool ok = true, ok2 = true;388389while (!(frame = frameSource_->nextFrame()).empty())390{391if (frameCount_ > 0)392{393motions_.push_back(motionEstimator_->estimate(prevFrame, frame, &ok));394395if (doWobbleSuppression_)396{397Mat M = wobbleSuppressor_->motionEstimator()->estimate(prevFrame, frame, &ok2);398if (ok2)399motions2_.push_back(M);400else401motions2_.push_back(motions_.back());402}403404if (ok)405{406if (ok2) log_->print(".");407else log_->print("?");408}409else log_->print("x");410}411else412{413frameSize_ = frame.size();414frameMask_.create(frameSize_, CV_8U);415frameMask_.setTo(255);416}417418prevFrame = frame;419frameCount_++;420}421422clock_t elapsedTime = clock() - startTime;423log_->print("\nmotion estimation time: %.3f sec\n",424static_cast<double>(elapsedTime) / CLOCKS_PER_SEC);425426// add aux. motions427428for (int i = 0; i < radius_; ++i)429motions_.push_back(Mat::eye(3, 3, CV_32F));430431// stabilize432433startTime = clock();434435stabilizationMotions_.resize(frameCount_);436motionStabilizer_->stabilize(437frameCount_, motions_, std::make_pair(0, frameCount_ - 1), &stabilizationMotions_[0]);438439elapsedTime = clock() - startTime;440log_->print("motion stabilization time: %.3f sec\n",441static_cast<double>(elapsedTime) / CLOCKS_PER_SEC);442443// estimate optimal trim ratio if necessary444445if (mustEstTrimRatio_)446{447trimRatio_ = 0;448for (int i = 0; i < frameCount_; ++i)449{450Mat S = stabilizationMotions_[i];451trimRatio_ = std::max(trimRatio_, estimateOptimalTrimRatio(S, frameSize_));452}453log_->print("estimated trim ratio: %f\n", static_cast<double>(trimRatio_));454}455456#if SAVE_MOTIONS457saveMotions(frameCount_, motions_, stabilizationMotions_);458#endif459460isPrePassDone_ = true;461frameSource_->reset();462}463}464465466void TwoPassStabilizer::setUp(const Mat &firstFrame)467{468int cacheSize = 2*radius_ + 1;469frames_.resize(cacheSize);470stabilizedFrames_.resize(cacheSize);471stabilizedMasks_.resize(cacheSize);472473for (int i = -radius_; i <= 0; ++i)474at(i, frames_) = firstFrame;475476WobbleSuppressorBase *wobble = wobbleSuppressor_.get();477doWobbleSuppression_ = dynamic_cast<NullWobbleSuppressor*>(wobble) == 0;478if (doWobbleSuppression_)479{480wobbleSuppressor_->setFrameCount(frameCount_);481wobbleSuppressor_->setMotions(motions_);482wobbleSuppressor_->setMotions2(motions2_);483wobbleSuppressor_->setStabilizationMotions(stabilizationMotions_);484}485486StabilizerBase::setUp(firstFrame);487}488489490Mat TwoPassStabilizer::estimateMotion()491{492return motions_[curPos_ - 1].clone();493}494495496Mat TwoPassStabilizer::estimateStabilizationMotion()497{498return stabilizationMotions_[curStabilizedPos_].clone();499}500501502Mat TwoPassStabilizer::postProcessFrame(const Mat &frame)503{504wobbleSuppressor_->suppress(curStabilizedPos_, frame, suppressedFrame_);505return StabilizerBase::postProcessFrame(suppressedFrame_);506}507508} // namespace videostab509} // namespace cv510511512