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.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // 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 damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
44 /****************************************************************************************\
46 \****************************************************************************************/
48 typedef struct CvWSNode
50 struct CvWSNode* next;
56 typedef struct CvWSQueue
64 icvAllocWSNodes( CvMemStorage* storage )
68 CV_FUNCNAME( "icvAllocWSNodes" );
72 int i, count = (storage->block_size - sizeof(CvMemBlock))/sizeof(*n) - 1;
74 CV_CALL( n = (CvWSNode*)cvMemStorageAlloc( storage, count*sizeof(*n) ));
75 for( i = 0; i < count-1; i++ )
76 n[i].next = n + i + 1;
86 cvWatershed( const CvArr* srcarr, CvArr* dstarr )
88 const int IN_QUEUE = -2;
91 CvMemStorage* storage = 0;
93 CV_FUNCNAME( "cvWatershed" );
100 CvWSNode* free_node = 0, *node;
110 // MAX(a,b) = b + MAX(a-b,0)
111 #define ws_max(a,b) ((b) + subs_tab[(a)-(b)+NQ])
112 // MIN(a,b) = a - MAX(a-b,0)
113 #define ws_min(a,b) ((a) - subs_tab[(a)-(b)+NQ])
115 #define ws_push(idx,mofs,iofs) \
118 CV_CALL( free_node = icvAllocWSNodes( storage ));\
120 free_node = free_node->next;\
122 node->mask_ofs = mofs; \
123 node->img_ofs = iofs; \
125 q[idx].last->next=node; \
127 q[idx].first = node; \
128 q[idx].last = node; \
131 #define ws_pop(idx,mofs,iofs) \
133 node = q[idx].first; \
134 q[idx].first = node->next; \
137 node->next = free_node; \
139 mofs = node->mask_ofs; \
140 iofs = node->img_ofs; \
143 #define c_diff(ptr1,ptr2,diff) \
145 db = abs((ptr1)[0] - (ptr2)[0]);\
146 dg = abs((ptr1)[1] - (ptr2)[1]);\
147 dr = abs((ptr1)[2] - (ptr2)[2]);\
148 diff = ws_max(db,dg); \
149 diff = ws_max(diff,dr); \
150 assert( 0 <= diff && diff <= 255 ); \
153 CV_CALL( src = cvGetMat( srcarr, &sstub ));
154 CV_CALL( dst = cvGetMat( dstarr, &dstub ));
156 if( CV_MAT_TYPE(src->type) != CV_8UC3 )
157 CV_ERROR( CV_StsUnsupportedFormat, "Only 8-bit, 3-channel input images are supported" );
159 if( CV_MAT_TYPE(dst->type) != CV_32SC1 )
160 CV_ERROR( CV_StsUnsupportedFormat,
161 "Only 32-bit, 1-channel output images are supported" );
163 if( !CV_ARE_SIZES_EQ( src, dst ))
164 CV_ERROR( CV_StsUnmatchedSizes, "The input and output images must have the same size" );
166 size = cvGetMatSize(src);
168 CV_CALL( storage = cvCreateMemStorage() );
172 mstep = dst->step / sizeof(mask[0]);
175 memset( q, 0, NQ*sizeof(q[0]) );
177 for( i = 0; i < 256; i++ )
179 for( i = 256; i <= 512; i++ )
180 subs_tab[i] = i - 256;
182 // draw a pixel-wide border of dummy "watershed" (i.e. boundary) pixels
183 for( j = 0; j < size.width; j++ )
184 mask[j] = mask[j + mstep*(size.height-1)] = WSHED;
186 // initial phase: put all the neighbor pixels of each marker to the ordered queue -
187 // determine the initial boundaries of the basins
188 for( i = 1; i < size.height-1; i++ )
190 img += istep; mask += mstep;
191 mask[0] = mask[size.width-1] = WSHED;
193 for( j = 1; j < size.width-1; j++ )
196 if( m[0] < 0 ) m[0] = 0;
197 if( m[0] == 0 && (m[-1] > 0 || m[1] > 0 || m[-mstep] > 0 || m[mstep] > 0) )
199 uchar* ptr = img + j*3;
202 c_diff( ptr, ptr - 3, idx );
205 c_diff( ptr, ptr + 3, t );
206 idx = ws_min( idx, t );
210 c_diff( ptr, ptr - istep, t );
211 idx = ws_min( idx, t );
215 c_diff( ptr, ptr + istep, t );
216 idx = ws_min( idx, t );
218 assert( 0 <= idx && idx <= 255 );
219 ws_push( idx, i*mstep + j, i*istep + j*3 );
225 // find the first non-empty queue
226 for( i = 0; i < NQ; i++ )
230 // if there is no markers, exit immediately
238 // recursively fill the basins
246 if( q[active_queue].first == 0 )
248 for( i = active_queue+1; i < NQ; i++ )
256 ws_pop( active_queue, mofs, iofs );
264 if( lab == 0 ) lab = t;
265 else if( t != lab ) lab = WSHED;
268 if( lab == 0 ) lab = t;
269 else if( t != lab ) lab = WSHED;
272 if( lab == 0 ) lab = t;
273 else if( t != lab ) lab = WSHED;
282 c_diff( ptr, ptr - 3, t );
283 ws_push( t, mofs - 1, iofs - 3 );
284 active_queue = ws_min( active_queue, t );
289 c_diff( ptr, ptr + 3, t );
290 ws_push( t, mofs + 1, iofs + 3 );
291 active_queue = ws_min( active_queue, t );
296 c_diff( ptr, ptr - istep, t );
297 ws_push( t, mofs - mstep, iofs - istep );
298 active_queue = ws_min( active_queue, t );
299 m[-mstep] = IN_QUEUE;
303 c_diff( ptr, ptr + 3, t );
304 ws_push( t, mofs + mstep, iofs + istep );
305 active_queue = ws_min( active_queue, t );
312 cvReleaseMemStorage( &storage );
316 /****************************************************************************************\
318 \****************************************************************************************/
321 cvPyrMeanShiftFiltering( const CvArr* srcarr, CvArr* dstarr,
322 double sp0, double sr, int max_level,
323 CvTermCriteria termcrit )
326 const int MAX_LEVELS = 8;
327 CvMat* src_pyramid[MAX_LEVELS+1];
328 CvMat* dst_pyramid[MAX_LEVELS+1];
331 //uchar* submask = 0;
333 #define cdiff(ofs0) (tab[c0-dptr[ofs0]+255] + \
334 tab[c1-dptr[(ofs0)+1]+255] + tab[c2-dptr[(ofs0)+2]+255] >= isr22)
336 memset( src_pyramid, 0, sizeof(src_pyramid) );
337 memset( dst_pyramid, 0, sizeof(dst_pyramid) );
339 CV_FUNCNAME( "cvPyrMeanShiftFiltering" );
343 double sr2 = sr * sr;
344 int isr2 = cvRound(sr2), isr22 = MAX(isr2,16);
349 CV_CALL( src0 = cvGetMat( srcarr, &sstub0 ));
350 CV_CALL( dst0 = cvGetMat( dstarr, &dstub0 ));
352 if( CV_MAT_TYPE(src0->type) != CV_8UC3 )
353 CV_ERROR( CV_StsUnsupportedFormat, "Only 8-bit, 3-channel images are supported" );
355 if( !CV_ARE_TYPES_EQ( src0, dst0 ))
356 CV_ERROR( CV_StsUnmatchedFormats, "The input and output images must have the same type" );
358 if( !CV_ARE_SIZES_EQ( src0, dst0 ))
359 CV_ERROR( CV_StsUnmatchedSizes, "The input and output images must have the same size" );
361 if( (unsigned)max_level > (unsigned)MAX_LEVELS )
362 CV_ERROR( CV_StsOutOfRange, "The number of pyramid levels is too large or negative" );
364 if( !(termcrit.type & CV_TERMCRIT_ITER) )
365 termcrit.max_iter = 5;
366 termcrit.max_iter = MAX(termcrit.max_iter,1);
367 termcrit.max_iter = MIN(termcrit.max_iter,100);
368 if( !(termcrit.type & CV_TERMCRIT_EPS) )
369 termcrit.epsilon = 1.f;
370 termcrit.epsilon = MAX(termcrit.epsilon, 0.f);
372 for( i = 0; i < 768; i++ )
373 tab[i] = (i - 255)*(i - 255);
375 // 1. construct pyramid
376 src_pyramid[0] = src0;
377 dst_pyramid[0] = dst0;
378 for( level = 1; level <= max_level; level++ )
380 CV_CALL( src_pyramid[level] = cvCreateMat( (src_pyramid[level-1]->rows+1)/2,
381 (src_pyramid[level-1]->cols+1)/2, src_pyramid[level-1]->type ));
382 CV_CALL( dst_pyramid[level] = cvCreateMat( src_pyramid[level]->rows,
383 src_pyramid[level]->cols, src_pyramid[level]->type ));
384 CV_CALL( cvPyrDown( src_pyramid[level-1], src_pyramid[level] ));
385 //CV_CALL( cvResize( src_pyramid[level-1], src_pyramid[level], CV_INTER_AREA ));
388 CV_CALL( mask0 = cvCreateMat( src0->rows, src0->cols, CV_8UC1 ));
389 //CV_CALL( submask = (uchar*)cvAlloc( (sp+2)*(sp+2) ));
391 // 2. apply meanshift, starting from the pyramid top (i.e. the smallest layer)
392 for( level = max_level; level >= 0; level-- )
394 CvMat* src = src_pyramid[level];
395 CvSize size = cvGetMatSize(src);
396 uchar* sptr = src->data.ptr;
397 int sstep = src->step;
402 float sp = (float)(sp0 / (1 << level));
405 if( level < max_level )
407 CvSize size1 = cvGetMatSize(dst_pyramid[level+1]);
408 CvMat m = cvMat( size.height, size.width, CV_8UC1, mask0->data.ptr );
409 dstep = dst_pyramid[level+1]->step;
410 dptr = dst_pyramid[level+1]->data.ptr + dstep + cn;
412 mask = m.data.ptr + mstep;
413 //cvResize( dst_pyramid[level+1], dst_pyramid[level], CV_INTER_CUBIC );
414 cvPyrUp( dst_pyramid[level+1], dst_pyramid[level] );
417 for( i = 1; i < size1.height-1; i++, dptr += dstep - (size1.width-2)*3, mask += mstep*2 )
419 for( j = 1; j < size1.width-1; j++, dptr += cn )
421 int c0 = dptr[0], c1 = dptr[1], c2 = dptr[2];
422 mask[j*2 - 1] = cdiff(-3) || cdiff(3) || cdiff(-dstep-3) || cdiff(-dstep) ||
423 cdiff(-dstep+3) || cdiff(dstep-3) || cdiff(dstep) || cdiff(dstep+3);
427 cvDilate( &m, &m, 0, 1 );
431 dptr = dst_pyramid[level]->data.ptr;
432 dstep = dst_pyramid[level]->step;
434 for( i = 0; i < size.height; i++, sptr += sstep - size.width*3,
435 dptr += dstep - size.width*3,
438 for( j = 0; j < size.width; j++, sptr += 3, dptr += 3 )
440 int x0 = j, y0 = i, x1, y1, iter;
443 if( mask && !mask[j] )
446 c0 = sptr[0], c1 = sptr[1], c2 = sptr[2];
448 // iterate meanshift procedure
449 for( iter = 0; iter < termcrit.max_iter; iter++ )
453 int minx, miny, maxx, maxy;
454 int s0 = 0, s1 = 0, s2 = 0, sx = 0, sy = 0;
458 //mean shift: process pixels in window (p-sigmaSp)x(p+sigmaSp)
459 minx = cvRound(x0 - sp); minx = MAX(minx, 0);
460 miny = cvRound(y0 - sp); miny = MAX(miny, 0);
461 maxx = cvRound(x0 + sp); maxx = MIN(maxx, size.width-1);
462 maxy = cvRound(y0 + sp); maxy = MIN(maxy, size.height-1);
463 ptr = sptr + (miny - i)*sstep + (minx - j)*3;
465 for( y = miny; y <= maxy; y++, ptr += sstep - (maxx-minx+1)*3 )
469 for( ; x + 3 <= maxx; x += 4, ptr += 12 )
471 int t0 = ptr[0], t1 = ptr[1], t2 = ptr[2];
472 if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
474 s0 += t0; s1 += t1; s2 += t2;
475 sx += x; row_count++;
477 t0 = ptr[3], t1 = ptr[4], t2 = ptr[5];
478 if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
480 s0 += t0; s1 += t1; s2 += t2;
481 sx += x+1; row_count++;
483 t0 = ptr[6], t1 = ptr[7], t2 = ptr[8];
484 if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
486 s0 += t0; s1 += t1; s2 += t2;
487 sx += x+2; row_count++;
489 t0 = ptr[9], t1 = ptr[10], t2 = ptr[11];
490 if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
492 s0 += t0; s1 += t1; s2 += t2;
493 sx += x+3; row_count++;
497 for( ; x <= maxx; x++, ptr += 3 )
499 int t0 = ptr[0], t1 = ptr[1], t2 = ptr[2];
500 if( tab[t0-c0+255] + tab[t1-c1+255] + tab[t2-c2+255] <= isr2 )
502 s0 += t0; s1 += t1; s2 += t2;
503 sx += x; row_count++;
514 x1 = cvRound(sx*icount);
515 y1 = cvRound(sy*icount);
516 s0 = cvRound(s0*icount);
517 s1 = cvRound(s1*icount);
518 s2 = cvRound(s2*icount);
520 stop_flag = x0 == x1 && y0 == y1 || abs(x1-x0) + abs(y1-y0) +
521 tab[s0 - c0 + 255] + tab[s1 - c1 + 255] +
522 tab[s2 - c2 + 255] <= termcrit.epsilon;
525 c0 = s0; c1 = s1; c2 = s2;
540 for( i = 1; i <= MAX_LEVELS; i++ )
542 cvReleaseMat( &src_pyramid[i] );
543 cvReleaseMat( &dst_pyramid[i] );
545 cvReleaseMat( &mask0 );