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.
45 icvSklansky_32s( CvPoint** array, int start, int end, int* stack, int nsign, int sign2 )
47 int incr = end > start ? 1 : -1;
48 /* prepare first triangle */
49 int pprev = start, pcur = pprev + incr, pnext = pcur + incr;
53 (array[start]->x == array[end]->x &&
54 array[start]->y == array[end]->y) )
64 end += incr; /* make end = afterend */
68 /* check the angle p1,p2,p3 */
69 int cury = array[pcur]->y;
70 int nexty = array[pnext]->y;
71 int by = nexty - cury;
73 if( CV_SIGN(by) != nsign )
75 int ax = array[pcur]->x - array[pprev]->x;
76 int bx = array[pnext]->x - array[pcur]->x;
77 int ay = cury - array[pprev]->y;
78 int convexity = ay*bx - ax*by;/* if >0 then convex angle */
80 if( CV_SIGN(convexity) == sign2 && (ax != 0 || ay != 0) )
85 stack[stacksize] = pnext;
99 stack[stacksize-2] = pnext;
101 pprev = stack[stacksize-4];
109 stack[stacksize-1] = pnext;
118 icvSklansky_32f( CvPoint2D32f** array, int start, int end, int* stack, int nsign, int sign2 )
120 int incr = end > start ? 1 : -1;
121 /* prepare first triangle */
122 int pprev = start, pcur = pprev + incr, pnext = pcur + incr;
126 (array[start]->x == array[end]->x &&
127 array[start]->y == array[end]->y) )
137 end += incr; /* make end = afterend */
139 while( pnext != end )
141 /* check the angle p1,p2,p3 */
142 float cury = array[pcur]->y;
143 float nexty = array[pnext]->y;
144 float by = nexty - cury;
146 if( CV_SIGN( by ) != nsign )
148 float ax = array[pcur]->x - array[pprev]->x;
149 float bx = array[pnext]->x - array[pcur]->x;
150 float ay = cury - array[pprev]->y;
151 float convexity = ay*bx - ax*by;/* if >0 then convex angle */
153 if( CV_SIGN( convexity ) == sign2 && (ax != 0 || ay != 0) )
158 stack[stacksize] = pnext;
173 stack[stacksize-2] = pnext;
175 pprev = stack[stacksize-4];
183 stack[stacksize-1] = pnext;
190 typedef int (*sklansky_func)( CvPoint** points, int start, int end,
191 int* stack, int sign, int sign2 );
193 #define cmp_pts( pt1, pt2 ) \
194 ((pt1)->x < (pt2)->x || (pt1)->x <= (pt2)->x && (pt1)->y < (pt2)->y)
195 static CV_IMPLEMENT_QSORT( icvSortPointsByPointers_32s, CvPoint*, cmp_pts )
196 static CV_IMPLEMENT_QSORT( icvSortPointsByPointers_32f, CvPoint2D32f*, cmp_pts )
199 icvCalcAndWritePtIndices( CvPoint** pointer, int* stack, int start, int end,
200 CvSeq* ptseq, CvSeqWriter* writer )
202 CV_FUNCNAME( "icvCalcAndWritePtIndices" );
206 int i, incr = start < end ? 1 : -1;
207 int idx, first_idx = ptseq->first->start_index;
209 for( i = start; i != end; i += incr )
211 CvPoint* ptr = (CvPoint*)pointer[stack[i]];
212 CvSeqBlock* block = ptseq->first;
213 while( (unsigned)(idx = (int)(ptr - (CvPoint*)block->data)) >= (unsigned)block->count )
216 if( block == ptseq->first )
217 CV_ERROR( CV_StsError, "Internal error" );
219 idx += block->start_index - first_idx;
220 CV_WRITE_SEQ_ELEM( idx, *writer );
228 cvConvexHull2( const CvArr* array, void* hull_storage,
229 int orientation, int return_points )
231 union { CvContour* c; CvSeq* s; } hull;
232 CvPoint** pointer = 0;
233 CvPoint2D32f** pointerf = 0;
236 CV_FUNCNAME( "cvConvexHull2" );
245 CvContour contour_header;
246 union { CvContour c; CvSeq s; } hull_header;
247 CvSeqBlock block, hullblock;
253 int i, miny_ind = 0, maxy_ind = 0, total;
256 sklansky_func sklansky;
258 if( CV_IS_SEQ( array ))
260 ptseq = (CvSeq*)array;
261 if( !CV_IS_SEQ_POINT_SET( ptseq ))
262 CV_ERROR( CV_StsBadArg, "Unsupported sequence type" );
263 if( hull_storage == 0 )
264 hull_storage = ptseq->storage;
268 CV_CALL( ptseq = cvPointSeqFromMat(
269 CV_SEQ_KIND_GENERIC, array, &contour_header, &block ));
272 if( CV_IS_STORAGE( hull_storage ))
276 CV_CALL( hullseq = cvCreateSeq(
277 CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE(ptseq)|
278 CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX,
279 sizeof(CvContour), sizeof(CvPoint),(CvMemStorage*)hull_storage ));
283 CV_CALL( hullseq = cvCreateSeq(
284 CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE_PPOINT|
285 CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX,
286 sizeof(CvContour), sizeof(CvPoint*), (CvMemStorage*)hull_storage ));
291 if( !CV_IS_MAT( hull_storage ))
292 CV_ERROR(CV_StsBadArg, "Destination must be valid memory storage or matrix");
294 mat = (CvMat*)hull_storage;
296 if( mat->cols != 1 && mat->rows != 1 || !CV_IS_MAT_CONT(mat->type))
297 CV_ERROR( CV_StsBadArg,
298 "The hull matrix should be continuous and have a single row or a single column" );
300 if( mat->cols + mat->rows - 1 < ptseq->total )
301 CV_ERROR( CV_StsBadSize, "The hull matrix size might be not enough to fit the hull" );
303 if( CV_MAT_TYPE(mat->type) != CV_SEQ_ELTYPE(ptseq) &&
304 CV_MAT_TYPE(mat->type) != CV_32SC1 )
305 CV_ERROR( CV_StsUnsupportedFormat,
306 "The hull matrix must have the same type as input or 32sC1 (integers)" );
308 CV_CALL( hullseq = cvMakeSeqHeaderForArray(
309 CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED,
310 sizeof(contour_header), CV_ELEM_SIZE(mat->type), mat->data.ptr,
311 mat->cols + mat->rows - 1, &hull_header.s, &hullblock ));
313 cvClearSeq( hullseq );
316 total = ptseq->total;
320 CV_ERROR( CV_StsBadSize,
321 "Point sequence can not be empty if the output is matrix" );
325 cvStartAppendToSeq( hullseq, &writer );
327 is_float = CV_SEQ_ELTYPE(ptseq) == CV_32FC2;
328 hulltype = CV_SEQ_ELTYPE(hullseq);
329 sklansky = !is_float ? (sklansky_func)icvSklansky_32s :
330 (sklansky_func)icvSklansky_32f;
332 CV_CALL( pointer = (CvPoint**)cvAlloc( ptseq->total*sizeof(pointer[0]) ));
333 CV_CALL( stack = (int*)cvAlloc( (ptseq->total + 2)*sizeof(stack[0]) ));
334 pointerf = (CvPoint2D32f**)pointer;
336 cvStartReadSeq( ptseq, &reader );
338 for( i = 0; i < total; i++ )
340 pointer[i] = (CvPoint*)reader.ptr;
341 CV_NEXT_SEQ_ELEM( ptseq->elem_size, reader );
344 // sort the point set by x-coordinate, find min and max y
347 icvSortPointsByPointers_32s( pointer, total, 0 );
348 for( i = 1; i < total; i++ )
350 int y = pointer[i]->y;
351 if( pointer[miny_ind]->y > y )
353 if( pointer[maxy_ind]->y < y )
359 icvSortPointsByPointers_32f( pointerf, total, 0 );
360 for( i = 1; i < total; i++ )
362 float y = pointerf[i]->y;
363 if( pointerf[miny_ind]->y > y )
365 if( pointerf[maxy_ind]->y < y )
370 if( pointer[0]->x == pointer[total-1]->x &&
371 pointer[0]->y == pointer[total-1]->y )
373 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
375 CV_WRITE_SEQ_ELEM( pointer[0], writer );
377 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
380 CV_WRITE_SEQ_ELEM( index, writer );
384 CvPoint pt = pointer[0][0];
385 CV_WRITE_SEQ_ELEM( pt, writer );
392 int *tl_stack = stack;
393 int tl_count = sklansky( pointer, 0, maxy_ind, tl_stack, -1, 1 );
394 int *tr_stack = tl_stack + tl_count;
395 int tr_count = sklansky( pointer, ptseq->total - 1, maxy_ind, tr_stack, -1, -1 );
397 /* gather upper part of convex hull to output */
398 if( orientation == CV_COUNTER_CLOCKWISE )
400 CV_SWAP( tl_stack, tr_stack, t_stack );
401 CV_SWAP( tl_count, tr_count, t_count );
404 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
406 for( i = 0; i < tl_count - 1; i++ )
407 CV_WRITE_SEQ_ELEM( pointer[tl_stack[i]], writer );
409 for( i = tr_count - 1; i > 0; i-- )
410 CV_WRITE_SEQ_ELEM( pointer[tr_stack[i]], writer );
412 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
414 CV_CALL( icvCalcAndWritePtIndices( pointer, tl_stack,
415 0, tl_count-1, ptseq, &writer ));
416 CV_CALL( icvCalcAndWritePtIndices( pointer, tr_stack,
417 tr_count-1, 0, ptseq, &writer ));
421 for( i = 0; i < tl_count - 1; i++ )
422 CV_WRITE_SEQ_ELEM( pointer[tl_stack[i]][0], writer );
424 for( i = tr_count - 1; i > 0; i-- )
425 CV_WRITE_SEQ_ELEM( pointer[tr_stack[i]][0], writer );
427 stop_idx = tr_count > 2 ? tr_stack[1] : tl_count > 2 ? tl_stack[tl_count - 2] : -1;
432 int *bl_stack = stack;
433 int bl_count = sklansky( pointer, 0, miny_ind, bl_stack, 1, -1 );
434 int *br_stack = stack + bl_count;
435 int br_count = sklansky( pointer, ptseq->total - 1, miny_ind, br_stack, 1, 1 );
437 if( orientation != CV_COUNTER_CLOCKWISE )
439 CV_SWAP( bl_stack, br_stack, t_stack );
440 CV_SWAP( bl_count, br_count, t_count );
445 int check_idx = bl_count > 2 ? bl_stack[1] :
446 bl_count + br_count > 2 ? br_stack[2-bl_count] : -1;
447 if( check_idx == stop_idx || check_idx >= 0 &&
448 pointer[check_idx]->x == pointer[stop_idx]->x &&
449 pointer[check_idx]->y == pointer[stop_idx]->y )
451 /* if all the points lie on the same line, then
452 the bottom part of the convex hull is the mirrored top part
453 (except the exteme points).*/
454 bl_count = MIN( bl_count, 2 );
455 br_count = MIN( br_count, 2 );
459 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
461 for( i = 0; i < bl_count - 1; i++ )
462 CV_WRITE_SEQ_ELEM( pointer[bl_stack[i]], writer );
464 for( i = br_count - 1; i > 0; i-- )
465 CV_WRITE_SEQ_ELEM( pointer[br_stack[i]], writer );
467 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
469 CV_CALL( icvCalcAndWritePtIndices( pointer, bl_stack,
470 0, bl_count-1, ptseq, &writer ));
471 CV_CALL( icvCalcAndWritePtIndices( pointer, br_stack,
472 br_count-1, 0, ptseq, &writer ));
476 for( i = 0; i < bl_count - 1; i++ )
477 CV_WRITE_SEQ_ELEM( pointer[bl_stack[i]][0], writer );
479 for( i = br_count - 1; i > 0; i-- )
480 CV_WRITE_SEQ_ELEM( pointer[br_stack[i]][0], writer );
485 CV_CALL( cvEndWriteSeq( &writer ));
489 if( mat->rows > mat->cols )
490 mat->rows = hullseq->total;
492 mat->cols = hullseq->total;
497 hull.c->rect = cvBoundingRect( ptseq,
498 ptseq->header_size < (int)sizeof(CvContour) ||
499 &ptseq->flags == &contour_header.flags );
501 /*if( ptseq != (CvSeq*)&contour_header )
502 hullseq->v_prev = ptseq;*/
514 /* contour must be a simple polygon */
515 /* it must have more than 3 points */
517 cvConvexityDefects( const CvArr* array,
518 const CvArr* hullarray,
519 CvMemStorage* storage )
523 CV_FUNCNAME( "cvConvexityDefects" );
530 /* is orientation of hull different from contour one */
533 CvContour contour_header;
534 union { CvContour c; CvSeq s; } hull_header;
535 CvSeqBlock block, hullblock;
536 CvSeq *ptseq = (CvSeq*)array, *hull = (CvSeq*)hullarray;
538 CvSeqReader hull_reader;
539 CvSeqReader ptseq_reader;
543 if( CV_IS_SEQ( ptseq ))
545 if( !CV_IS_SEQ_POINT_SET( ptseq ))
546 CV_ERROR( CV_StsUnsupportedFormat,
547 "Input sequence is not a sequence of points" );
549 storage = ptseq->storage;
553 CV_CALL( ptseq = cvPointSeqFromMat(
554 CV_SEQ_KIND_GENERIC, array, &contour_header, &block ));
557 if( CV_SEQ_ELTYPE( ptseq ) != CV_32SC2 )
558 CV_ERROR( CV_StsUnsupportedFormat,
559 "Floating-point coordinates are not supported here" );
561 if( CV_IS_SEQ( hull ))
563 int hulltype = CV_SEQ_ELTYPE( hull );
564 if( hulltype != CV_SEQ_ELTYPE_PPOINT && hulltype != CV_SEQ_ELTYPE_INDEX )
565 CV_ERROR( CV_StsUnsupportedFormat,
566 "Convex hull must represented as a sequence "
567 "of indices or sequence of pointers" );
569 storage = hull->storage;
573 CvMat* mat = (CvMat*)hull;
575 if( !CV_IS_MAT( hull ))
576 CV_ERROR(CV_StsBadArg, "Convex hull is neither sequence nor matrix");
578 if( mat->cols != 1 && mat->rows != 1 ||
579 !CV_IS_MAT_CONT(mat->type) || CV_MAT_TYPE(mat->type) != CV_32SC1 )
580 CV_ERROR( CV_StsBadArg,
581 "The matrix should be 1-dimensional and continuous array of int's" );
583 if( mat->cols + mat->rows - 1 > ptseq->total )
584 CV_ERROR( CV_StsBadSize, "Convex hull is larger than the point sequence" );
586 CV_CALL( hull = cvMakeSeqHeaderForArray(
587 CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED,
588 sizeof(CvContour), CV_ELEM_SIZE(mat->type), mat->data.ptr,
589 mat->cols + mat->rows - 1, &hull_header.s, &hullblock ));
592 is_index = CV_SEQ_ELTYPE(hull) == CV_SEQ_ELTYPE_INDEX;
595 CV_ERROR( CV_StsNullPtr, "NULL storage pointer" );
597 CV_CALL( defects = cvCreateSeq( CV_SEQ_KIND_GENERIC, sizeof(CvSeq),
598 sizeof(CvConvexityDefect), storage ));
600 if( ptseq->total < 4 || hull->total < 3)
602 //CV_ERROR( CV_StsBadSize,
603 // "point seq size must be >= 4, convex hull size must be >= 3" );
607 /* recognize co-orientation of ptseq and its hull */
610 int index1, index2, index3;
614 CvPoint* pos = *CV_SEQ_ELEM( hull, CvPoint*, 0 );
615 CV_CALL( index1 = cvSeqElemIdx( ptseq, pos ));
617 pos = *CV_SEQ_ELEM( hull, CvPoint*, 1 );
618 CV_CALL( index2 = cvSeqElemIdx( ptseq, pos ));
620 pos = *CV_SEQ_ELEM( hull, CvPoint*, 2 );
621 CV_CALL( index3 = cvSeqElemIdx( ptseq, pos ));
625 index1 = *CV_SEQ_ELEM( hull, int, 0 );
626 index2 = *CV_SEQ_ELEM( hull, int, 1 );
627 index3 = *CV_SEQ_ELEM( hull, int, 2 );
630 sign += (index2 > index1) ? 1 : 0;
631 sign += (index3 > index2) ? 1 : 0;
632 sign += (index1 > index3) ? 1 : 0;
634 rev_orientation = (sign == 2) ? 0 : 1;
637 cvStartReadSeq( ptseq, &ptseq_reader, 0 );
638 cvStartReadSeq( hull, &hull_reader, rev_orientation );
642 hull_cur = *(CvPoint**)hull_reader.prev_elem;
643 index = cvSeqElemIdx( ptseq, (char*)hull_cur, 0 );
647 index = *(int*)hull_reader.prev_elem;
648 hull_cur = CV_GET_SEQ_ELEM( CvPoint, ptseq, index );
650 cvSetSeqReaderPos( &ptseq_reader, index );
651 cvStartAppendToSeq( defects, &writer );
653 /* cycle through ptseq and hull with computing defects */
654 for( i = 0; i < hull->total; i++ )
656 CvConvexityDefect defect;
659 double depth = 0, scale;
663 hull_next = *(CvPoint**)hull_reader.ptr;
666 int t = *(int*)hull_reader.ptr;
667 hull_next = CV_GET_SEQ_ELEM( CvPoint, ptseq, t );
670 dx0 = (double)hull_next->x - (double)hull_cur->x;
671 dy0 = (double)hull_next->y - (double)hull_cur->y;
672 assert( dx0 != 0 || dy0 != 0 );
673 scale = 1./sqrt(dx0*dx0 + dy0*dy0);
675 defect.start = hull_cur;
676 defect.end = hull_next;
680 /* go through ptseq to achieve next hull point */
681 CV_NEXT_SEQ_ELEM( sizeof(CvPoint), ptseq_reader );
683 if( ptseq_reader.ptr == (schar*)hull_next )
687 CvPoint* cur = (CvPoint*)ptseq_reader.ptr;
689 /* compute distance from current point to hull edge */
690 double dx = (double)cur->x - (double)hull_cur->x;
691 double dy = (double)cur->y - (double)hull_cur->y;
694 double dist = fabs(-dy0*dx + dx0*dy) * scale;
699 defect.depth_point = cur;
700 defect.depth = (float)depth;
707 CV_WRITE_SEQ_ELEM( defect, writer );
710 hull_cur = hull_next;
711 if( rev_orientation )
713 CV_PREV_SEQ_ELEM( hull->elem_size, hull_reader );
717 CV_NEXT_SEQ_ELEM( hull->elem_size, hull_reader );
721 defects = cvEndWriteSeq( &writer );
730 cvCheckContourConvexity( const CvArr* array )
734 CV_FUNCNAME( "cvCheckContourConvexity" );
741 CvContour contour_header;
743 CvSeq* contour = (CvSeq*)array;
745 if( CV_IS_SEQ(contour) )
747 if( !CV_IS_SEQ_POLYGON(contour))
748 CV_ERROR( CV_StsUnsupportedFormat,
749 "Input sequence must be polygon (closed 2d curve)" );
753 CV_CALL( contour = cvPointSeqFromMat(
754 CV_SEQ_KIND_CURVE|CV_SEQ_FLAG_CLOSED, array, &contour_header, &block ));
757 if( contour->total == 0 )
760 cvStartReadSeq( contour, &reader, 0 );
764 if( CV_SEQ_ELTYPE( contour ) == CV_32SC2 )
766 CvPoint *prev_pt = (CvPoint*)reader.prev_elem;
767 CvPoint *cur_pt = (CvPoint*)reader.ptr;
769 int dx0 = cur_pt->x - prev_pt->x;
770 int dy0 = cur_pt->y - prev_pt->y;
772 for( i = 0; i < contour->total; i++ )
778 CV_NEXT_SEQ_ELEM( sizeof(CvPoint), reader );
780 cur_pt = (CvPoint *) reader.ptr;
782 dx = cur_pt->x - prev_pt->x;
783 dy = cur_pt->y - prev_pt->y;
787 /* find orientation */
788 /*orient = -dy0 * dx + dx0 * dy;
789 orientation |= (orient > 0) ? 1 : 2;
791 orientation |= (dydx0 > dxdy0) ? 1 : ((dydx0 < dxdy0) ? 2 : 3);
793 if( orientation == 3 )
805 assert( CV_SEQ_ELTYPE(contour) == CV_32FC2 );
807 CvPoint2D32f *prev_pt = (CvPoint2D32f*)reader.prev_elem;
808 CvPoint2D32f *cur_pt = (CvPoint2D32f*)reader.ptr;
810 float dx0 = cur_pt->x - prev_pt->x;
811 float dy0 = cur_pt->y - prev_pt->y;
813 for( i = 0; i < contour->total; i++ )
819 CV_NEXT_SEQ_ELEM( sizeof(CvPoint2D32f), reader );
821 cur_pt = (CvPoint2D32f*) reader.ptr;
823 dx = cur_pt->x - prev_pt->x;
824 dy = cur_pt->y - prev_pt->y;
828 /* find orientation */
829 /*orient = -dy0 * dx + dx0 * dy;
830 orientation |= (orient > 0) ? 1 : 2;
832 orientation |= (dydx0 > dxdy0) ? 1 : ((dydx0 < dxdy0) ? 2 : 3);
834 if( orientation == 3 )