1
/*M///////////////////////////////////////////////////////////////////////////////////////
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11
// For Open Source Computer Vision Library
13
// Copyright (C) 2000, Intel Corporation, all rights reserved.
14
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
15
// Third party copyrights are property of their respective owners.
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
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.
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.
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.
43
#include "precomp.hpp"
45
/****************************************************************************************\
47
\****************************************************************************************/
51
// A node represents a pixel to label
62
WSQueue() { first = last = 0; }
68
allocWSNodes( std::vector<WSNode>& storage )
70
int sz = (int)storage.size();
71
int newsz = MAX(128, sz*3/2);
73
storage.resize(newsz);
79
for( int i = sz; i < newsz-1; i++ )
80
storage[i].next = i+1;
81
storage[newsz-1].next = 0;
88
void cv::watershed( InputArray _src, InputOutputArray _markers )
91
const int IN_QUEUE = -2; // Pixel visited
92
const int WSHED = -1; // Pixel belongs to watershed
94
// possible bit values = 2^8
97
Mat src = _src.getMat(), dst = _markers.getMat();
98
Size size = src.size();
100
// Vector of every created node
101
std::vector<WSNode> storage;
102
int free_node = 0, node;
103
// Priority queue of queues of nodes
104
// from high priority (0) to low priority (255)
106
// Non-empty queue with highest priority
113
// MAX(a,b) = b + MAX(a-b,0)
114
#define ws_max(a,b) ((b) + subs_tab[(a)-(b)+NQ])
115
// MIN(a,b) = a - MAX(a-b,0)
116
#define ws_min(a,b) ((a) - subs_tab[(a)-(b)+NQ])
118
// Create a new node with offsets mofs and iofs in queue idx
119
#define ws_push(idx,mofs,iofs) \
122
free_node = allocWSNodes( storage );\
124
free_node = storage[free_node].next;\
125
storage[node].next = 0; \
126
storage[node].mask_ofs = mofs; \
127
storage[node].img_ofs = iofs; \
129
storage[q[idx].last].next=node; \
131
q[idx].first = node; \
132
q[idx].last = node; \
135
// Get next node from queue idx
136
#define ws_pop(idx,mofs,iofs) \
138
node = q[idx].first; \
139
q[idx].first = storage[node].next; \
140
if( !storage[node].next ) \
142
storage[node].next = free_node; \
144
mofs = storage[node].mask_ofs; \
145
iofs = storage[node].img_ofs; \
148
// Get highest absolute channel difference in diff
149
#define c_diff(ptr1,ptr2,diff) \
151
db = std::abs((ptr1)[0] - (ptr2)[0]);\
152
dg = std::abs((ptr1)[1] - (ptr2)[1]);\
153
dr = std::abs((ptr1)[2] - (ptr2)[2]);\
154
diff = ws_max(db,dg); \
155
diff = ws_max(diff,dr); \
156
assert( 0 <= diff && diff <= 255 ); \
159
CV_Assert( src.type() == CV_8UC3 && dst.type() == CV_32SC1 );
160
CV_Assert( src.size() == dst.size() );
162
// Current pixel in input image
163
const uchar* img = src.ptr();
164
// Step size to next row in input image
165
int istep = int(src.step/sizeof(img[0]));
167
// Current pixel in mask image
168
int* mask = dst.ptr<int>();
169
// Step size to next row in mask image
170
int mstep = int(dst.step / sizeof(mask[0]));
172
for( i = 0; i < 256; i++ )
174
for( i = 256; i <= 512; i++ )
175
subs_tab[i] = i - 256;
177
// draw a pixel-wide border of dummy "watershed" (i.e. boundary) pixels
178
for( j = 0; j < size.width; j++ )
179
mask[j] = mask[j + mstep*(size.height-1)] = WSHED;
181
// initial phase: put all the neighbor pixels of each marker to the ordered queue -
182
// determine the initial boundaries of the basins
183
for( i = 1; i < size.height-1; i++ )
185
img += istep; mask += mstep;
186
mask[0] = mask[size.width-1] = WSHED; // boundary pixels
188
for( j = 1; j < size.width-1; j++ )
191
if( m[0] < 0 ) m[0] = 0;
192
if( m[0] == 0 && (m[-1] > 0 || m[1] > 0 || m[-mstep] > 0 || m[mstep] > 0) )
194
// Find smallest difference to adjacent markers
195
const uchar* ptr = img + j*3;
198
c_diff( ptr, ptr - 3, idx );
201
c_diff( ptr, ptr + 3, t );
202
idx = ws_min( idx, t );
206
c_diff( ptr, ptr - istep, t );
207
idx = ws_min( idx, t );
211
c_diff( ptr, ptr + istep, t );
212
idx = ws_min( idx, t );
215
// Add to according queue
216
assert( 0 <= idx && idx <= 255 );
217
ws_push( idx, i*mstep + j, i*istep + j*3 );
223
// find the first non-empty queue
224
for( i = 0; i < NQ; i++ )
228
// if there is no markers, exit immediately
234
mask = dst.ptr<int>();
236
// recursively fill the basins
244
// Get non-empty queue with highest priority
245
// Exit condition: empty priority queue
246
if( q[active_queue].first == 0 )
248
for( i = active_queue+1; i < NQ; i++ )
257
ws_pop( active_queue, mofs, iofs );
259
// Calculate pointer to current pixel in input and marker image
263
// Check surrounding pixels for labels
264
// to determine label for current pixel
270
if( lab == 0 ) lab = t;
271
else if( t != lab ) lab = WSHED;
273
t = m[-mstep]; // Top
276
if( lab == 0 ) lab = t;
277
else if( t != lab ) lab = WSHED;
279
t = m[mstep]; // Bottom
282
if( lab == 0 ) lab = t;
283
else if( t != lab ) lab = WSHED;
286
// Set label to current pixel in marker image
293
// Add adjacent, unlabeled pixels to corresponding queue
296
c_diff( ptr, ptr - 3, t );
297
ws_push( t, mofs - 1, iofs - 3 );
298
active_queue = ws_min( active_queue, t );
303
c_diff( ptr, ptr + 3, t );
304
ws_push( t, mofs + 1, iofs + 3 );
305
active_queue = ws_min( active_queue, t );
310
c_diff( ptr, ptr - istep, t );
311
ws_push( t, mofs - mstep, iofs - istep );
312
active_queue = ws_min( active_queue, t );
313
m[-mstep] = IN_QUEUE;
317
c_diff( ptr, ptr + istep, t );
318
ws_push( t, mofs + mstep, iofs + istep );
319
active_queue = ws_min( active_queue, t );
326
/****************************************************************************************\
328
\****************************************************************************************/
331
void cv::pyrMeanShiftFiltering( InputArray _src, OutputArray _dst,
332
double sp0, double sr, int max_level,
333
TermCriteria termcrit )
335
Mat src0 = _src.getMat();
340
_dst.create( src0.size(), src0.type() );
341
Mat dst0 = _dst.getMat();
344
const int MAX_LEVELS = 8;
346
if( (unsigned)max_level > (unsigned)MAX_LEVELS )
347
CV_Error( CV_StsOutOfRange, "The number of pyramid levels is too large or negative" );
349
std::vector<cv::Mat> src_pyramid(max_level+1);
350
std::vector<cv::Mat> dst_pyramid(max_level+1);
353
//uchar* submask = 0;
355
#define cdiff(ofs0) (tab[c0-dptr[ofs0]+255] + \
356
tab[c1-dptr[(ofs0)+1]+255] + tab[c2-dptr[(ofs0)+2]+255] >= isr22)
358
double sr2 = sr * sr;
359
int isr2 = cvRound(sr2), isr22 = MAX(isr2,16);
363
if( src0.type() != CV_8UC3 )
364
CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 3-channel images are supported" );
366
if( src0.type() != dst0.type() )
367
CV_Error( CV_StsUnmatchedFormats, "The input and output images must have the same type" );
369
if( src0.size() != dst0.size() )
370
CV_Error( CV_StsUnmatchedSizes, "The input and output images must have the same size" );
372
if( !(termcrit.type & CV_TERMCRIT_ITER) )
373
termcrit.maxCount = 5;
374
termcrit.maxCount = MAX(termcrit.maxCount,1);
375
termcrit.maxCount = MIN(termcrit.maxCount,100);
376
if( !(termcrit.type & CV_TERMCRIT_EPS) )
377
termcrit.epsilon = 1.f;
378
termcrit.epsilon = MAX(termcrit.epsilon, 0.f);
380
for( i = 0; i < 768; i++ )
381
tab[i] = (i - 255)*(i - 255);
383
// 1. construct pyramid
384
src_pyramid[0] = src0;
385
dst_pyramid[0] = dst0;
386
for( level = 1; level <= max_level; level++ )
388
src_pyramid[level].create( (src_pyramid[level-1].rows+1)/2,
389
(src_pyramid[level-1].cols+1)/2, src_pyramid[level-1].type() );
390
dst_pyramid[level].create( src_pyramid[level].rows,
391
src_pyramid[level].cols, src_pyramid[level].type() );
392
cv::pyrDown( src_pyramid[level-1], src_pyramid[level], src_pyramid[level].size() );
393
//CV_CALL( cvResize( src_pyramid[level-1], src_pyramid[level], CV_INTER_AREA ));
396
mask0.create(src0.rows, src0.cols, CV_8UC1);
397
//CV_CALL( submask = (uchar*)cvAlloc( (sp+2)*(sp+2) ));
399
// 2. apply meanshift, starting from the pyramid top (i.e. the smallest layer)
400
for( level = max_level; level >= 0; level-- )
402
cv::Mat src = src_pyramid[level];
403
cv::Size size = src.size();
404
const uchar* sptr = src.ptr();
405
int sstep = (int)src.step;
410
float sp = (float)(sp0 / (1 << level));
413
if( level < max_level )
415
cv::Size size1 = dst_pyramid[level+1].size();
416
cv::Mat m( size.height, size.width, CV_8UC1, mask0.ptr() );
417
dstep = (int)dst_pyramid[level+1].step;
418
dptr = dst_pyramid[level+1].ptr() + dstep + cn;
420
mask = m.ptr() + mstep;
421
//cvResize( dst_pyramid[level+1], dst_pyramid[level], CV_INTER_CUBIC );
422
cv::pyrUp( dst_pyramid[level+1], dst_pyramid[level], dst_pyramid[level].size() );
423
m.setTo(cv::Scalar::all(0));
425
for( i = 1; i < size1.height-1; i++, dptr += dstep - (size1.width-2)*3, mask += mstep*2 )
427
for( j = 1; j < size1.width-1; j++, dptr += cn )
429
int c0 = dptr[0], c1 = dptr[1], c2 = dptr[2];
430
mask[j*2 - 1] = cdiff(-3) || cdiff(3) || cdiff(-dstep-3) || cdiff(-dstep) ||
431
cdiff(-dstep+3) || cdiff(dstep-3) || cdiff(dstep) || cdiff(dstep+3);
435
cv::dilate( m, m, cv::Mat() );
439
dptr = dst_pyramid[level].ptr();
440
dstep = (int)dst_pyramid[level].step;
442
for( i = 0; i < size.height; i++, sptr += sstep - size.width*3,
443
dptr += dstep - size.width*3,
446
for( j = 0; j < size.width; j++, sptr += 3, dptr += 3 )
448
int x0 = j, y0 = i, x1, y1, iter;
451
if( mask && !mask[j] )
454
c0 = sptr[0], c1 = sptr[1], c2 = sptr[2];
456
// iterate meanshift procedure
457
for( iter = 0; iter < termcrit.maxCount; iter++ )
461
int minx, miny, maxx, maxy;
462
int s0 = 0, s1 = 0, s2 = 0, sx = 0, sy = 0;
466
//mean shift: process pixels in window (p-sigmaSp)x(p+sigmaSp)
467
minx = cvRound(x0 - sp); minx = MAX(minx, 0);
468
miny = cvRound(y0 - sp); miny = MAX(miny, 0);
469
maxx = cvRound(x0 + sp); maxx = MIN(maxx, size.width-1);
470
maxy = cvRound(y0 + sp); maxy = MIN(maxy, size.height-1);
471
ptr = sptr + (miny - i)*sstep + (minx - j)*3;
473
for( y = miny; y <= maxy; y++, ptr += sstep - (maxx-minx+1)*3 )
477
#if CV_ENABLE_UNROLLED
478
for( ; x + 3 <= maxx; x += 4, ptr += 12 )
480
int t0 = ptr[0], t1 = ptr[1], t2 = ptr[2];
481
if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
483
s0 += t0; s1 += t1; s2 += t2;
484
sx += x; row_count++;
486
t0 = ptr[3], t1 = ptr[4], t2 = ptr[5];
487
if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
489
s0 += t0; s1 += t1; s2 += t2;
490
sx += x+1; row_count++;
492
t0 = ptr[6], t1 = ptr[7], t2 = ptr[8];
493
if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
495
s0 += t0; s1 += t1; s2 += t2;
496
sx += x+2; row_count++;
498
t0 = ptr[9], t1 = ptr[10], t2 = ptr[11];
499
if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
501
s0 += t0; s1 += t1; s2 += t2;
502
sx += x+3; row_count++;
506
for( ; x <= maxx; x++, ptr += 3 )
508
int t0 = ptr[0], t1 = ptr[1], t2 = ptr[2];
509
if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
511
s0 += t0; s1 += t1; s2 += t2;
512
sx += x; row_count++;
523
x1 = cvRound(sx*icount);
524
y1 = cvRound(sy*icount);
525
s0 = cvRound(s0*icount);
526
s1 = cvRound(s1*icount);
527
s2 = cvRound(s2*icount);
529
stop_flag = (x0 == x1 && y0 == y1) || std::abs(x1-x0) + std::abs(y1-y0) +
530
tab[s0 - c0 + 255] + tab[s1 - c1 + 255] +
531
tab[s2 - c2 + 255] <= termcrit.epsilon;
534
c0 = s0; c1 = s1; c2 = s2;
549
///////////////////////////////////////////////////////////////////////////////////////////////
551
CV_IMPL void cvWatershed( const CvArr* _src, CvArr* _markers )
553
cv::Mat src = cv::cvarrToMat(_src), markers = cv::cvarrToMat(_markers);
554
cv::watershed(src, markers);
559
cvPyrMeanShiftFiltering( const CvArr* srcarr, CvArr* dstarr,
560
double sp0, double sr, int max_level,
561
CvTermCriteria termcrit )
563
cv::Mat src = cv::cvarrToMat(srcarr);
564
const cv::Mat dst = cv::cvarrToMat(dstarr);
566
cv::pyrMeanShiftFiltering(src, dst, sp0, sr, max_level, termcrit);