Path: blob/master/modules/stitching/src/seam_finders.cpp
16337 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, 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/imgproc/detail/gcgraph.hpp"44#include <map>4546namespace cv {47namespace detail {4849void PairwiseSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,50std::vector<UMat> &masks)51{52LOGLN("Finding seams...");53if (src.size() == 0)54return;5556#if ENABLE_LOG57int64 t = getTickCount();58#endif5960images_ = src;61sizes_.resize(src.size());62for (size_t i = 0; i < src.size(); ++i)63sizes_[i] = src[i].size();64corners_ = corners;65masks_ = masks;66run();6768LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");69}707172void PairwiseSeamFinder::run()73{74for (size_t i = 0; i < sizes_.size() - 1; ++i)75{76for (size_t j = i + 1; j < sizes_.size(); ++j)77{78Rect roi;79if (overlapRoi(corners_[i], corners_[j], sizes_[i], sizes_[j], roi))80findInPair(i, j, roi);81}82}83}8485void VoronoiSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,86std::vector<UMat> &masks)87{88PairwiseSeamFinder::find(src, corners, masks);89}9091void VoronoiSeamFinder::find(const std::vector<Size> &sizes, const std::vector<Point> &corners,92std::vector<UMat> &masks)93{94LOGLN("Finding seams...");95if (sizes.size() == 0)96return;9798#if ENABLE_LOG99int64 t = getTickCount();100#endif101102sizes_ = sizes;103corners_ = corners;104masks_ = masks;105run();106107LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");108}109110111void VoronoiSeamFinder::findInPair(size_t first, size_t second, Rect roi)112{113const int gap = 10;114Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);115Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);116117Size img1 = sizes_[first], img2 = sizes_[second];118Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW);119Point tl1 = corners_[first], tl2 = corners_[second];120121// Cut submasks with some gap122for (int y = -gap; y < roi.height + gap; ++y)123{124for (int x = -gap; x < roi.width + gap; ++x)125{126int y1 = roi.y - tl1.y + y;127int x1 = roi.x - tl1.x + x;128if (y1 >= 0 && x1 >= 0 && y1 < img1.height && x1 < img1.width)129submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);130else131submask1.at<uchar>(y + gap, x + gap) = 0;132133int y2 = roi.y - tl2.y + y;134int x2 = roi.x - tl2.x + x;135if (y2 >= 0 && x2 >= 0 && y2 < img2.height && x2 < img2.width)136submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);137else138submask2.at<uchar>(y + gap, x + gap) = 0;139}140}141142Mat collision = (submask1 != 0) & (submask2 != 0);143Mat unique1 = submask1.clone(); unique1.setTo(0, collision);144Mat unique2 = submask2.clone(); unique2.setTo(0, collision);145146Mat dist1, dist2;147distanceTransform(unique1 == 0, dist1, DIST_L1, 3);148distanceTransform(unique2 == 0, dist2, DIST_L1, 3);149150Mat seam = dist1 < dist2;151152for (int y = 0; y < roi.height; ++y)153{154for (int x = 0; x < roi.width; ++x)155{156if (seam.at<uchar>(y + gap, x + gap))157mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;158else159mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;160}161}162}163164165DpSeamFinder::DpSeamFinder(CostFunction costFunc) : costFunc_(costFunc), ncomps_(0) {}166167168void DpSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks)169{170LOGLN("Finding seams...");171#if ENABLE_LOG172int64 t = getTickCount();173#endif174175if (src.size() == 0)176return;177178std::vector<std::pair<size_t, size_t> > pairs;179180for (size_t i = 0; i+1 < src.size(); ++i)181for (size_t j = i+1; j < src.size(); ++j)182pairs.push_back(std::make_pair(i, j));183184{185std::vector<Mat> _src(src.size());186for (size_t i = 0; i < src.size(); ++i) _src[i] = src[i].getMat(ACCESS_READ);187sort(pairs.begin(), pairs.end(), ImagePairLess(_src, corners));188}189std::reverse(pairs.begin(), pairs.end());190191for (size_t i = 0; i < pairs.size(); ++i)192{193size_t i0 = pairs[i].first, i1 = pairs[i].second;194Mat mask0 = masks[i0].getMat(ACCESS_RW), mask1 = masks[i1].getMat(ACCESS_RW);195process(src[i0].getMat(ACCESS_READ), src[i1].getMat(ACCESS_READ), corners[i0], corners[i1], mask0, mask1);196}197198LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");199}200201202void DpSeamFinder::process(203const Mat &image1, const Mat &image2, Point tl1, Point tl2,204Mat &mask1, Mat &mask2)205{206CV_INSTRUMENT_REGION();207208CV_Assert(image1.size() == mask1.size());209CV_Assert(image2.size() == mask2.size());210211Point intersectTl(std::max(tl1.x, tl2.x), std::max(tl1.y, tl2.y));212213Point intersectBr(std::min(tl1.x + image1.cols, tl2.x + image2.cols),214std::min(tl1.y + image1.rows, tl2.y + image2.rows));215216if (intersectTl.x >= intersectBr.x || intersectTl.y >= intersectBr.y)217return; // there are no conflicts218219unionTl_ = Point(std::min(tl1.x, tl2.x), std::min(tl1.y, tl2.y));220221unionBr_ = Point(std::max(tl1.x + image1.cols, tl2.x + image2.cols),222std::max(tl1.y + image1.rows, tl2.y + image2.rows));223224unionSize_ = Size(unionBr_.x - unionTl_.x, unionBr_.y - unionTl_.y);225226mask1_ = Mat::zeros(unionSize_, CV_8U);227mask2_ = Mat::zeros(unionSize_, CV_8U);228229Mat tmp = mask1_(Rect(tl1.x - unionTl_.x, tl1.y - unionTl_.y, mask1.cols, mask1.rows));230mask1.copyTo(tmp);231232tmp = mask2_(Rect(tl2.x - unionTl_.x, tl2.y - unionTl_.y, mask2.cols, mask2.rows));233mask2.copyTo(tmp);234235// find both images contour masks236237contour1mask_ = Mat::zeros(unionSize_, CV_8U);238contour2mask_ = Mat::zeros(unionSize_, CV_8U);239240for (int y = 0; y < unionSize_.height; ++y)241{242for (int x = 0; x < unionSize_.width; ++x)243{244if (mask1_(y, x) &&245((x == 0 || !mask1_(y, x-1)) || (x == unionSize_.width-1 || !mask1_(y, x+1)) ||246(y == 0 || !mask1_(y-1, x)) || (y == unionSize_.height-1 || !mask1_(y+1, x))))247{248contour1mask_(y, x) = 255;249}250251if (mask2_(y, x) &&252((x == 0 || !mask2_(y, x-1)) || (x == unionSize_.width-1 || !mask2_(y, x+1)) ||253(y == 0 || !mask2_(y-1, x)) || (y == unionSize_.height-1 || !mask2_(y+1, x))))254{255contour2mask_(y, x) = 255;256}257}258}259260findComponents();261262findEdges();263264resolveConflicts(image1, image2, tl1, tl2, mask1, mask2);265}266267268void DpSeamFinder::findComponents()269{270// label all connected components and get information about them271272ncomps_ = 0;273labels_.create(unionSize_);274states_.clear();275tls_.clear();276brs_.clear();277contours_.clear();278279for (int y = 0; y < unionSize_.height; ++y)280{281for (int x = 0; x < unionSize_.width; ++x)282{283if (mask1_(y, x) && mask2_(y, x))284labels_(y, x) = std::numeric_limits<int>::max();285else if (mask1_(y, x))286labels_(y, x) = std::numeric_limits<int>::max()-1;287else if (mask2_(y, x))288labels_(y, x) = std::numeric_limits<int>::max()-2;289else290labels_(y, x) = 0;291}292}293294for (int y = 0; y < unionSize_.height; ++y)295{296for (int x = 0; x < unionSize_.width; ++x)297{298if (labels_(y, x) >= std::numeric_limits<int>::max()-2)299{300if (labels_(y, x) == std::numeric_limits<int>::max())301states_.push_back(INTERS);302else if (labels_(y, x) == std::numeric_limits<int>::max()-1)303states_.push_back(FIRST);304else if (labels_(y, x) == std::numeric_limits<int>::max()-2)305states_.push_back(SECOND);306307floodFill(labels_, Point(x, y), ++ncomps_);308tls_.push_back(Point(x, y));309brs_.push_back(Point(x+1, y+1));310contours_.push_back(std::vector<Point>());311}312313if (labels_(y, x))314{315int l = labels_(y, x);316int ci = l-1;317318tls_[ci].x = std::min(tls_[ci].x, x);319tls_[ci].y = std::min(tls_[ci].y, y);320brs_[ci].x = std::max(brs_[ci].x, x+1);321brs_[ci].y = std::max(brs_[ci].y, y+1);322323if ((x == 0 || labels_(y, x-1) != l) || (x == unionSize_.width-1 || labels_(y, x+1) != l) ||324(y == 0 || labels_(y-1, x) != l) || (y == unionSize_.height-1 || labels_(y+1, x) != l))325{326contours_[ci].push_back(Point(x, y));327}328}329}330}331}332333334void DpSeamFinder::findEdges()335{336// find edges between components337338std::map<std::pair<int, int>, int> wedges; // weighted edges339340for (int ci = 0; ci < ncomps_-1; ++ci)341{342for (int cj = ci+1; cj < ncomps_; ++cj)343{344wedges[std::make_pair(ci, cj)] = 0;345wedges[std::make_pair(cj, ci)] = 0;346}347}348349for (int ci = 0; ci < ncomps_; ++ci)350{351for (size_t i = 0; i < contours_[ci].size(); ++i)352{353int x = contours_[ci][i].x;354int y = contours_[ci][i].y;355int l = ci + 1;356357if (x > 0 && labels_(y, x-1) && labels_(y, x-1) != l)358{359wedges[std::make_pair(ci, labels_(y, x-1)-1)]++;360wedges[std::make_pair(labels_(y, x-1)-1, ci)]++;361}362363if (y > 0 && labels_(y-1, x) && labels_(y-1, x) != l)364{365wedges[std::make_pair(ci, labels_(y-1, x)-1)]++;366wedges[std::make_pair(labels_(y-1, x)-1, ci)]++;367}368369if (x < unionSize_.width-1 && labels_(y, x+1) && labels_(y, x+1) != l)370{371wedges[std::make_pair(ci, labels_(y, x+1)-1)]++;372wedges[std::make_pair(labels_(y, x+1)-1, ci)]++;373}374375if (y < unionSize_.height-1 && labels_(y+1, x) && labels_(y+1, x) != l)376{377wedges[std::make_pair(ci, labels_(y+1, x)-1)]++;378wedges[std::make_pair(labels_(y+1, x)-1, ci)]++;379}380}381}382383edges_.clear();384385for (int ci = 0; ci < ncomps_-1; ++ci)386{387for (int cj = ci+1; cj < ncomps_; ++cj)388{389std::map<std::pair<int, int>, int>::iterator itr = wedges.find(std::make_pair(ci, cj));390if (itr != wedges.end() && itr->second > 0)391edges_.insert(itr->first);392393itr = wedges.find(std::make_pair(cj, ci));394if (itr != wedges.end() && itr->second > 0)395edges_.insert(itr->first);396}397}398}399400401void DpSeamFinder::resolveConflicts(402const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2)403{404if (costFunc_ == COLOR_GRAD)405computeGradients(image1, image2);406407// resolve conflicts between components408409bool hasConflict = true;410while (hasConflict)411{412int c1 = 0, c2 = 0;413hasConflict = false;414415for (std::set<std::pair<int, int> >::iterator itr = edges_.begin(); itr != edges_.end(); ++itr)416{417c1 = itr->first;418c2 = itr->second;419420if ((states_[c1] & INTERS) && (states_[c1] & (~INTERS)) != states_[c2])421{422hasConflict = true;423break;424}425}426427if (hasConflict)428{429int l1 = c1+1, l2 = c2+1;430431if (hasOnlyOneNeighbor(c1))432{433// if the first components has only one adjacent component434435for (int y = tls_[c1].y; y < brs_[c1].y; ++y)436for (int x = tls_[c1].x; x < brs_[c1].x; ++x)437if (labels_(y, x) == l1)438labels_(y, x) = l2;439440states_[c1] = states_[c2] == FIRST ? SECOND : FIRST;441}442else443{444// if the first component has more than one adjacent component445446Point p1, p2;447if (getSeamTips(c1, c2, p1, p2))448{449std::vector<Point> seam;450bool isHorizontalSeam;451452if (estimateSeam(image1, image2, tl1, tl2, c1, p1, p2, seam, isHorizontalSeam))453updateLabelsUsingSeam(c1, c2, seam, isHorizontalSeam);454}455456states_[c1] = states_[c2] == FIRST ? INTERS_SECOND : INTERS_FIRST;457}458459const int c[] = {c1, c2};460const int l[] = {l1, l2};461462for (int i = 0; i < 2; ++i)463{464// update information about the (i+1)-th component465466int x0 = tls_[c[i]].x, x1 = brs_[c[i]].x;467int y0 = tls_[c[i]].y, y1 = brs_[c[i]].y;468469tls_[c[i]] = Point(std::numeric_limits<int>::max(), std::numeric_limits<int>::max());470brs_[c[i]] = Point(std::numeric_limits<int>::min(), std::numeric_limits<int>::min());471contours_[c[i]].clear();472473for (int y = y0; y < y1; ++y)474{475for (int x = x0; x < x1; ++x)476{477if (labels_(y, x) == l[i])478{479tls_[c[i]].x = std::min(tls_[c[i]].x, x);480tls_[c[i]].y = std::min(tls_[c[i]].y, y);481brs_[c[i]].x = std::max(brs_[c[i]].x, x+1);482brs_[c[i]].y = std::max(brs_[c[i]].y, y+1);483484if ((x == 0 || labels_(y, x-1) != l[i]) || (x == unionSize_.width-1 || labels_(y, x+1) != l[i]) ||485(y == 0 || labels_(y-1, x) != l[i]) || (y == unionSize_.height-1 || labels_(y+1, x) != l[i]))486{487contours_[c[i]].push_back(Point(x, y));488}489}490}491}492}493494// remove edges495496edges_.erase(std::make_pair(c1, c2));497edges_.erase(std::make_pair(c2, c1));498}499}500501// update masks502503int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;504int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;505506for (int y = 0; y < mask2.rows; ++y)507{508for (int x = 0; x < mask2.cols; ++x)509{510int l = labels_(y - dy2, x - dx2);511if (l > 0 && (states_[l-1] & FIRST) && mask1.at<uchar>(y - dy2 + dy1, x - dx2 + dx1))512mask2.at<uchar>(y, x) = 0;513}514}515516for (int y = 0; y < mask1.rows; ++y)517{518for (int x = 0; x < mask1.cols; ++x)519{520int l = labels_(y - dy1, x - dx1);521if (l > 0 && (states_[l-1] & SECOND) && mask2.at<uchar>(y - dy1 + dy2, x - dx1 + dx2))522mask1.at<uchar>(y, x) = 0;523}524}525}526527528void DpSeamFinder::computeGradients(const Mat &image1, const Mat &image2)529{530CV_Assert(image1.channels() == 3 || image1.channels() == 4);531CV_Assert(image2.channels() == 3 || image2.channels() == 4);532CV_Assert(costFunction() == COLOR_GRAD);533534Mat gray;535536if (image1.channels() == 3)537cvtColor(image1, gray, COLOR_BGR2GRAY);538else if (image1.channels() == 4)539cvtColor(image1, gray, COLOR_BGRA2GRAY);540541Sobel(gray, gradx1_, CV_32F, 1, 0);542Sobel(gray, grady1_, CV_32F, 0, 1);543544if (image2.channels() == 3)545cvtColor(image2, gray, COLOR_BGR2GRAY);546else if (image2.channels() == 4)547cvtColor(image2, gray, COLOR_BGRA2GRAY);548549Sobel(gray, gradx2_, CV_32F, 1, 0);550Sobel(gray, grady2_, CV_32F, 0, 1);551}552553554bool DpSeamFinder::hasOnlyOneNeighbor(int comp)555{556std::set<std::pair<int, int> >::iterator begin, end;557begin = lower_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::min()));558end = upper_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::max()));559return ++begin == end;560}561562563bool DpSeamFinder::closeToContour(int y, int x, const Mat_<uchar> &contourMask)564{565const int rad = 2;566567for (int dy = -rad; dy <= rad; ++dy)568{569if (y + dy >= 0 && y + dy < unionSize_.height)570{571for (int dx = -rad; dx <= rad; ++dx)572{573if (x + dx >= 0 && x + dx < unionSize_.width &&574contourMask(y + dy, x + dx))575{576return true;577}578}579}580}581582return false;583}584585586bool DpSeamFinder::getSeamTips(int comp1, int comp2, Point &p1, Point &p2)587{588CV_Assert(states_[comp1] & INTERS);589590// find special points591592std::vector<Point> specialPoints;593int l2 = comp2+1;594595for (size_t i = 0; i < contours_[comp1].size(); ++i)596{597int x = contours_[comp1][i].x;598int y = contours_[comp1][i].y;599600if (closeToContour(y, x, contour1mask_) &&601closeToContour(y, x, contour2mask_) &&602((x > 0 && labels_(y, x-1) == l2) ||603(y > 0 && labels_(y-1, x) == l2) ||604(x < unionSize_.width-1 && labels_(y, x+1) == l2) ||605(y < unionSize_.height-1 && labels_(y+1, x) == l2)))606{607specialPoints.push_back(Point(x, y));608}609}610611if (specialPoints.size() < 2)612return false;613614// find clusters615616std::vector<int> labels;617cv::partition(specialPoints, labels, ClosePoints(10));618619int nlabels = *std::max_element(labels.begin(), labels.end()) + 1;620if (nlabels < 2)621return false;622623std::vector<Point> sum(nlabels);624std::vector<std::vector<Point> > points(nlabels);625626for (size_t i = 0; i < specialPoints.size(); ++i)627{628sum[labels[i]] += specialPoints[i];629points[labels[i]].push_back(specialPoints[i]);630}631632// select two most distant clusters633634int idx[2] = {-1,-1};635double maxDist = -std::numeric_limits<double>::max();636637for (int i = 0; i < nlabels-1; ++i)638{639for (int j = i+1; j < nlabels; ++j)640{641double size1 = static_cast<double>(points[i].size()), size2 = static_cast<double>(points[j].size());642double cx1 = cvRound(sum[i].x / size1), cy1 = cvRound(sum[i].y / size1);643double cx2 = cvRound(sum[j].x / size2), cy2 = cvRound(sum[j].y / size2);644645double dist = (cx1 - cx2) * (cx1 - cx2) + (cy1 - cy2) * (cy1 - cy2);646if (dist > maxDist)647{648maxDist = dist;649idx[0] = i;650idx[1] = j;651}652}653}654655// select two points closest to the clusters' centers656657Point p[2];658659for (int i = 0; i < 2; ++i)660{661double size = static_cast<double>(points[idx[i]].size());662double cx = cvRound(sum[idx[i]].x / size);663double cy = cvRound(sum[idx[i]].y / size);664665size_t closest = points[idx[i]].size();666double minDist = std::numeric_limits<double>::max();667668for (size_t j = 0; j < points[idx[i]].size(); ++j)669{670double dist = (points[idx[i]][j].x - cx) * (points[idx[i]][j].x - cx) +671(points[idx[i]][j].y - cy) * (points[idx[i]][j].y - cy);672if (dist < minDist)673{674minDist = dist;675closest = j;676}677}678679p[i] = points[idx[i]][closest];680}681682p1 = p[0];683p2 = p[1];684return true;685}686687688namespace689{690691template <typename T>692float diffL2Square3(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2)693{694const T *r1 = image1.ptr<T>(y1);695const T *r2 = image2.ptr<T>(y2);696return static_cast<float>(sqr(r1[3*x1] - r2[3*x2]) + sqr(r1[3*x1+1] - r2[3*x2+1]) +697sqr(r1[3*x1+2] - r2[3*x2+2]));698}699700701template <typename T>702float diffL2Square4(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2)703{704const T *r1 = image1.ptr<T>(y1);705const T *r2 = image2.ptr<T>(y2);706return static_cast<float>(sqr(r1[4*x1] - r2[4*x2]) + sqr(r1[4*x1+1] - r2[4*x2+1]) +707sqr(r1[4*x1+2] - r2[4*x2+2]));708}709710} // namespace711712713void DpSeamFinder::computeCosts(714const Mat &image1, const Mat &image2, Point tl1, Point tl2,715int comp, Mat_<float> &costV, Mat_<float> &costH)716{717CV_Assert(states_[comp] & INTERS);718719// compute costs720721float (*diff)(const Mat&, int, int, const Mat&, int, int) = 0;722if (image1.type() == CV_32FC3 && image2.type() == CV_32FC3)723diff = diffL2Square3<float>;724else if (image1.type() == CV_8UC3 && image2.type() == CV_8UC3)725diff = diffL2Square3<uchar>;726else if (image1.type() == CV_32FC4 && image2.type() == CV_32FC4)727diff = diffL2Square4<float>;728else if (image1.type() == CV_8UC4 && image2.type() == CV_8UC4)729diff = diffL2Square4<uchar>;730else731CV_Error(Error::StsBadArg, "both images must have CV_32FC3(4) or CV_8UC3(4) type");732733int l = comp+1;734Rect roi(tls_[comp], brs_[comp]);735736int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;737int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;738739const float badRegionCost = normL2(Point3f(255.f, 255.f, 255.f),740Point3f(0.f, 0.f, 0.f));741742costV.create(roi.height, roi.width+1);743744for (int y = roi.y; y < roi.br().y; ++y)745{746for (int x = roi.x; x < roi.br().x+1; ++x)747{748if (labels_(y, x) == l && x > 0 && labels_(y, x-1) == l)749{750float costColor = (diff(image1, y + dy1, x + dx1 - 1, image2, y + dy2, x + dx2) +751diff(image1, y + dy1, x + dx1, image2, y + dy2, x + dx2 - 1)) / 2;752if (costFunc_ == COLOR)753costV(y - roi.y, x - roi.x) = costColor;754else if (costFunc_ == COLOR_GRAD)755{756float costGrad = std::abs(gradx1_(y + dy1, x + dx1)) + std::abs(gradx1_(y + dy1, x + dx1 - 1)) +757std::abs(gradx2_(y + dy2, x + dx2)) + std::abs(gradx2_(y + dy2, x + dx2 - 1)) + 1.f;758costV(y - roi.y, x - roi.x) = costColor / costGrad;759}760}761else762costV(y - roi.y, x - roi.x) = badRegionCost;763}764}765766costH.create(roi.height+1, roi.width);767768for (int y = roi.y; y < roi.br().y+1; ++y)769{770for (int x = roi.x; x < roi.br().x; ++x)771{772if (labels_(y, x) == l && y > 0 && labels_(y-1, x) == l)773{774float costColor = (diff(image1, y + dy1 - 1, x + dx1, image2, y + dy2, x + dx2) +775diff(image1, y + dy1, x + dx1, image2, y + dy2 - 1, x + dx2)) / 2;776if (costFunc_ == COLOR)777costH(y - roi.y, x - roi.x) = costColor;778else if (costFunc_ == COLOR_GRAD)779{780float costGrad = std::abs(grady1_(y + dy1, x + dx1)) + std::abs(grady1_(y + dy1 - 1, x + dx1)) +781std::abs(grady2_(y + dy2, x + dx2)) + std::abs(grady2_(y + dy2 - 1, x + dx2)) + 1.f;782costH(y - roi.y, x - roi.x) = costColor / costGrad;783}784}785else786costH(y - roi.y, x - roi.x) = badRegionCost;787}788}789}790791792bool DpSeamFinder::estimateSeam(793const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp,794Point p1, Point p2, std::vector<Point> &seam, bool &isHorizontal)795{796CV_Assert(states_[comp] & INTERS);797798Mat_<float> costV, costH;799computeCosts(image1, image2, tl1, tl2, comp, costV, costH);800801Rect roi(tls_[comp], brs_[comp]);802Point src = p1 - roi.tl();803Point dst = p2 - roi.tl();804int l = comp+1;805806// estimate seam direction807808bool swapped = false;809isHorizontal = std::abs(dst.x - src.x) > std::abs(dst.y - src.y);810811if (isHorizontal)812{813if (src.x > dst.x)814{815std::swap(src, dst);816swapped = true;817}818}819else if (src.y > dst.y)820{821swapped = true;822std::swap(src, dst);823}824825// find optimal control826827Mat_<uchar> control = Mat::zeros(roi.size(), CV_8U);828Mat_<uchar> reachable = Mat::zeros(roi.size(), CV_8U);829Mat_<float> cost = Mat::zeros(roi.size(), CV_32F);830831reachable(src) = 1;832cost(src) = 0.f;833834int nsteps;835std::pair<float, int> steps[3];836837if (isHorizontal)838{839for (int x = src.x+1; x <= dst.x; ++x)840{841for (int y = 0; y < roi.height; ++y)842{843// seam follows along upper side of pixels844845nsteps = 0;846847if (labels_(y + roi.y, x + roi.x) == l)848{849if (reachable(y, x-1))850steps[nsteps++] = std::make_pair(cost(y, x-1) + costH(y, x-1), 1);851if (y > 0 && reachable(y-1, x-1))852steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costH(y-1, x-1) + costV(y-1, x), 2);853if (y < roi.height-1 && reachable(y+1, x-1))854steps[nsteps++] = std::make_pair(cost(y+1, x-1) + costH(y+1, x-1) + costV(y, x), 3);855}856857if (nsteps)858{859std::pair<float, int> opt = *min_element(steps, steps + nsteps);860cost(y, x) = opt.first;861control(y, x) = (uchar)opt.second;862reachable(y, x) = 255;863}864}865}866}867else868{869for (int y = src.y+1; y <= dst.y; ++y)870{871for (int x = 0; x < roi.width; ++x)872{873// seam follows along left side of pixels874875nsteps = 0;876877if (labels_(y + roi.y, x + roi.x) == l)878{879if (reachable(y-1, x))880steps[nsteps++] = std::make_pair(cost(y-1, x) + costV(y-1, x), 1);881if (x > 0 && reachable(y-1, x-1))882steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costV(y-1, x-1) + costH(y, x-1), 2);883if (x < roi.width-1 && reachable(y-1, x+1))884steps[nsteps++] = std::make_pair(cost(y-1, x+1) + costV(y-1, x+1) + costH(y, x), 3);885}886887if (nsteps)888{889std::pair<float, int> opt = *min_element(steps, steps + nsteps);890cost(y, x) = opt.first;891control(y, x) = (uchar)opt.second;892reachable(y, x) = 255;893}894}895}896}897898if (!reachable(dst))899return false;900901// restore seam902903Point p = dst;904seam.clear();905seam.push_back(p + roi.tl());906907if (isHorizontal)908{909for (; p.x != src.x; seam.push_back(p + roi.tl()))910{911if (control(p) == 2) p.y--;912else if (control(p) == 3) p.y++;913p.x--;914}915}916else917{918for (; p.y != src.y; seam.push_back(p + roi.tl()))919{920if (control(p) == 2) p.x--;921else if (control(p) == 3) p.x++;922p.y--;923}924}925926if (!swapped)927std::reverse(seam.begin(), seam.end());928929CV_Assert(seam.front() == p1);930CV_Assert(seam.back() == p2);931return true;932}933934935void DpSeamFinder::updateLabelsUsingSeam(936int comp1, int comp2, const std::vector<Point> &seam, bool isHorizontalSeam)937{938Mat_<int> mask = Mat::zeros(brs_[comp1].y - tls_[comp1].y,939brs_[comp1].x - tls_[comp1].x, CV_32S);940941for (size_t i = 0; i < contours_[comp1].size(); ++i)942mask(contours_[comp1][i] - tls_[comp1]) = 255;943944for (size_t i = 0; i < seam.size(); ++i)945mask(seam[i] - tls_[comp1]) = 255;946947// find connected components after seam carving948949int l1 = comp1+1, l2 = comp2+1;950951int ncomps = 0;952953for (int y = 0; y < mask.rows; ++y)954for (int x = 0; x < mask.cols; ++x)955if (!mask(y, x) && labels_(y + tls_[comp1].y, x + tls_[comp1].x) == l1)956floodFill(mask, Point(x, y), ++ncomps);957958for (size_t i = 0; i < contours_[comp1].size(); ++i)959{960int x = contours_[comp1][i].x - tls_[comp1].x;961int y = contours_[comp1][i].y - tls_[comp1].y;962963bool ok = false;964static const int dx[] = {-1, +1, 0, 0, -1, +1, -1, +1};965static const int dy[] = {0, 0, -1, +1, -1, -1, +1, +1};966967for (int j = 0; j < 8; ++j)968{969int c = x + dx[j];970int r = y + dy[j];971972if (c >= 0 && c < mask.cols && r >= 0 && r < mask.rows &&973mask(r, c) && mask(r, c) != 255)974{975ok = true;976mask(y, x) = mask(r, c);977}978}979980if (!ok)981mask(y, x) = 0;982}983984if (isHorizontalSeam)985{986for (size_t i = 0; i < seam.size(); ++i)987{988int x = seam[i].x - tls_[comp1].x;989int y = seam[i].y - tls_[comp1].y;990991if (y < mask.rows-1 && mask(y+1, x) && mask(y+1, x) != 255)992mask(y, x) = mask(y+1, x);993else994mask(y, x) = 0;995}996}997else998{999for (size_t i = 0; i < seam.size(); ++i)1000{1001int x = seam[i].x - tls_[comp1].x;1002int y = seam[i].y - tls_[comp1].y;10031004if (x < mask.cols-1 && mask(y, x+1) && mask(y, x+1) != 255)1005mask(y, x) = mask(y, x+1);1006else1007mask(y, x) = 0;1008}1009}10101011// find new components connected with the second component and1012// with other components except the ones we are working with10131014std::map<int, int> connect2;1015std::map<int, int> connectOther;10161017for (int i = 1; i <= ncomps; ++i)1018{1019connect2.insert(std::make_pair(i, 0));1020connectOther.insert(std::make_pair(i, 0));1021}10221023for (size_t i = 0; i < contours_[comp1].size(); ++i)1024{1025int x = contours_[comp1][i].x;1026int y = contours_[comp1][i].y;10271028if ((x > 0 && labels_(y, x-1) == l2) ||1029(y > 0 && labels_(y-1, x) == l2) ||1030(x < unionSize_.width-1 && labels_(y, x+1) == l2) ||1031(y < unionSize_.height-1 && labels_(y+1, x) == l2))1032{1033connect2[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;1034}10351036if ((x > 0 && labels_(y, x-1) != l1 && labels_(y, x-1) != l2) ||1037(y > 0 && labels_(y-1, x) != l1 && labels_(y-1, x) != l2) ||1038(x < unionSize_.width-1 && labels_(y, x+1) != l1 && labels_(y, x+1) != l2) ||1039(y < unionSize_.height-1 && labels_(y+1, x) != l1 && labels_(y+1, x) != l2))1040{1041connectOther[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;1042}1043}10441045std::vector<int> isAdjComp(ncomps + 1, 0);10461047for (std::map<int, int>::iterator itr = connect2.begin(); itr != connect2.end(); ++itr)1048{1049double len = static_cast<double>(contours_[comp1].size());1050int res = 0;1051if (itr->second / len > 0.05)1052{1053std::map<int, int>::const_iterator sub = connectOther.find(itr->first);1054if (sub != connectOther.end() && (sub->second / len < 0.1))1055{1056res = 1;1057}1058}1059isAdjComp[itr->first] = res;1060}10611062// update labels10631064for (int y = 0; y < mask.rows; ++y)1065for (int x = 0; x < mask.cols; ++x)1066if (mask(y, x) && isAdjComp[mask(y, x)])1067labels_(y + tls_[comp1].y, x + tls_[comp1].x) = l2;1068}106910701071class GraphCutSeamFinder::Impl CV_FINAL : public PairwiseSeamFinder1072{1073public:1074Impl(int cost_type, float terminal_cost, float bad_region_penalty)1075: cost_type_(cost_type), terminal_cost_(terminal_cost), bad_region_penalty_(bad_region_penalty) {}10761077~Impl() {}10781079void find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) CV_OVERRIDE;1080void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE;10811082private:1083void setGraphWeightsColor(const Mat &img1, const Mat &img2,1084const Mat &mask1, const Mat &mask2, GCGraph<float> &graph);1085void setGraphWeightsColorGrad(const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,1086const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,1087GCGraph<float> &graph);10881089std::vector<Mat> dx_, dy_;1090int cost_type_;1091float terminal_cost_;1092float bad_region_penalty_;1093};109410951096void GraphCutSeamFinder::Impl::find(const std::vector<UMat> &src, const std::vector<Point> &corners,1097std::vector<UMat> &masks)1098{1099// Compute gradients1100dx_.resize(src.size());1101dy_.resize(src.size());1102Mat dx, dy;1103for (size_t i = 0; i < src.size(); ++i)1104{1105CV_Assert(src[i].channels() == 3);1106Sobel(src[i], dx, CV_32F, 1, 0);1107Sobel(src[i], dy, CV_32F, 0, 1);1108dx_[i].create(src[i].size(), CV_32F);1109dy_[i].create(src[i].size(), CV_32F);1110for (int y = 0; y < src[i].rows; ++y)1111{1112const Point3f* dx_row = dx.ptr<Point3f>(y);1113const Point3f* dy_row = dy.ptr<Point3f>(y);1114float* dx_row_ = dx_[i].ptr<float>(y);1115float* dy_row_ = dy_[i].ptr<float>(y);1116for (int x = 0; x < src[i].cols; ++x)1117{1118dx_row_[x] = normL2(dx_row[x]);1119dy_row_[x] = normL2(dy_row[x]);1120}1121}1122}1123PairwiseSeamFinder::find(src, corners, masks);1124}112511261127void GraphCutSeamFinder::Impl::setGraphWeightsColor(const Mat &img1, const Mat &img2,1128const Mat &mask1, const Mat &mask2, GCGraph<float> &graph)1129{1130const Size img_size = img1.size();11311132// Set terminal weights1133for (int y = 0; y < img_size.height; ++y)1134{1135for (int x = 0; x < img_size.width; ++x)1136{1137int v = graph.addVtx();1138graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,1139mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);1140}1141}11421143// Set regular edge weights1144const float weight_eps = 1.f;1145for (int y = 0; y < img_size.height; ++y)1146{1147for (int x = 0; x < img_size.width; ++x)1148{1149int v = y * img_size.width + x;1150if (x < img_size.width - 1)1151{1152float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1153normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) +1154weight_eps;1155if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||1156!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))1157weight += bad_region_penalty_;1158graph.addEdges(v, v + 1, weight, weight);1159}1160if (y < img_size.height - 1)1161{1162float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1163normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) +1164weight_eps;1165if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||1166!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))1167weight += bad_region_penalty_;1168graph.addEdges(v, v + img_size.width, weight, weight);1169}1170}1171}1172}117311741175void GraphCutSeamFinder::Impl::setGraphWeightsColorGrad(1176const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,1177const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,1178GCGraph<float> &graph)1179{1180const Size img_size = img1.size();11811182// Set terminal weights1183for (int y = 0; y < img_size.height; ++y)1184{1185for (int x = 0; x < img_size.width; ++x)1186{1187int v = graph.addVtx();1188graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,1189mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);1190}1191}11921193// Set regular edge weights1194const float weight_eps = 1.f;1195for (int y = 0; y < img_size.height; ++y)1196{1197for (int x = 0; x < img_size.width; ++x)1198{1199int v = y * img_size.width + x;1200if (x < img_size.width - 1)1201{1202float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) +1203dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps;1204float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1205normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad +1206weight_eps;1207if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||1208!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))1209weight += bad_region_penalty_;1210graph.addEdges(v, v + 1, weight, weight);1211}1212if (y < img_size.height - 1)1213{1214float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) +1215dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps;1216float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1217normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad +1218weight_eps;1219if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||1220!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))1221weight += bad_region_penalty_;1222graph.addEdges(v, v + img_size.width, weight, weight);1223}1224}1225}1226}122712281229void GraphCutSeamFinder::Impl::findInPair(size_t first, size_t second, Rect roi)1230{1231Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ);1232Mat dx1 = dx_[first], dx2 = dx_[second];1233Mat dy1 = dy_[first], dy2 = dy_[second];1234Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW);1235Point tl1 = corners_[first], tl2 = corners_[second];12361237const int gap = 10;1238Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);1239Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);1240Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);1241Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);1242Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1243Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1244Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1245Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);12461247// Cut subimages and submasks with some gap1248for (int y = -gap; y < roi.height + gap; ++y)1249{1250for (int x = -gap; x < roi.width + gap; ++x)1251{1252int y1 = roi.y - tl1.y + y;1253int x1 = roi.x - tl1.x + x;1254if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols)1255{1256subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1);1257submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);1258subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1);1259subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1);1260}1261else1262{1263subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);1264submask1.at<uchar>(y + gap, x + gap) = 0;1265subdx1.at<float>(y + gap, x + gap) = 0.f;1266subdy1.at<float>(y + gap, x + gap) = 0.f;1267}12681269int y2 = roi.y - tl2.y + y;1270int x2 = roi.x - tl2.x + x;1271if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols)1272{1273subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2);1274submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);1275subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2);1276subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2);1277}1278else1279{1280subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);1281submask2.at<uchar>(y + gap, x + gap) = 0;1282subdx2.at<float>(y + gap, x + gap) = 0.f;1283subdy2.at<float>(y + gap, x + gap) = 0.f;1284}1285}1286}12871288const int vertex_count = (roi.height + 2 * gap) * (roi.width + 2 * gap);1289const int edge_count = (roi.height - 1 + 2 * gap) * (roi.width + 2 * gap) +1290(roi.width - 1 + 2 * gap) * (roi.height + 2 * gap);1291GCGraph<float> graph(vertex_count, edge_count);12921293switch (cost_type_)1294{1295case GraphCutSeamFinder::COST_COLOR:1296setGraphWeightsColor(subimg1, subimg2, submask1, submask2, graph);1297break;1298case GraphCutSeamFinder::COST_COLOR_GRAD:1299setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2,1300submask1, submask2, graph);1301break;1302default:1303CV_Error(Error::StsBadArg, "unsupported pixel similarity measure");1304}13051306graph.maxFlow();13071308for (int y = 0; y < roi.height; ++y)1309{1310for (int x = 0; x < roi.width; ++x)1311{1312if (graph.inSourceSegment((y + gap) * (roi.width + 2 * gap) + x + gap))1313{1314if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x))1315mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;1316}1317else1318{1319if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x))1320mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;1321}1322}1323}1324}132513261327GraphCutSeamFinder::GraphCutSeamFinder(int cost_type, float terminal_cost, float bad_region_penalty)1328: impl_(new Impl(cost_type, terminal_cost, bad_region_penalty)) {}13291330GraphCutSeamFinder::~GraphCutSeamFinder() {}133113321333void GraphCutSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,1334std::vector<UMat> &masks)1335{1336impl_->find(src, corners, masks);1337}133813391340#ifdef HAVE_OPENCV_CUDALEGACY1341void GraphCutSeamFinderGpu::find(const std::vector<UMat> &src, const std::vector<Point> &corners,1342std::vector<UMat> &masks)1343{1344// Compute gradients1345dx_.resize(src.size());1346dy_.resize(src.size());1347Mat dx, dy;1348for (size_t i = 0; i < src.size(); ++i)1349{1350CV_Assert(src[i].channels() == 3);1351Sobel(src[i], dx, CV_32F, 1, 0);1352Sobel(src[i], dy, CV_32F, 0, 1);1353dx_[i].create(src[i].size(), CV_32F);1354dy_[i].create(src[i].size(), CV_32F);1355for (int y = 0; y < src[i].rows; ++y)1356{1357const Point3f* dx_row = dx.ptr<Point3f>(y);1358const Point3f* dy_row = dy.ptr<Point3f>(y);1359float* dx_row_ = dx_[i].ptr<float>(y);1360float* dy_row_ = dy_[i].ptr<float>(y);1361for (int x = 0; x < src[i].cols; ++x)1362{1363dx_row_[x] = normL2(dx_row[x]);1364dy_row_[x] = normL2(dy_row[x]);1365}1366}1367}1368PairwiseSeamFinder::find(src, corners, masks);1369}137013711372void GraphCutSeamFinderGpu::findInPair(size_t first, size_t second, Rect roi)1373{1374Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ);1375Mat dx1 = dx_[first], dx2 = dx_[second];1376Mat dy1 = dy_[first], dy2 = dy_[second];1377Mat mask1 = masks_[first].getMat(ACCESS_READ), mask2 = masks_[second].getMat(ACCESS_READ);1378Point tl1 = corners_[first], tl2 = corners_[second];13791380const int gap = 10;1381Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);1382Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);1383Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);1384Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);1385Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1386Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1387Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);1388Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);13891390// Cut subimages and submasks with some gap1391for (int y = -gap; y < roi.height + gap; ++y)1392{1393for (int x = -gap; x < roi.width + gap; ++x)1394{1395int y1 = roi.y - tl1.y + y;1396int x1 = roi.x - tl1.x + x;1397if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols)1398{1399subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1);1400submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);1401subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1);1402subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1);1403}1404else1405{1406subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);1407submask1.at<uchar>(y + gap, x + gap) = 0;1408subdx1.at<float>(y + gap, x + gap) = 0.f;1409subdy1.at<float>(y + gap, x + gap) = 0.f;1410}14111412int y2 = roi.y - tl2.y + y;1413int x2 = roi.x - tl2.x + x;1414if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols)1415{1416subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2);1417submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);1418subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2);1419subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2);1420}1421else1422{1423subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);1424submask2.at<uchar>(y + gap, x + gap) = 0;1425subdx2.at<float>(y + gap, x + gap) = 0.f;1426subdy2.at<float>(y + gap, x + gap) = 0.f;1427}1428}1429}14301431Mat terminals, leftT, rightT, top, bottom;14321433switch (cost_type_)1434{1435case GraphCutSeamFinder::COST_COLOR:1436setGraphWeightsColor(subimg1, subimg2, submask1, submask2,1437terminals, leftT, rightT, top, bottom);1438break;1439case GraphCutSeamFinder::COST_COLOR_GRAD:1440setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2,1441submask1, submask2, terminals, leftT, rightT, top, bottom);1442break;1443default:1444CV_Error(Error::StsBadArg, "unsupported pixel similarity measure");1445}14461447cuda::GpuMat terminals_d(terminals);1448cuda::GpuMat leftT_d(leftT);1449cuda::GpuMat rightT_d(rightT);1450cuda::GpuMat top_d(top);1451cuda::GpuMat bottom_d(bottom);1452cuda::GpuMat labels_d, buf_d;14531454cuda::graphcut(terminals_d, leftT_d, rightT_d, top_d, bottom_d, labels_d, buf_d);14551456Mat_<uchar> labels = (Mat)labels_d;1457for (int y = 0; y < roi.height; ++y)1458{1459for (int x = 0; x < roi.width; ++x)1460{1461if (labels(y + gap, x + gap))1462{1463if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x))1464mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;1465}1466else1467{1468if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x))1469mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;1470}1471}1472}1473}147414751476void GraphCutSeamFinderGpu::setGraphWeightsColor(const Mat &img1, const Mat &img2, const Mat &mask1, const Mat &mask2,1477Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom)1478{1479const Size img_size = img1.size();14801481terminals.create(img_size, CV_32S);1482leftT.create(Size(img_size.height, img_size.width), CV_32S);1483rightT.create(Size(img_size.height, img_size.width), CV_32S);1484top.create(img_size, CV_32S);1485bottom.create(img_size, CV_32S);14861487Mat_<int> terminals_(terminals);1488Mat_<int> leftT_(leftT);1489Mat_<int> rightT_(rightT);1490Mat_<int> top_(top);1491Mat_<int> bottom_(bottom);14921493// Set terminal weights1494for (int y = 0; y < img_size.height; ++y)1495{1496for (int x = 0; x < img_size.width; ++x)1497{1498float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f;1499float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f;1500terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f);1501}1502}15031504// Set regular edge weights1505const float weight_eps = 1.f;1506for (int y = 0; y < img_size.height; ++y)1507{1508for (int x = 0; x < img_size.width; ++x)1509{1510if (x > 0)1511{1512float weight = normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) +1513normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1514weight_eps;1515if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) ||1516!mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x))1517weight += bad_region_penalty_;1518leftT_(x, y) = saturate_cast<int>(weight * 255.f);1519}1520else1521leftT_(x, y) = 0;15221523if (x < img_size.width - 1)1524{1525float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1526normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) +1527weight_eps;1528if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||1529!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))1530weight += bad_region_penalty_;1531rightT_(x, y) = saturate_cast<int>(weight * 255.f);1532}1533else1534rightT_(x, y) = 0;15351536if (y > 0)1537{1538float weight = normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) +1539normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1540weight_eps;1541if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) ||1542!mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x))1543weight += bad_region_penalty_;1544top_(y, x) = saturate_cast<int>(weight * 255.f);1545}1546else1547top_(y, x) = 0;15481549if (y < img_size.height - 1)1550{1551float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1552normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) +1553weight_eps;1554if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||1555!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))1556weight += bad_region_penalty_;1557bottom_(y, x) = saturate_cast<int>(weight * 255.f);1558}1559else1560bottom_(y, x) = 0;1561}1562}1563}156415651566void GraphCutSeamFinderGpu::setGraphWeightsColorGrad(1567const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,1568const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,1569Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom)1570{1571const Size img_size = img1.size();15721573terminals.create(img_size, CV_32S);1574leftT.create(Size(img_size.height, img_size.width), CV_32S);1575rightT.create(Size(img_size.height, img_size.width), CV_32S);1576top.create(img_size, CV_32S);1577bottom.create(img_size, CV_32S);15781579Mat_<int> terminals_(terminals);1580Mat_<int> leftT_(leftT);1581Mat_<int> rightT_(rightT);1582Mat_<int> top_(top);1583Mat_<int> bottom_(bottom);15841585// Set terminal weights1586for (int y = 0; y < img_size.height; ++y)1587{1588for (int x = 0; x < img_size.width; ++x)1589{1590float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f;1591float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f;1592terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f);1593}1594}15951596// Set regular edge weights1597const float weight_eps = 1.f;1598for (int y = 0; y < img_size.height; ++y)1599{1600for (int x = 0; x < img_size.width; ++x)1601{1602if (x > 0)1603{1604float grad = dx1.at<float>(y, x - 1) + dx1.at<float>(y, x) +1605dx2.at<float>(y, x - 1) + dx2.at<float>(y, x) + weight_eps;1606float weight = (normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) +1607normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad +1608weight_eps;1609if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) ||1610!mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x))1611weight += bad_region_penalty_;1612leftT_(x, y) = saturate_cast<int>(weight * 255.f);1613}1614else1615leftT_(x, y) = 0;16161617if (x < img_size.width - 1)1618{1619float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) +1620dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps;1621float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1622normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad +1623weight_eps;1624if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||1625!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))1626weight += bad_region_penalty_;1627rightT_(x, y) = saturate_cast<int>(weight * 255.f);1628}1629else1630rightT_(x, y) = 0;16311632if (y > 0)1633{1634float grad = dy1.at<float>(y - 1, x) + dy1.at<float>(y, x) +1635dy2.at<float>(y - 1, x) + dy2.at<float>(y, x) + weight_eps;1636float weight = (normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) +1637normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad +1638weight_eps;1639if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) ||1640!mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x))1641weight += bad_region_penalty_;1642top_(y, x) = saturate_cast<int>(weight * 255.f);1643}1644else1645top_(y, x) = 0;16461647if (y < img_size.height - 1)1648{1649float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) +1650dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps;1651float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +1652normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad +1653weight_eps;1654if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||1655!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))1656weight += bad_region_penalty_;1657bottom_(y, x) = saturate_cast<int>(weight * 255.f);1658}1659else1660bottom_(y, x) = 0;1661}1662}1663}1664#endif16651666} // namespace detail1667} // namespace cv166816691670