Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/stitching/src/seam_finders.cpp
16337 views
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
8
//
9
//
10
// License Agreement
11
// For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Third party copyrights are property of their respective owners.
16
//
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
19
//
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
22
//
23
// * Redistribution's in binary form must reproduce the above copyright notice,
24
// this list of conditions and the following disclaimer in the documentation
25
// and/or other materials provided with the distribution.
26
//
27
// * The name of the copyright holders may not be used to endorse or promote products
28
// derived from this software without specific prior written permission.
29
//
30
// This software is provided by the copyright holders and contributors "as is" and
31
// any express or implied warranties, including, but not limited to, the implied
32
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
40
//
41
//M*/
42
43
#include "precomp.hpp"
44
#include "opencv2/imgproc/detail/gcgraph.hpp"
45
#include <map>
46
47
namespace cv {
48
namespace detail {
49
50
void PairwiseSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,
51
std::vector<UMat> &masks)
52
{
53
LOGLN("Finding seams...");
54
if (src.size() == 0)
55
return;
56
57
#if ENABLE_LOG
58
int64 t = getTickCount();
59
#endif
60
61
images_ = src;
62
sizes_.resize(src.size());
63
for (size_t i = 0; i < src.size(); ++i)
64
sizes_[i] = src[i].size();
65
corners_ = corners;
66
masks_ = masks;
67
run();
68
69
LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
70
}
71
72
73
void PairwiseSeamFinder::run()
74
{
75
for (size_t i = 0; i < sizes_.size() - 1; ++i)
76
{
77
for (size_t j = i + 1; j < sizes_.size(); ++j)
78
{
79
Rect roi;
80
if (overlapRoi(corners_[i], corners_[j], sizes_[i], sizes_[j], roi))
81
findInPair(i, j, roi);
82
}
83
}
84
}
85
86
void VoronoiSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,
87
std::vector<UMat> &masks)
88
{
89
PairwiseSeamFinder::find(src, corners, masks);
90
}
91
92
void VoronoiSeamFinder::find(const std::vector<Size> &sizes, const std::vector<Point> &corners,
93
std::vector<UMat> &masks)
94
{
95
LOGLN("Finding seams...");
96
if (sizes.size() == 0)
97
return;
98
99
#if ENABLE_LOG
100
int64 t = getTickCount();
101
#endif
102
103
sizes_ = sizes;
104
corners_ = corners;
105
masks_ = masks;
106
run();
107
108
LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
109
}
110
111
112
void VoronoiSeamFinder::findInPair(size_t first, size_t second, Rect roi)
113
{
114
const int gap = 10;
115
Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
116
Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
117
118
Size img1 = sizes_[first], img2 = sizes_[second];
119
Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW);
120
Point tl1 = corners_[first], tl2 = corners_[second];
121
122
// Cut submasks with some gap
123
for (int y = -gap; y < roi.height + gap; ++y)
124
{
125
for (int x = -gap; x < roi.width + gap; ++x)
126
{
127
int y1 = roi.y - tl1.y + y;
128
int x1 = roi.x - tl1.x + x;
129
if (y1 >= 0 && x1 >= 0 && y1 < img1.height && x1 < img1.width)
130
submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);
131
else
132
submask1.at<uchar>(y + gap, x + gap) = 0;
133
134
int y2 = roi.y - tl2.y + y;
135
int x2 = roi.x - tl2.x + x;
136
if (y2 >= 0 && x2 >= 0 && y2 < img2.height && x2 < img2.width)
137
submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);
138
else
139
submask2.at<uchar>(y + gap, x + gap) = 0;
140
}
141
}
142
143
Mat collision = (submask1 != 0) & (submask2 != 0);
144
Mat unique1 = submask1.clone(); unique1.setTo(0, collision);
145
Mat unique2 = submask2.clone(); unique2.setTo(0, collision);
146
147
Mat dist1, dist2;
148
distanceTransform(unique1 == 0, dist1, DIST_L1, 3);
149
distanceTransform(unique2 == 0, dist2, DIST_L1, 3);
150
151
Mat seam = dist1 < dist2;
152
153
for (int y = 0; y < roi.height; ++y)
154
{
155
for (int x = 0; x < roi.width; ++x)
156
{
157
if (seam.at<uchar>(y + gap, x + gap))
158
mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;
159
else
160
mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;
161
}
162
}
163
}
164
165
166
DpSeamFinder::DpSeamFinder(CostFunction costFunc) : costFunc_(costFunc), ncomps_(0) {}
167
168
169
void DpSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks)
170
{
171
LOGLN("Finding seams...");
172
#if ENABLE_LOG
173
int64 t = getTickCount();
174
#endif
175
176
if (src.size() == 0)
177
return;
178
179
std::vector<std::pair<size_t, size_t> > pairs;
180
181
for (size_t i = 0; i+1 < src.size(); ++i)
182
for (size_t j = i+1; j < src.size(); ++j)
183
pairs.push_back(std::make_pair(i, j));
184
185
{
186
std::vector<Mat> _src(src.size());
187
for (size_t i = 0; i < src.size(); ++i) _src[i] = src[i].getMat(ACCESS_READ);
188
sort(pairs.begin(), pairs.end(), ImagePairLess(_src, corners));
189
}
190
std::reverse(pairs.begin(), pairs.end());
191
192
for (size_t i = 0; i < pairs.size(); ++i)
193
{
194
size_t i0 = pairs[i].first, i1 = pairs[i].second;
195
Mat mask0 = masks[i0].getMat(ACCESS_RW), mask1 = masks[i1].getMat(ACCESS_RW);
196
process(src[i0].getMat(ACCESS_READ), src[i1].getMat(ACCESS_READ), corners[i0], corners[i1], mask0, mask1);
197
}
198
199
LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
200
}
201
202
203
void DpSeamFinder::process(
204
const Mat &image1, const Mat &image2, Point tl1, Point tl2,
205
Mat &mask1, Mat &mask2)
206
{
207
CV_INSTRUMENT_REGION();
208
209
CV_Assert(image1.size() == mask1.size());
210
CV_Assert(image2.size() == mask2.size());
211
212
Point intersectTl(std::max(tl1.x, tl2.x), std::max(tl1.y, tl2.y));
213
214
Point intersectBr(std::min(tl1.x + image1.cols, tl2.x + image2.cols),
215
std::min(tl1.y + image1.rows, tl2.y + image2.rows));
216
217
if (intersectTl.x >= intersectBr.x || intersectTl.y >= intersectBr.y)
218
return; // there are no conflicts
219
220
unionTl_ = Point(std::min(tl1.x, tl2.x), std::min(tl1.y, tl2.y));
221
222
unionBr_ = Point(std::max(tl1.x + image1.cols, tl2.x + image2.cols),
223
std::max(tl1.y + image1.rows, tl2.y + image2.rows));
224
225
unionSize_ = Size(unionBr_.x - unionTl_.x, unionBr_.y - unionTl_.y);
226
227
mask1_ = Mat::zeros(unionSize_, CV_8U);
228
mask2_ = Mat::zeros(unionSize_, CV_8U);
229
230
Mat tmp = mask1_(Rect(tl1.x - unionTl_.x, tl1.y - unionTl_.y, mask1.cols, mask1.rows));
231
mask1.copyTo(tmp);
232
233
tmp = mask2_(Rect(tl2.x - unionTl_.x, tl2.y - unionTl_.y, mask2.cols, mask2.rows));
234
mask2.copyTo(tmp);
235
236
// find both images contour masks
237
238
contour1mask_ = Mat::zeros(unionSize_, CV_8U);
239
contour2mask_ = Mat::zeros(unionSize_, CV_8U);
240
241
for (int y = 0; y < unionSize_.height; ++y)
242
{
243
for (int x = 0; x < unionSize_.width; ++x)
244
{
245
if (mask1_(y, x) &&
246
((x == 0 || !mask1_(y, x-1)) || (x == unionSize_.width-1 || !mask1_(y, x+1)) ||
247
(y == 0 || !mask1_(y-1, x)) || (y == unionSize_.height-1 || !mask1_(y+1, x))))
248
{
249
contour1mask_(y, x) = 255;
250
}
251
252
if (mask2_(y, x) &&
253
((x == 0 || !mask2_(y, x-1)) || (x == unionSize_.width-1 || !mask2_(y, x+1)) ||
254
(y == 0 || !mask2_(y-1, x)) || (y == unionSize_.height-1 || !mask2_(y+1, x))))
255
{
256
contour2mask_(y, x) = 255;
257
}
258
}
259
}
260
261
findComponents();
262
263
findEdges();
264
265
resolveConflicts(image1, image2, tl1, tl2, mask1, mask2);
266
}
267
268
269
void DpSeamFinder::findComponents()
270
{
271
// label all connected components and get information about them
272
273
ncomps_ = 0;
274
labels_.create(unionSize_);
275
states_.clear();
276
tls_.clear();
277
brs_.clear();
278
contours_.clear();
279
280
for (int y = 0; y < unionSize_.height; ++y)
281
{
282
for (int x = 0; x < unionSize_.width; ++x)
283
{
284
if (mask1_(y, x) && mask2_(y, x))
285
labels_(y, x) = std::numeric_limits<int>::max();
286
else if (mask1_(y, x))
287
labels_(y, x) = std::numeric_limits<int>::max()-1;
288
else if (mask2_(y, x))
289
labels_(y, x) = std::numeric_limits<int>::max()-2;
290
else
291
labels_(y, x) = 0;
292
}
293
}
294
295
for (int y = 0; y < unionSize_.height; ++y)
296
{
297
for (int x = 0; x < unionSize_.width; ++x)
298
{
299
if (labels_(y, x) >= std::numeric_limits<int>::max()-2)
300
{
301
if (labels_(y, x) == std::numeric_limits<int>::max())
302
states_.push_back(INTERS);
303
else if (labels_(y, x) == std::numeric_limits<int>::max()-1)
304
states_.push_back(FIRST);
305
else if (labels_(y, x) == std::numeric_limits<int>::max()-2)
306
states_.push_back(SECOND);
307
308
floodFill(labels_, Point(x, y), ++ncomps_);
309
tls_.push_back(Point(x, y));
310
brs_.push_back(Point(x+1, y+1));
311
contours_.push_back(std::vector<Point>());
312
}
313
314
if (labels_(y, x))
315
{
316
int l = labels_(y, x);
317
int ci = l-1;
318
319
tls_[ci].x = std::min(tls_[ci].x, x);
320
tls_[ci].y = std::min(tls_[ci].y, y);
321
brs_[ci].x = std::max(brs_[ci].x, x+1);
322
brs_[ci].y = std::max(brs_[ci].y, y+1);
323
324
if ((x == 0 || labels_(y, x-1) != l) || (x == unionSize_.width-1 || labels_(y, x+1) != l) ||
325
(y == 0 || labels_(y-1, x) != l) || (y == unionSize_.height-1 || labels_(y+1, x) != l))
326
{
327
contours_[ci].push_back(Point(x, y));
328
}
329
}
330
}
331
}
332
}
333
334
335
void DpSeamFinder::findEdges()
336
{
337
// find edges between components
338
339
std::map<std::pair<int, int>, int> wedges; // weighted edges
340
341
for (int ci = 0; ci < ncomps_-1; ++ci)
342
{
343
for (int cj = ci+1; cj < ncomps_; ++cj)
344
{
345
wedges[std::make_pair(ci, cj)] = 0;
346
wedges[std::make_pair(cj, ci)] = 0;
347
}
348
}
349
350
for (int ci = 0; ci < ncomps_; ++ci)
351
{
352
for (size_t i = 0; i < contours_[ci].size(); ++i)
353
{
354
int x = contours_[ci][i].x;
355
int y = contours_[ci][i].y;
356
int l = ci + 1;
357
358
if (x > 0 && labels_(y, x-1) && labels_(y, x-1) != l)
359
{
360
wedges[std::make_pair(ci, labels_(y, x-1)-1)]++;
361
wedges[std::make_pair(labels_(y, x-1)-1, ci)]++;
362
}
363
364
if (y > 0 && labels_(y-1, x) && labels_(y-1, x) != l)
365
{
366
wedges[std::make_pair(ci, labels_(y-1, x)-1)]++;
367
wedges[std::make_pair(labels_(y-1, x)-1, ci)]++;
368
}
369
370
if (x < unionSize_.width-1 && labels_(y, x+1) && labels_(y, x+1) != l)
371
{
372
wedges[std::make_pair(ci, labels_(y, x+1)-1)]++;
373
wedges[std::make_pair(labels_(y, x+1)-1, ci)]++;
374
}
375
376
if (y < unionSize_.height-1 && labels_(y+1, x) && labels_(y+1, x) != l)
377
{
378
wedges[std::make_pair(ci, labels_(y+1, x)-1)]++;
379
wedges[std::make_pair(labels_(y+1, x)-1, ci)]++;
380
}
381
}
382
}
383
384
edges_.clear();
385
386
for (int ci = 0; ci < ncomps_-1; ++ci)
387
{
388
for (int cj = ci+1; cj < ncomps_; ++cj)
389
{
390
std::map<std::pair<int, int>, int>::iterator itr = wedges.find(std::make_pair(ci, cj));
391
if (itr != wedges.end() && itr->second > 0)
392
edges_.insert(itr->first);
393
394
itr = wedges.find(std::make_pair(cj, ci));
395
if (itr != wedges.end() && itr->second > 0)
396
edges_.insert(itr->first);
397
}
398
}
399
}
400
401
402
void DpSeamFinder::resolveConflicts(
403
const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2)
404
{
405
if (costFunc_ == COLOR_GRAD)
406
computeGradients(image1, image2);
407
408
// resolve conflicts between components
409
410
bool hasConflict = true;
411
while (hasConflict)
412
{
413
int c1 = 0, c2 = 0;
414
hasConflict = false;
415
416
for (std::set<std::pair<int, int> >::iterator itr = edges_.begin(); itr != edges_.end(); ++itr)
417
{
418
c1 = itr->first;
419
c2 = itr->second;
420
421
if ((states_[c1] & INTERS) && (states_[c1] & (~INTERS)) != states_[c2])
422
{
423
hasConflict = true;
424
break;
425
}
426
}
427
428
if (hasConflict)
429
{
430
int l1 = c1+1, l2 = c2+1;
431
432
if (hasOnlyOneNeighbor(c1))
433
{
434
// if the first components has only one adjacent component
435
436
for (int y = tls_[c1].y; y < brs_[c1].y; ++y)
437
for (int x = tls_[c1].x; x < brs_[c1].x; ++x)
438
if (labels_(y, x) == l1)
439
labels_(y, x) = l2;
440
441
states_[c1] = states_[c2] == FIRST ? SECOND : FIRST;
442
}
443
else
444
{
445
// if the first component has more than one adjacent component
446
447
Point p1, p2;
448
if (getSeamTips(c1, c2, p1, p2))
449
{
450
std::vector<Point> seam;
451
bool isHorizontalSeam;
452
453
if (estimateSeam(image1, image2, tl1, tl2, c1, p1, p2, seam, isHorizontalSeam))
454
updateLabelsUsingSeam(c1, c2, seam, isHorizontalSeam);
455
}
456
457
states_[c1] = states_[c2] == FIRST ? INTERS_SECOND : INTERS_FIRST;
458
}
459
460
const int c[] = {c1, c2};
461
const int l[] = {l1, l2};
462
463
for (int i = 0; i < 2; ++i)
464
{
465
// update information about the (i+1)-th component
466
467
int x0 = tls_[c[i]].x, x1 = brs_[c[i]].x;
468
int y0 = tls_[c[i]].y, y1 = brs_[c[i]].y;
469
470
tls_[c[i]] = Point(std::numeric_limits<int>::max(), std::numeric_limits<int>::max());
471
brs_[c[i]] = Point(std::numeric_limits<int>::min(), std::numeric_limits<int>::min());
472
contours_[c[i]].clear();
473
474
for (int y = y0; y < y1; ++y)
475
{
476
for (int x = x0; x < x1; ++x)
477
{
478
if (labels_(y, x) == l[i])
479
{
480
tls_[c[i]].x = std::min(tls_[c[i]].x, x);
481
tls_[c[i]].y = std::min(tls_[c[i]].y, y);
482
brs_[c[i]].x = std::max(brs_[c[i]].x, x+1);
483
brs_[c[i]].y = std::max(brs_[c[i]].y, y+1);
484
485
if ((x == 0 || labels_(y, x-1) != l[i]) || (x == unionSize_.width-1 || labels_(y, x+1) != l[i]) ||
486
(y == 0 || labels_(y-1, x) != l[i]) || (y == unionSize_.height-1 || labels_(y+1, x) != l[i]))
487
{
488
contours_[c[i]].push_back(Point(x, y));
489
}
490
}
491
}
492
}
493
}
494
495
// remove edges
496
497
edges_.erase(std::make_pair(c1, c2));
498
edges_.erase(std::make_pair(c2, c1));
499
}
500
}
501
502
// update masks
503
504
int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;
505
int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;
506
507
for (int y = 0; y < mask2.rows; ++y)
508
{
509
for (int x = 0; x < mask2.cols; ++x)
510
{
511
int l = labels_(y - dy2, x - dx2);
512
if (l > 0 && (states_[l-1] & FIRST) && mask1.at<uchar>(y - dy2 + dy1, x - dx2 + dx1))
513
mask2.at<uchar>(y, x) = 0;
514
}
515
}
516
517
for (int y = 0; y < mask1.rows; ++y)
518
{
519
for (int x = 0; x < mask1.cols; ++x)
520
{
521
int l = labels_(y - dy1, x - dx1);
522
if (l > 0 && (states_[l-1] & SECOND) && mask2.at<uchar>(y - dy1 + dy2, x - dx1 + dx2))
523
mask1.at<uchar>(y, x) = 0;
524
}
525
}
526
}
527
528
529
void DpSeamFinder::computeGradients(const Mat &image1, const Mat &image2)
530
{
531
CV_Assert(image1.channels() == 3 || image1.channels() == 4);
532
CV_Assert(image2.channels() == 3 || image2.channels() == 4);
533
CV_Assert(costFunction() == COLOR_GRAD);
534
535
Mat gray;
536
537
if (image1.channels() == 3)
538
cvtColor(image1, gray, COLOR_BGR2GRAY);
539
else if (image1.channels() == 4)
540
cvtColor(image1, gray, COLOR_BGRA2GRAY);
541
542
Sobel(gray, gradx1_, CV_32F, 1, 0);
543
Sobel(gray, grady1_, CV_32F, 0, 1);
544
545
if (image2.channels() == 3)
546
cvtColor(image2, gray, COLOR_BGR2GRAY);
547
else if (image2.channels() == 4)
548
cvtColor(image2, gray, COLOR_BGRA2GRAY);
549
550
Sobel(gray, gradx2_, CV_32F, 1, 0);
551
Sobel(gray, grady2_, CV_32F, 0, 1);
552
}
553
554
555
bool DpSeamFinder::hasOnlyOneNeighbor(int comp)
556
{
557
std::set<std::pair<int, int> >::iterator begin, end;
558
begin = lower_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::min()));
559
end = upper_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::max()));
560
return ++begin == end;
561
}
562
563
564
bool DpSeamFinder::closeToContour(int y, int x, const Mat_<uchar> &contourMask)
565
{
566
const int rad = 2;
567
568
for (int dy = -rad; dy <= rad; ++dy)
569
{
570
if (y + dy >= 0 && y + dy < unionSize_.height)
571
{
572
for (int dx = -rad; dx <= rad; ++dx)
573
{
574
if (x + dx >= 0 && x + dx < unionSize_.width &&
575
contourMask(y + dy, x + dx))
576
{
577
return true;
578
}
579
}
580
}
581
}
582
583
return false;
584
}
585
586
587
bool DpSeamFinder::getSeamTips(int comp1, int comp2, Point &p1, Point &p2)
588
{
589
CV_Assert(states_[comp1] & INTERS);
590
591
// find special points
592
593
std::vector<Point> specialPoints;
594
int l2 = comp2+1;
595
596
for (size_t i = 0; i < contours_[comp1].size(); ++i)
597
{
598
int x = contours_[comp1][i].x;
599
int y = contours_[comp1][i].y;
600
601
if (closeToContour(y, x, contour1mask_) &&
602
closeToContour(y, x, contour2mask_) &&
603
((x > 0 && labels_(y, x-1) == l2) ||
604
(y > 0 && labels_(y-1, x) == l2) ||
605
(x < unionSize_.width-1 && labels_(y, x+1) == l2) ||
606
(y < unionSize_.height-1 && labels_(y+1, x) == l2)))
607
{
608
specialPoints.push_back(Point(x, y));
609
}
610
}
611
612
if (specialPoints.size() < 2)
613
return false;
614
615
// find clusters
616
617
std::vector<int> labels;
618
cv::partition(specialPoints, labels, ClosePoints(10));
619
620
int nlabels = *std::max_element(labels.begin(), labels.end()) + 1;
621
if (nlabels < 2)
622
return false;
623
624
std::vector<Point> sum(nlabels);
625
std::vector<std::vector<Point> > points(nlabels);
626
627
for (size_t i = 0; i < specialPoints.size(); ++i)
628
{
629
sum[labels[i]] += specialPoints[i];
630
points[labels[i]].push_back(specialPoints[i]);
631
}
632
633
// select two most distant clusters
634
635
int idx[2] = {-1,-1};
636
double maxDist = -std::numeric_limits<double>::max();
637
638
for (int i = 0; i < nlabels-1; ++i)
639
{
640
for (int j = i+1; j < nlabels; ++j)
641
{
642
double size1 = static_cast<double>(points[i].size()), size2 = static_cast<double>(points[j].size());
643
double cx1 = cvRound(sum[i].x / size1), cy1 = cvRound(sum[i].y / size1);
644
double cx2 = cvRound(sum[j].x / size2), cy2 = cvRound(sum[j].y / size2);
645
646
double dist = (cx1 - cx2) * (cx1 - cx2) + (cy1 - cy2) * (cy1 - cy2);
647
if (dist > maxDist)
648
{
649
maxDist = dist;
650
idx[0] = i;
651
idx[1] = j;
652
}
653
}
654
}
655
656
// select two points closest to the clusters' centers
657
658
Point p[2];
659
660
for (int i = 0; i < 2; ++i)
661
{
662
double size = static_cast<double>(points[idx[i]].size());
663
double cx = cvRound(sum[idx[i]].x / size);
664
double cy = cvRound(sum[idx[i]].y / size);
665
666
size_t closest = points[idx[i]].size();
667
double minDist = std::numeric_limits<double>::max();
668
669
for (size_t j = 0; j < points[idx[i]].size(); ++j)
670
{
671
double dist = (points[idx[i]][j].x - cx) * (points[idx[i]][j].x - cx) +
672
(points[idx[i]][j].y - cy) * (points[idx[i]][j].y - cy);
673
if (dist < minDist)
674
{
675
minDist = dist;
676
closest = j;
677
}
678
}
679
680
p[i] = points[idx[i]][closest];
681
}
682
683
p1 = p[0];
684
p2 = p[1];
685
return true;
686
}
687
688
689
namespace
690
{
691
692
template <typename T>
693
float diffL2Square3(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2)
694
{
695
const T *r1 = image1.ptr<T>(y1);
696
const T *r2 = image2.ptr<T>(y2);
697
return static_cast<float>(sqr(r1[3*x1] - r2[3*x2]) + sqr(r1[3*x1+1] - r2[3*x2+1]) +
698
sqr(r1[3*x1+2] - r2[3*x2+2]));
699
}
700
701
702
template <typename T>
703
float diffL2Square4(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2)
704
{
705
const T *r1 = image1.ptr<T>(y1);
706
const T *r2 = image2.ptr<T>(y2);
707
return static_cast<float>(sqr(r1[4*x1] - r2[4*x2]) + sqr(r1[4*x1+1] - r2[4*x2+1]) +
708
sqr(r1[4*x1+2] - r2[4*x2+2]));
709
}
710
711
} // namespace
712
713
714
void DpSeamFinder::computeCosts(
715
const Mat &image1, const Mat &image2, Point tl1, Point tl2,
716
int comp, Mat_<float> &costV, Mat_<float> &costH)
717
{
718
CV_Assert(states_[comp] & INTERS);
719
720
// compute costs
721
722
float (*diff)(const Mat&, int, int, const Mat&, int, int) = 0;
723
if (image1.type() == CV_32FC3 && image2.type() == CV_32FC3)
724
diff = diffL2Square3<float>;
725
else if (image1.type() == CV_8UC3 && image2.type() == CV_8UC3)
726
diff = diffL2Square3<uchar>;
727
else if (image1.type() == CV_32FC4 && image2.type() == CV_32FC4)
728
diff = diffL2Square4<float>;
729
else if (image1.type() == CV_8UC4 && image2.type() == CV_8UC4)
730
diff = diffL2Square4<uchar>;
731
else
732
CV_Error(Error::StsBadArg, "both images must have CV_32FC3(4) or CV_8UC3(4) type");
733
734
int l = comp+1;
735
Rect roi(tls_[comp], brs_[comp]);
736
737
int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;
738
int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;
739
740
const float badRegionCost = normL2(Point3f(255.f, 255.f, 255.f),
741
Point3f(0.f, 0.f, 0.f));
742
743
costV.create(roi.height, roi.width+1);
744
745
for (int y = roi.y; y < roi.br().y; ++y)
746
{
747
for (int x = roi.x; x < roi.br().x+1; ++x)
748
{
749
if (labels_(y, x) == l && x > 0 && labels_(y, x-1) == l)
750
{
751
float costColor = (diff(image1, y + dy1, x + dx1 - 1, image2, y + dy2, x + dx2) +
752
diff(image1, y + dy1, x + dx1, image2, y + dy2, x + dx2 - 1)) / 2;
753
if (costFunc_ == COLOR)
754
costV(y - roi.y, x - roi.x) = costColor;
755
else if (costFunc_ == COLOR_GRAD)
756
{
757
float costGrad = std::abs(gradx1_(y + dy1, x + dx1)) + std::abs(gradx1_(y + dy1, x + dx1 - 1)) +
758
std::abs(gradx2_(y + dy2, x + dx2)) + std::abs(gradx2_(y + dy2, x + dx2 - 1)) + 1.f;
759
costV(y - roi.y, x - roi.x) = costColor / costGrad;
760
}
761
}
762
else
763
costV(y - roi.y, x - roi.x) = badRegionCost;
764
}
765
}
766
767
costH.create(roi.height+1, roi.width);
768
769
for (int y = roi.y; y < roi.br().y+1; ++y)
770
{
771
for (int x = roi.x; x < roi.br().x; ++x)
772
{
773
if (labels_(y, x) == l && y > 0 && labels_(y-1, x) == l)
774
{
775
float costColor = (diff(image1, y + dy1 - 1, x + dx1, image2, y + dy2, x + dx2) +
776
diff(image1, y + dy1, x + dx1, image2, y + dy2 - 1, x + dx2)) / 2;
777
if (costFunc_ == COLOR)
778
costH(y - roi.y, x - roi.x) = costColor;
779
else if (costFunc_ == COLOR_GRAD)
780
{
781
float costGrad = std::abs(grady1_(y + dy1, x + dx1)) + std::abs(grady1_(y + dy1 - 1, x + dx1)) +
782
std::abs(grady2_(y + dy2, x + dx2)) + std::abs(grady2_(y + dy2 - 1, x + dx2)) + 1.f;
783
costH(y - roi.y, x - roi.x) = costColor / costGrad;
784
}
785
}
786
else
787
costH(y - roi.y, x - roi.x) = badRegionCost;
788
}
789
}
790
}
791
792
793
bool DpSeamFinder::estimateSeam(
794
const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp,
795
Point p1, Point p2, std::vector<Point> &seam, bool &isHorizontal)
796
{
797
CV_Assert(states_[comp] & INTERS);
798
799
Mat_<float> costV, costH;
800
computeCosts(image1, image2, tl1, tl2, comp, costV, costH);
801
802
Rect roi(tls_[comp], brs_[comp]);
803
Point src = p1 - roi.tl();
804
Point dst = p2 - roi.tl();
805
int l = comp+1;
806
807
// estimate seam direction
808
809
bool swapped = false;
810
isHorizontal = std::abs(dst.x - src.x) > std::abs(dst.y - src.y);
811
812
if (isHorizontal)
813
{
814
if (src.x > dst.x)
815
{
816
std::swap(src, dst);
817
swapped = true;
818
}
819
}
820
else if (src.y > dst.y)
821
{
822
swapped = true;
823
std::swap(src, dst);
824
}
825
826
// find optimal control
827
828
Mat_<uchar> control = Mat::zeros(roi.size(), CV_8U);
829
Mat_<uchar> reachable = Mat::zeros(roi.size(), CV_8U);
830
Mat_<float> cost = Mat::zeros(roi.size(), CV_32F);
831
832
reachable(src) = 1;
833
cost(src) = 0.f;
834
835
int nsteps;
836
std::pair<float, int> steps[3];
837
838
if (isHorizontal)
839
{
840
for (int x = src.x+1; x <= dst.x; ++x)
841
{
842
for (int y = 0; y < roi.height; ++y)
843
{
844
// seam follows along upper side of pixels
845
846
nsteps = 0;
847
848
if (labels_(y + roi.y, x + roi.x) == l)
849
{
850
if (reachable(y, x-1))
851
steps[nsteps++] = std::make_pair(cost(y, x-1) + costH(y, x-1), 1);
852
if (y > 0 && reachable(y-1, x-1))
853
steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costH(y-1, x-1) + costV(y-1, x), 2);
854
if (y < roi.height-1 && reachable(y+1, x-1))
855
steps[nsteps++] = std::make_pair(cost(y+1, x-1) + costH(y+1, x-1) + costV(y, x), 3);
856
}
857
858
if (nsteps)
859
{
860
std::pair<float, int> opt = *min_element(steps, steps + nsteps);
861
cost(y, x) = opt.first;
862
control(y, x) = (uchar)opt.second;
863
reachable(y, x) = 255;
864
}
865
}
866
}
867
}
868
else
869
{
870
for (int y = src.y+1; y <= dst.y; ++y)
871
{
872
for (int x = 0; x < roi.width; ++x)
873
{
874
// seam follows along left side of pixels
875
876
nsteps = 0;
877
878
if (labels_(y + roi.y, x + roi.x) == l)
879
{
880
if (reachable(y-1, x))
881
steps[nsteps++] = std::make_pair(cost(y-1, x) + costV(y-1, x), 1);
882
if (x > 0 && reachable(y-1, x-1))
883
steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costV(y-1, x-1) + costH(y, x-1), 2);
884
if (x < roi.width-1 && reachable(y-1, x+1))
885
steps[nsteps++] = std::make_pair(cost(y-1, x+1) + costV(y-1, x+1) + costH(y, x), 3);
886
}
887
888
if (nsteps)
889
{
890
std::pair<float, int> opt = *min_element(steps, steps + nsteps);
891
cost(y, x) = opt.first;
892
control(y, x) = (uchar)opt.second;
893
reachable(y, x) = 255;
894
}
895
}
896
}
897
}
898
899
if (!reachable(dst))
900
return false;
901
902
// restore seam
903
904
Point p = dst;
905
seam.clear();
906
seam.push_back(p + roi.tl());
907
908
if (isHorizontal)
909
{
910
for (; p.x != src.x; seam.push_back(p + roi.tl()))
911
{
912
if (control(p) == 2) p.y--;
913
else if (control(p) == 3) p.y++;
914
p.x--;
915
}
916
}
917
else
918
{
919
for (; p.y != src.y; seam.push_back(p + roi.tl()))
920
{
921
if (control(p) == 2) p.x--;
922
else if (control(p) == 3) p.x++;
923
p.y--;
924
}
925
}
926
927
if (!swapped)
928
std::reverse(seam.begin(), seam.end());
929
930
CV_Assert(seam.front() == p1);
931
CV_Assert(seam.back() == p2);
932
return true;
933
}
934
935
936
void DpSeamFinder::updateLabelsUsingSeam(
937
int comp1, int comp2, const std::vector<Point> &seam, bool isHorizontalSeam)
938
{
939
Mat_<int> mask = Mat::zeros(brs_[comp1].y - tls_[comp1].y,
940
brs_[comp1].x - tls_[comp1].x, CV_32S);
941
942
for (size_t i = 0; i < contours_[comp1].size(); ++i)
943
mask(contours_[comp1][i] - tls_[comp1]) = 255;
944
945
for (size_t i = 0; i < seam.size(); ++i)
946
mask(seam[i] - tls_[comp1]) = 255;
947
948
// find connected components after seam carving
949
950
int l1 = comp1+1, l2 = comp2+1;
951
952
int ncomps = 0;
953
954
for (int y = 0; y < mask.rows; ++y)
955
for (int x = 0; x < mask.cols; ++x)
956
if (!mask(y, x) && labels_(y + tls_[comp1].y, x + tls_[comp1].x) == l1)
957
floodFill(mask, Point(x, y), ++ncomps);
958
959
for (size_t i = 0; i < contours_[comp1].size(); ++i)
960
{
961
int x = contours_[comp1][i].x - tls_[comp1].x;
962
int y = contours_[comp1][i].y - tls_[comp1].y;
963
964
bool ok = false;
965
static const int dx[] = {-1, +1, 0, 0, -1, +1, -1, +1};
966
static const int dy[] = {0, 0, -1, +1, -1, -1, +1, +1};
967
968
for (int j = 0; j < 8; ++j)
969
{
970
int c = x + dx[j];
971
int r = y + dy[j];
972
973
if (c >= 0 && c < mask.cols && r >= 0 && r < mask.rows &&
974
mask(r, c) && mask(r, c) != 255)
975
{
976
ok = true;
977
mask(y, x) = mask(r, c);
978
}
979
}
980
981
if (!ok)
982
mask(y, x) = 0;
983
}
984
985
if (isHorizontalSeam)
986
{
987
for (size_t i = 0; i < seam.size(); ++i)
988
{
989
int x = seam[i].x - tls_[comp1].x;
990
int y = seam[i].y - tls_[comp1].y;
991
992
if (y < mask.rows-1 && mask(y+1, x) && mask(y+1, x) != 255)
993
mask(y, x) = mask(y+1, x);
994
else
995
mask(y, x) = 0;
996
}
997
}
998
else
999
{
1000
for (size_t i = 0; i < seam.size(); ++i)
1001
{
1002
int x = seam[i].x - tls_[comp1].x;
1003
int y = seam[i].y - tls_[comp1].y;
1004
1005
if (x < mask.cols-1 && mask(y, x+1) && mask(y, x+1) != 255)
1006
mask(y, x) = mask(y, x+1);
1007
else
1008
mask(y, x) = 0;
1009
}
1010
}
1011
1012
// find new components connected with the second component and
1013
// with other components except the ones we are working with
1014
1015
std::map<int, int> connect2;
1016
std::map<int, int> connectOther;
1017
1018
for (int i = 1; i <= ncomps; ++i)
1019
{
1020
connect2.insert(std::make_pair(i, 0));
1021
connectOther.insert(std::make_pair(i, 0));
1022
}
1023
1024
for (size_t i = 0; i < contours_[comp1].size(); ++i)
1025
{
1026
int x = contours_[comp1][i].x;
1027
int y = contours_[comp1][i].y;
1028
1029
if ((x > 0 && labels_(y, x-1) == l2) ||
1030
(y > 0 && labels_(y-1, x) == l2) ||
1031
(x < unionSize_.width-1 && labels_(y, x+1) == l2) ||
1032
(y < unionSize_.height-1 && labels_(y+1, x) == l2))
1033
{
1034
connect2[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;
1035
}
1036
1037
if ((x > 0 && labels_(y, x-1) != l1 && labels_(y, x-1) != l2) ||
1038
(y > 0 && labels_(y-1, x) != l1 && labels_(y-1, x) != l2) ||
1039
(x < unionSize_.width-1 && labels_(y, x+1) != l1 && labels_(y, x+1) != l2) ||
1040
(y < unionSize_.height-1 && labels_(y+1, x) != l1 && labels_(y+1, x) != l2))
1041
{
1042
connectOther[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;
1043
}
1044
}
1045
1046
std::vector<int> isAdjComp(ncomps + 1, 0);
1047
1048
for (std::map<int, int>::iterator itr = connect2.begin(); itr != connect2.end(); ++itr)
1049
{
1050
double len = static_cast<double>(contours_[comp1].size());
1051
int res = 0;
1052
if (itr->second / len > 0.05)
1053
{
1054
std::map<int, int>::const_iterator sub = connectOther.find(itr->first);
1055
if (sub != connectOther.end() && (sub->second / len < 0.1))
1056
{
1057
res = 1;
1058
}
1059
}
1060
isAdjComp[itr->first] = res;
1061
}
1062
1063
// update labels
1064
1065
for (int y = 0; y < mask.rows; ++y)
1066
for (int x = 0; x < mask.cols; ++x)
1067
if (mask(y, x) && isAdjComp[mask(y, x)])
1068
labels_(y + tls_[comp1].y, x + tls_[comp1].x) = l2;
1069
}
1070
1071
1072
class GraphCutSeamFinder::Impl CV_FINAL : public PairwiseSeamFinder
1073
{
1074
public:
1075
Impl(int cost_type, float terminal_cost, float bad_region_penalty)
1076
: cost_type_(cost_type), terminal_cost_(terminal_cost), bad_region_penalty_(bad_region_penalty) {}
1077
1078
~Impl() {}
1079
1080
void find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) CV_OVERRIDE;
1081
void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE;
1082
1083
private:
1084
void setGraphWeightsColor(const Mat &img1, const Mat &img2,
1085
const Mat &mask1, const Mat &mask2, GCGraph<float> &graph);
1086
void setGraphWeightsColorGrad(const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,
1087
const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,
1088
GCGraph<float> &graph);
1089
1090
std::vector<Mat> dx_, dy_;
1091
int cost_type_;
1092
float terminal_cost_;
1093
float bad_region_penalty_;
1094
};
1095
1096
1097
void GraphCutSeamFinder::Impl::find(const std::vector<UMat> &src, const std::vector<Point> &corners,
1098
std::vector<UMat> &masks)
1099
{
1100
// Compute gradients
1101
dx_.resize(src.size());
1102
dy_.resize(src.size());
1103
Mat dx, dy;
1104
for (size_t i = 0; i < src.size(); ++i)
1105
{
1106
CV_Assert(src[i].channels() == 3);
1107
Sobel(src[i], dx, CV_32F, 1, 0);
1108
Sobel(src[i], dy, CV_32F, 0, 1);
1109
dx_[i].create(src[i].size(), CV_32F);
1110
dy_[i].create(src[i].size(), CV_32F);
1111
for (int y = 0; y < src[i].rows; ++y)
1112
{
1113
const Point3f* dx_row = dx.ptr<Point3f>(y);
1114
const Point3f* dy_row = dy.ptr<Point3f>(y);
1115
float* dx_row_ = dx_[i].ptr<float>(y);
1116
float* dy_row_ = dy_[i].ptr<float>(y);
1117
for (int x = 0; x < src[i].cols; ++x)
1118
{
1119
dx_row_[x] = normL2(dx_row[x]);
1120
dy_row_[x] = normL2(dy_row[x]);
1121
}
1122
}
1123
}
1124
PairwiseSeamFinder::find(src, corners, masks);
1125
}
1126
1127
1128
void GraphCutSeamFinder::Impl::setGraphWeightsColor(const Mat &img1, const Mat &img2,
1129
const Mat &mask1, const Mat &mask2, GCGraph<float> &graph)
1130
{
1131
const Size img_size = img1.size();
1132
1133
// Set terminal weights
1134
for (int y = 0; y < img_size.height; ++y)
1135
{
1136
for (int x = 0; x < img_size.width; ++x)
1137
{
1138
int v = graph.addVtx();
1139
graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,
1140
mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);
1141
}
1142
}
1143
1144
// Set regular edge weights
1145
const float weight_eps = 1.f;
1146
for (int y = 0; y < img_size.height; ++y)
1147
{
1148
for (int x = 0; x < img_size.width; ++x)
1149
{
1150
int v = y * img_size.width + x;
1151
if (x < img_size.width - 1)
1152
{
1153
float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1154
normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) +
1155
weight_eps;
1156
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
1157
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
1158
weight += bad_region_penalty_;
1159
graph.addEdges(v, v + 1, weight, weight);
1160
}
1161
if (y < img_size.height - 1)
1162
{
1163
float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1164
normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) +
1165
weight_eps;
1166
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
1167
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
1168
weight += bad_region_penalty_;
1169
graph.addEdges(v, v + img_size.width, weight, weight);
1170
}
1171
}
1172
}
1173
}
1174
1175
1176
void GraphCutSeamFinder::Impl::setGraphWeightsColorGrad(
1177
const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,
1178
const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,
1179
GCGraph<float> &graph)
1180
{
1181
const Size img_size = img1.size();
1182
1183
// Set terminal weights
1184
for (int y = 0; y < img_size.height; ++y)
1185
{
1186
for (int x = 0; x < img_size.width; ++x)
1187
{
1188
int v = graph.addVtx();
1189
graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,
1190
mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);
1191
}
1192
}
1193
1194
// Set regular edge weights
1195
const float weight_eps = 1.f;
1196
for (int y = 0; y < img_size.height; ++y)
1197
{
1198
for (int x = 0; x < img_size.width; ++x)
1199
{
1200
int v = y * img_size.width + x;
1201
if (x < img_size.width - 1)
1202
{
1203
float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) +
1204
dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps;
1205
float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1206
normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad +
1207
weight_eps;
1208
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
1209
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
1210
weight += bad_region_penalty_;
1211
graph.addEdges(v, v + 1, weight, weight);
1212
}
1213
if (y < img_size.height - 1)
1214
{
1215
float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) +
1216
dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps;
1217
float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1218
normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad +
1219
weight_eps;
1220
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
1221
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
1222
weight += bad_region_penalty_;
1223
graph.addEdges(v, v + img_size.width, weight, weight);
1224
}
1225
}
1226
}
1227
}
1228
1229
1230
void GraphCutSeamFinder::Impl::findInPair(size_t first, size_t second, Rect roi)
1231
{
1232
Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ);
1233
Mat dx1 = dx_[first], dx2 = dx_[second];
1234
Mat dy1 = dy_[first], dy2 = dy_[second];
1235
Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW);
1236
Point tl1 = corners_[first], tl2 = corners_[second];
1237
1238
const int gap = 10;
1239
Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
1240
Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
1241
Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
1242
Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
1243
Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1244
Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1245
Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1246
Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1247
1248
// Cut subimages and submasks with some gap
1249
for (int y = -gap; y < roi.height + gap; ++y)
1250
{
1251
for (int x = -gap; x < roi.width + gap; ++x)
1252
{
1253
int y1 = roi.y - tl1.y + y;
1254
int x1 = roi.x - tl1.x + x;
1255
if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols)
1256
{
1257
subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1);
1258
submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);
1259
subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1);
1260
subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1);
1261
}
1262
else
1263
{
1264
subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
1265
submask1.at<uchar>(y + gap, x + gap) = 0;
1266
subdx1.at<float>(y + gap, x + gap) = 0.f;
1267
subdy1.at<float>(y + gap, x + gap) = 0.f;
1268
}
1269
1270
int y2 = roi.y - tl2.y + y;
1271
int x2 = roi.x - tl2.x + x;
1272
if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols)
1273
{
1274
subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2);
1275
submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);
1276
subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2);
1277
subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2);
1278
}
1279
else
1280
{
1281
subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
1282
submask2.at<uchar>(y + gap, x + gap) = 0;
1283
subdx2.at<float>(y + gap, x + gap) = 0.f;
1284
subdy2.at<float>(y + gap, x + gap) = 0.f;
1285
}
1286
}
1287
}
1288
1289
const int vertex_count = (roi.height + 2 * gap) * (roi.width + 2 * gap);
1290
const int edge_count = (roi.height - 1 + 2 * gap) * (roi.width + 2 * gap) +
1291
(roi.width - 1 + 2 * gap) * (roi.height + 2 * gap);
1292
GCGraph<float> graph(vertex_count, edge_count);
1293
1294
switch (cost_type_)
1295
{
1296
case GraphCutSeamFinder::COST_COLOR:
1297
setGraphWeightsColor(subimg1, subimg2, submask1, submask2, graph);
1298
break;
1299
case GraphCutSeamFinder::COST_COLOR_GRAD:
1300
setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2,
1301
submask1, submask2, graph);
1302
break;
1303
default:
1304
CV_Error(Error::StsBadArg, "unsupported pixel similarity measure");
1305
}
1306
1307
graph.maxFlow();
1308
1309
for (int y = 0; y < roi.height; ++y)
1310
{
1311
for (int x = 0; x < roi.width; ++x)
1312
{
1313
if (graph.inSourceSegment((y + gap) * (roi.width + 2 * gap) + x + gap))
1314
{
1315
if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x))
1316
mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;
1317
}
1318
else
1319
{
1320
if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x))
1321
mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;
1322
}
1323
}
1324
}
1325
}
1326
1327
1328
GraphCutSeamFinder::GraphCutSeamFinder(int cost_type, float terminal_cost, float bad_region_penalty)
1329
: impl_(new Impl(cost_type, terminal_cost, bad_region_penalty)) {}
1330
1331
GraphCutSeamFinder::~GraphCutSeamFinder() {}
1332
1333
1334
void GraphCutSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners,
1335
std::vector<UMat> &masks)
1336
{
1337
impl_->find(src, corners, masks);
1338
}
1339
1340
1341
#ifdef HAVE_OPENCV_CUDALEGACY
1342
void GraphCutSeamFinderGpu::find(const std::vector<UMat> &src, const std::vector<Point> &corners,
1343
std::vector<UMat> &masks)
1344
{
1345
// Compute gradients
1346
dx_.resize(src.size());
1347
dy_.resize(src.size());
1348
Mat dx, dy;
1349
for (size_t i = 0; i < src.size(); ++i)
1350
{
1351
CV_Assert(src[i].channels() == 3);
1352
Sobel(src[i], dx, CV_32F, 1, 0);
1353
Sobel(src[i], dy, CV_32F, 0, 1);
1354
dx_[i].create(src[i].size(), CV_32F);
1355
dy_[i].create(src[i].size(), CV_32F);
1356
for (int y = 0; y < src[i].rows; ++y)
1357
{
1358
const Point3f* dx_row = dx.ptr<Point3f>(y);
1359
const Point3f* dy_row = dy.ptr<Point3f>(y);
1360
float* dx_row_ = dx_[i].ptr<float>(y);
1361
float* dy_row_ = dy_[i].ptr<float>(y);
1362
for (int x = 0; x < src[i].cols; ++x)
1363
{
1364
dx_row_[x] = normL2(dx_row[x]);
1365
dy_row_[x] = normL2(dy_row[x]);
1366
}
1367
}
1368
}
1369
PairwiseSeamFinder::find(src, corners, masks);
1370
}
1371
1372
1373
void GraphCutSeamFinderGpu::findInPair(size_t first, size_t second, Rect roi)
1374
{
1375
Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ);
1376
Mat dx1 = dx_[first], dx2 = dx_[second];
1377
Mat dy1 = dy_[first], dy2 = dy_[second];
1378
Mat mask1 = masks_[first].getMat(ACCESS_READ), mask2 = masks_[second].getMat(ACCESS_READ);
1379
Point tl1 = corners_[first], tl2 = corners_[second];
1380
1381
const int gap = 10;
1382
Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
1383
Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
1384
Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
1385
Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
1386
Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1387
Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1388
Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1389
Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
1390
1391
// Cut subimages and submasks with some gap
1392
for (int y = -gap; y < roi.height + gap; ++y)
1393
{
1394
for (int x = -gap; x < roi.width + gap; ++x)
1395
{
1396
int y1 = roi.y - tl1.y + y;
1397
int x1 = roi.x - tl1.x + x;
1398
if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols)
1399
{
1400
subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1);
1401
submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);
1402
subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1);
1403
subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1);
1404
}
1405
else
1406
{
1407
subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
1408
submask1.at<uchar>(y + gap, x + gap) = 0;
1409
subdx1.at<float>(y + gap, x + gap) = 0.f;
1410
subdy1.at<float>(y + gap, x + gap) = 0.f;
1411
}
1412
1413
int y2 = roi.y - tl2.y + y;
1414
int x2 = roi.x - tl2.x + x;
1415
if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols)
1416
{
1417
subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2);
1418
submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);
1419
subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2);
1420
subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2);
1421
}
1422
else
1423
{
1424
subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
1425
submask2.at<uchar>(y + gap, x + gap) = 0;
1426
subdx2.at<float>(y + gap, x + gap) = 0.f;
1427
subdy2.at<float>(y + gap, x + gap) = 0.f;
1428
}
1429
}
1430
}
1431
1432
Mat terminals, leftT, rightT, top, bottom;
1433
1434
switch (cost_type_)
1435
{
1436
case GraphCutSeamFinder::COST_COLOR:
1437
setGraphWeightsColor(subimg1, subimg2, submask1, submask2,
1438
terminals, leftT, rightT, top, bottom);
1439
break;
1440
case GraphCutSeamFinder::COST_COLOR_GRAD:
1441
setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2,
1442
submask1, submask2, terminals, leftT, rightT, top, bottom);
1443
break;
1444
default:
1445
CV_Error(Error::StsBadArg, "unsupported pixel similarity measure");
1446
}
1447
1448
cuda::GpuMat terminals_d(terminals);
1449
cuda::GpuMat leftT_d(leftT);
1450
cuda::GpuMat rightT_d(rightT);
1451
cuda::GpuMat top_d(top);
1452
cuda::GpuMat bottom_d(bottom);
1453
cuda::GpuMat labels_d, buf_d;
1454
1455
cuda::graphcut(terminals_d, leftT_d, rightT_d, top_d, bottom_d, labels_d, buf_d);
1456
1457
Mat_<uchar> labels = (Mat)labels_d;
1458
for (int y = 0; y < roi.height; ++y)
1459
{
1460
for (int x = 0; x < roi.width; ++x)
1461
{
1462
if (labels(y + gap, x + gap))
1463
{
1464
if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x))
1465
mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;
1466
}
1467
else
1468
{
1469
if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x))
1470
mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;
1471
}
1472
}
1473
}
1474
}
1475
1476
1477
void GraphCutSeamFinderGpu::setGraphWeightsColor(const Mat &img1, const Mat &img2, const Mat &mask1, const Mat &mask2,
1478
Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom)
1479
{
1480
const Size img_size = img1.size();
1481
1482
terminals.create(img_size, CV_32S);
1483
leftT.create(Size(img_size.height, img_size.width), CV_32S);
1484
rightT.create(Size(img_size.height, img_size.width), CV_32S);
1485
top.create(img_size, CV_32S);
1486
bottom.create(img_size, CV_32S);
1487
1488
Mat_<int> terminals_(terminals);
1489
Mat_<int> leftT_(leftT);
1490
Mat_<int> rightT_(rightT);
1491
Mat_<int> top_(top);
1492
Mat_<int> bottom_(bottom);
1493
1494
// Set terminal weights
1495
for (int y = 0; y < img_size.height; ++y)
1496
{
1497
for (int x = 0; x < img_size.width; ++x)
1498
{
1499
float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f;
1500
float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f;
1501
terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f);
1502
}
1503
}
1504
1505
// Set regular edge weights
1506
const float weight_eps = 1.f;
1507
for (int y = 0; y < img_size.height; ++y)
1508
{
1509
for (int x = 0; x < img_size.width; ++x)
1510
{
1511
if (x > 0)
1512
{
1513
float weight = normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) +
1514
normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1515
weight_eps;
1516
if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) ||
1517
!mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x))
1518
weight += bad_region_penalty_;
1519
leftT_(x, y) = saturate_cast<int>(weight * 255.f);
1520
}
1521
else
1522
leftT_(x, y) = 0;
1523
1524
if (x < img_size.width - 1)
1525
{
1526
float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1527
normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) +
1528
weight_eps;
1529
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
1530
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
1531
weight += bad_region_penalty_;
1532
rightT_(x, y) = saturate_cast<int>(weight * 255.f);
1533
}
1534
else
1535
rightT_(x, y) = 0;
1536
1537
if (y > 0)
1538
{
1539
float weight = normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) +
1540
normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1541
weight_eps;
1542
if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) ||
1543
!mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x))
1544
weight += bad_region_penalty_;
1545
top_(y, x) = saturate_cast<int>(weight * 255.f);
1546
}
1547
else
1548
top_(y, x) = 0;
1549
1550
if (y < img_size.height - 1)
1551
{
1552
float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1553
normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) +
1554
weight_eps;
1555
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
1556
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
1557
weight += bad_region_penalty_;
1558
bottom_(y, x) = saturate_cast<int>(weight * 255.f);
1559
}
1560
else
1561
bottom_(y, x) = 0;
1562
}
1563
}
1564
}
1565
1566
1567
void GraphCutSeamFinderGpu::setGraphWeightsColorGrad(
1568
const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,
1569
const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,
1570
Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom)
1571
{
1572
const Size img_size = img1.size();
1573
1574
terminals.create(img_size, CV_32S);
1575
leftT.create(Size(img_size.height, img_size.width), CV_32S);
1576
rightT.create(Size(img_size.height, img_size.width), CV_32S);
1577
top.create(img_size, CV_32S);
1578
bottom.create(img_size, CV_32S);
1579
1580
Mat_<int> terminals_(terminals);
1581
Mat_<int> leftT_(leftT);
1582
Mat_<int> rightT_(rightT);
1583
Mat_<int> top_(top);
1584
Mat_<int> bottom_(bottom);
1585
1586
// Set terminal weights
1587
for (int y = 0; y < img_size.height; ++y)
1588
{
1589
for (int x = 0; x < img_size.width; ++x)
1590
{
1591
float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f;
1592
float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f;
1593
terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f);
1594
}
1595
}
1596
1597
// Set regular edge weights
1598
const float weight_eps = 1.f;
1599
for (int y = 0; y < img_size.height; ++y)
1600
{
1601
for (int x = 0; x < img_size.width; ++x)
1602
{
1603
if (x > 0)
1604
{
1605
float grad = dx1.at<float>(y, x - 1) + dx1.at<float>(y, x) +
1606
dx2.at<float>(y, x - 1) + dx2.at<float>(y, x) + weight_eps;
1607
float weight = (normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) +
1608
normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad +
1609
weight_eps;
1610
if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) ||
1611
!mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x))
1612
weight += bad_region_penalty_;
1613
leftT_(x, y) = saturate_cast<int>(weight * 255.f);
1614
}
1615
else
1616
leftT_(x, y) = 0;
1617
1618
if (x < img_size.width - 1)
1619
{
1620
float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) +
1621
dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps;
1622
float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1623
normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad +
1624
weight_eps;
1625
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
1626
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
1627
weight += bad_region_penalty_;
1628
rightT_(x, y) = saturate_cast<int>(weight * 255.f);
1629
}
1630
else
1631
rightT_(x, y) = 0;
1632
1633
if (y > 0)
1634
{
1635
float grad = dy1.at<float>(y - 1, x) + dy1.at<float>(y, x) +
1636
dy2.at<float>(y - 1, x) + dy2.at<float>(y, x) + weight_eps;
1637
float weight = (normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) +
1638
normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad +
1639
weight_eps;
1640
if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) ||
1641
!mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x))
1642
weight += bad_region_penalty_;
1643
top_(y, x) = saturate_cast<int>(weight * 255.f);
1644
}
1645
else
1646
top_(y, x) = 0;
1647
1648
if (y < img_size.height - 1)
1649
{
1650
float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) +
1651
dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps;
1652
float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
1653
normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad +
1654
weight_eps;
1655
if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
1656
!mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
1657
weight += bad_region_penalty_;
1658
bottom_(y, x) = saturate_cast<int>(weight * 255.f);
1659
}
1660
else
1661
bottom_(y, x) = 0;
1662
}
1663
}
1664
}
1665
#endif
1666
1667
} // namespace detail
1668
} // namespace cv
1669
1670