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.
42 #include "precomp.hpp"
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 int i, incr = start < end ? 1 : -1;
203 int idx, first_idx = ptseq->first->start_index;
205 for( i = start; i != end; i += incr )
207 CvPoint* ptr = (CvPoint*)pointer[stack[i]];
208 CvSeqBlock* block = ptseq->first;
209 while( (unsigned)(idx = (int)(ptr - (CvPoint*)block->data)) >= (unsigned)block->count )
212 if( block == ptseq->first )
213 CV_Error( CV_StsError, "Internal error" );
215 idx += block->start_index - first_idx;
216 CV_WRITE_SEQ_ELEM( idx, *writer );
222 cvConvexHull2( const CvArr* array, void* hull_storage,
223 int orientation, int return_points )
225 union { CvContour* c; CvSeq* s; } hull;
226 cv::AutoBuffer<CvPoint*> _pointer;
228 CvPoint2D32f** pointerf = 0;
229 cv::AutoBuffer<int> _stack;
237 CvContour contour_header;
238 union { CvContour c; CvSeq s; } hull_header;
239 CvSeqBlock block, hullblock;
245 int i, miny_ind = 0, maxy_ind = 0, total;
248 sklansky_func sklansky;
250 if( CV_IS_SEQ( array ))
252 ptseq = (CvSeq*)array;
253 if( !CV_IS_SEQ_POINT_SET( ptseq ))
254 CV_Error( CV_StsBadArg, "Unsupported sequence type" );
255 if( hull_storage == 0 )
256 hull_storage = ptseq->storage;
260 ptseq = cvPointSeqFromMat( CV_SEQ_KIND_GENERIC, array, &contour_header, &block );
263 if( CV_IS_STORAGE( hull_storage ))
267 hullseq = cvCreateSeq(
268 CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE(ptseq)|
269 CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX,
270 sizeof(CvContour), sizeof(CvPoint),(CvMemStorage*)hull_storage );
274 hullseq = cvCreateSeq(
275 CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE_PPOINT|
276 CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX,
277 sizeof(CvContour), sizeof(CvPoint*), (CvMemStorage*)hull_storage );
282 if( !CV_IS_MAT( hull_storage ))
283 CV_Error(CV_StsBadArg, "Destination must be valid memory storage or matrix");
285 mat = (CvMat*)hull_storage;
287 if( (mat->cols != 1 && mat->rows != 1) || !CV_IS_MAT_CONT(mat->type))
288 CV_Error( CV_StsBadArg,
289 "The hull matrix should be continuous and have a single row or a single column" );
291 if( mat->cols + mat->rows - 1 < ptseq->total )
292 CV_Error( CV_StsBadSize, "The hull matrix size might be not enough to fit the hull" );
294 if( CV_MAT_TYPE(mat->type) != CV_SEQ_ELTYPE(ptseq) &&
295 CV_MAT_TYPE(mat->type) != CV_32SC1 )
296 CV_Error( CV_StsUnsupportedFormat,
297 "The hull matrix must have the same type as input or 32sC1 (integers)" );
299 hullseq = cvMakeSeqHeaderForArray(
300 CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED,
301 sizeof(contour_header), CV_ELEM_SIZE(mat->type), mat->data.ptr,
302 mat->cols + mat->rows - 1, &hull_header.s, &hullblock );
304 cvClearSeq( hullseq );
307 total = ptseq->total;
311 CV_Error( CV_StsBadSize,
312 "Point sequence can not be empty if the output is matrix" );
316 cvStartAppendToSeq( hullseq, &writer );
318 is_float = CV_SEQ_ELTYPE(ptseq) == CV_32FC2;
319 hulltype = CV_SEQ_ELTYPE(hullseq);
320 sklansky = !is_float ? (sklansky_func)icvSklansky_32s :
321 (sklansky_func)icvSklansky_32f;
323 _pointer.allocate( ptseq->total );
324 _stack.allocate( ptseq->total + 2);
326 pointerf = (CvPoint2D32f**)pointer;
329 cvStartReadSeq( ptseq, &reader );
331 for( i = 0; i < total; i++ )
333 pointer[i] = (CvPoint*)reader.ptr;
334 CV_NEXT_SEQ_ELEM( ptseq->elem_size, reader );
337 // sort the point set by x-coordinate, find min and max y
340 icvSortPointsByPointers_32s( pointer, total, 0 );
341 for( i = 1; i < total; i++ )
343 int y = pointer[i]->y;
344 if( pointer[miny_ind]->y > y )
346 if( pointer[maxy_ind]->y < y )
352 icvSortPointsByPointers_32f( pointerf, total, 0 );
353 for( i = 1; i < total; i++ )
355 float y = pointerf[i]->y;
356 if( pointerf[miny_ind]->y > y )
358 if( pointerf[maxy_ind]->y < y )
363 if( pointer[0]->x == pointer[total-1]->x &&
364 pointer[0]->y == pointer[total-1]->y )
366 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
368 CV_WRITE_SEQ_ELEM( pointer[0], writer );
370 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
373 CV_WRITE_SEQ_ELEM( index, writer );
377 CvPoint pt = pointer[0][0];
378 CV_WRITE_SEQ_ELEM( pt, writer );
385 int *tl_stack = stack;
386 int tl_count = sklansky( pointer, 0, maxy_ind, tl_stack, -1, 1 );
387 int *tr_stack = tl_stack + tl_count;
388 int tr_count = sklansky( pointer, ptseq->total - 1, maxy_ind, tr_stack, -1, -1 );
390 /* gather upper part of convex hull to output */
391 if( orientation == CV_COUNTER_CLOCKWISE )
393 CV_SWAP( tl_stack, tr_stack, t_stack );
394 CV_SWAP( tl_count, tr_count, t_count );
397 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
399 for( i = 0; i < tl_count - 1; i++ )
400 CV_WRITE_SEQ_ELEM( pointer[tl_stack[i]], writer );
402 for( i = tr_count - 1; i > 0; i-- )
403 CV_WRITE_SEQ_ELEM( pointer[tr_stack[i]], writer );
405 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
407 icvCalcAndWritePtIndices( pointer, tl_stack, 0, tl_count-1, ptseq, &writer );
408 icvCalcAndWritePtIndices( pointer, tr_stack, tr_count-1, 0, ptseq, &writer );
412 for( i = 0; i < tl_count - 1; i++ )
413 CV_WRITE_SEQ_ELEM( pointer[tl_stack[i]][0], writer );
415 for( i = tr_count - 1; i > 0; i-- )
416 CV_WRITE_SEQ_ELEM( pointer[tr_stack[i]][0], writer );
418 stop_idx = tr_count > 2 ? tr_stack[1] : tl_count > 2 ? tl_stack[tl_count - 2] : -1;
423 int *bl_stack = stack;
424 int bl_count = sklansky( pointer, 0, miny_ind, bl_stack, 1, -1 );
425 int *br_stack = stack + bl_count;
426 int br_count = sklansky( pointer, ptseq->total - 1, miny_ind, br_stack, 1, 1 );
428 if( orientation != CV_COUNTER_CLOCKWISE )
430 CV_SWAP( bl_stack, br_stack, t_stack );
431 CV_SWAP( bl_count, br_count, t_count );
436 int check_idx = bl_count > 2 ? bl_stack[1] :
437 bl_count + br_count > 2 ? br_stack[2-bl_count] : -1;
438 if( check_idx == stop_idx || (check_idx >= 0 &&
439 pointer[check_idx]->x == pointer[stop_idx]->x &&
440 pointer[check_idx]->y == pointer[stop_idx]->y) )
442 /* if all the points lie on the same line, then
443 the bottom part of the convex hull is the mirrored top part
444 (except the exteme points).*/
445 bl_count = MIN( bl_count, 2 );
446 br_count = MIN( br_count, 2 );
450 if( hulltype == CV_SEQ_ELTYPE_PPOINT )
452 for( i = 0; i < bl_count - 1; i++ )
453 CV_WRITE_SEQ_ELEM( pointer[bl_stack[i]], writer );
455 for( i = br_count - 1; i > 0; i-- )
456 CV_WRITE_SEQ_ELEM( pointer[br_stack[i]], writer );
458 else if( hulltype == CV_SEQ_ELTYPE_INDEX )
460 icvCalcAndWritePtIndices( pointer, bl_stack, 0, bl_count-1, ptseq, &writer );
461 icvCalcAndWritePtIndices( pointer, br_stack, br_count-1, 0, ptseq, &writer );
465 for( i = 0; i < bl_count - 1; i++ )
466 CV_WRITE_SEQ_ELEM( pointer[bl_stack[i]][0], writer );
468 for( i = br_count - 1; i > 0; i-- )
469 CV_WRITE_SEQ_ELEM( pointer[br_stack[i]][0], writer );
474 cvEndWriteSeq( &writer );
478 if( mat->rows > mat->cols )
479 mat->rows = hullseq->total;
481 mat->cols = hullseq->total;
486 hull.c->rect = cvBoundingRect( ptseq,
487 ptseq->header_size < (int)sizeof(CvContour) ||
488 &ptseq->flags == &contour_header.flags );
490 /*if( ptseq != (CvSeq*)&contour_header )
491 hullseq->v_prev = ptseq;*/
498 /* contour must be a simple polygon */
499 /* it must have more than 3 points */
500 CV_IMPL CvSeq* cvConvexityDefects( const CvArr* array,
501 const CvArr* hullarray,
502 CvMemStorage* storage )
509 /* is orientation of hull different from contour one */
512 CvContour contour_header;
513 union { CvContour c; CvSeq s; } hull_header;
514 CvSeqBlock block, hullblock;
515 CvSeq *ptseq = (CvSeq*)array, *hull = (CvSeq*)hullarray;
517 CvSeqReader hull_reader;
518 CvSeqReader ptseq_reader;
522 if( CV_IS_SEQ( ptseq ))
524 if( !CV_IS_SEQ_POINT_SET( ptseq ))
525 CV_Error( CV_StsUnsupportedFormat,
526 "Input sequence is not a sequence of points" );
528 storage = ptseq->storage;
532 ptseq = cvPointSeqFromMat( CV_SEQ_KIND_GENERIC, array, &contour_header, &block );
535 if( CV_SEQ_ELTYPE( ptseq ) != CV_32SC2 )
536 CV_Error( CV_StsUnsupportedFormat, "Floating-point coordinates are not supported here" );
538 if( CV_IS_SEQ( hull ))
540 int hulltype = CV_SEQ_ELTYPE( hull );
541 if( hulltype != CV_SEQ_ELTYPE_PPOINT && hulltype != CV_SEQ_ELTYPE_INDEX )
542 CV_Error( CV_StsUnsupportedFormat,
543 "Convex hull must represented as a sequence "
544 "of indices or sequence of pointers" );
546 storage = hull->storage;
550 CvMat* mat = (CvMat*)hull;
552 if( !CV_IS_MAT( hull ))
553 CV_Error(CV_StsBadArg, "Convex hull is neither sequence nor matrix");
555 if( (mat->cols != 1 && mat->rows != 1) ||
556 !CV_IS_MAT_CONT(mat->type) || CV_MAT_TYPE(mat->type) != CV_32SC1 )
557 CV_Error( CV_StsBadArg,
558 "The matrix should be 1-dimensional and continuous array of int's" );
560 if( mat->cols + mat->rows - 1 > ptseq->total )
561 CV_Error( CV_StsBadSize, "Convex hull is larger than the point sequence" );
563 hull = cvMakeSeqHeaderForArray(
564 CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED,
565 sizeof(CvContour), CV_ELEM_SIZE(mat->type), mat->data.ptr,
566 mat->cols + mat->rows - 1, &hull_header.s, &hullblock );
569 is_index = CV_SEQ_ELTYPE(hull) == CV_SEQ_ELTYPE_INDEX;
572 CV_Error( CV_StsNullPtr, "NULL storage pointer" );
574 defects = cvCreateSeq( CV_SEQ_KIND_GENERIC, sizeof(CvSeq), sizeof(CvConvexityDefect), storage );
576 if( ptseq->total < 4 || hull->total < 3)
578 //CV_ERROR( CV_StsBadSize,
579 // "point seq size must be >= 4, convex hull size must be >= 3" );
583 /* recognize co-orientation of ptseq and its hull */
586 int index1, index2, index3;
590 CvPoint* pos = *CV_SEQ_ELEM( hull, CvPoint*, 0 );
591 index1 = cvSeqElemIdx( ptseq, pos );
593 pos = *CV_SEQ_ELEM( hull, CvPoint*, 1 );
594 index2 = cvSeqElemIdx( ptseq, pos );
596 pos = *CV_SEQ_ELEM( hull, CvPoint*, 2 );
597 index3 = cvSeqElemIdx( ptseq, pos );
601 index1 = *CV_SEQ_ELEM( hull, int, 0 );
602 index2 = *CV_SEQ_ELEM( hull, int, 1 );
603 index3 = *CV_SEQ_ELEM( hull, int, 2 );
606 sign += (index2 > index1) ? 1 : 0;
607 sign += (index3 > index2) ? 1 : 0;
608 sign += (index1 > index3) ? 1 : 0;
610 rev_orientation = (sign == 2) ? 0 : 1;
613 cvStartReadSeq( ptseq, &ptseq_reader, 0 );
614 cvStartReadSeq( hull, &hull_reader, rev_orientation );
618 hull_cur = *(CvPoint**)hull_reader.prev_elem;
619 index = cvSeqElemIdx( ptseq, (char*)hull_cur, 0 );
623 index = *(int*)hull_reader.prev_elem;
624 hull_cur = CV_GET_SEQ_ELEM( CvPoint, ptseq, index );
626 cvSetSeqReaderPos( &ptseq_reader, index );
627 cvStartAppendToSeq( defects, &writer );
629 /* cycle through ptseq and hull with computing defects */
630 for( i = 0; i < hull->total; i++ )
632 CvConvexityDefect defect;
635 double depth = 0, scale;
639 hull_next = *(CvPoint**)hull_reader.ptr;
642 int t = *(int*)hull_reader.ptr;
643 hull_next = CV_GET_SEQ_ELEM( CvPoint, ptseq, t );
646 dx0 = (double)hull_next->x - (double)hull_cur->x;
647 dy0 = (double)hull_next->y - (double)hull_cur->y;
648 assert( dx0 != 0 || dy0 != 0 );
649 scale = 1./sqrt(dx0*dx0 + dy0*dy0);
651 defect.start = hull_cur;
652 defect.end = hull_next;
656 /* go through ptseq to achieve next hull point */
657 CV_NEXT_SEQ_ELEM( sizeof(CvPoint), ptseq_reader );
659 if( ptseq_reader.ptr == (schar*)hull_next )
663 CvPoint* cur = (CvPoint*)ptseq_reader.ptr;
665 /* compute distance from current point to hull edge */
666 double dx = (double)cur->x - (double)hull_cur->x;
667 double dy = (double)cur->y - (double)hull_cur->y;
670 double dist = fabs(-dy0*dx + dx0*dy) * scale;
675 defect.depth_point = cur;
676 defect.depth = (float)depth;
683 CV_WRITE_SEQ_ELEM( defect, writer );
686 hull_cur = hull_next;
687 if( rev_orientation )
689 CV_PREV_SEQ_ELEM( hull->elem_size, hull_reader );
693 CV_NEXT_SEQ_ELEM( hull->elem_size, hull_reader );
697 return cvEndWriteSeq( &writer );
702 cvCheckContourConvexity( const CvArr* array )
709 CvContour contour_header;
711 CvSeq* contour = (CvSeq*)array;
713 if( CV_IS_SEQ(contour) )
715 if( !CV_IS_SEQ_POINT_SET(contour))
716 CV_Error( CV_StsUnsupportedFormat,
717 "Input sequence must be polygon (closed 2d curve)" );
721 contour = cvPointSeqFromMat(CV_SEQ_KIND_CURVE|CV_SEQ_FLAG_CLOSED, array, &contour_header, &block );
724 if( contour->total == 0 )
727 cvStartReadSeq( contour, &reader, 0 );
730 if( CV_SEQ_ELTYPE( contour ) == CV_32SC2 )
732 CvPoint *prev_pt = (CvPoint*)reader.prev_elem;
733 CvPoint *cur_pt = (CvPoint*)reader.ptr;
735 int dx0 = cur_pt->x - prev_pt->x;
736 int dy0 = cur_pt->y - prev_pt->y;
738 for( i = 0; i < contour->total; i++ )
744 CV_NEXT_SEQ_ELEM( sizeof(CvPoint), reader );
746 cur_pt = (CvPoint *) reader.ptr;
748 dx = cur_pt->x - prev_pt->x;
749 dy = cur_pt->y - prev_pt->y;
753 /* find orientation */
754 /*orient = -dy0 * dx + dx0 * dy;
755 orientation |= (orient > 0) ? 1 : 2;
757 orientation |= (dydx0 > dxdy0) ? 1 : ((dydx0 < dxdy0) ? 2 : 3);
759 if( orientation == 3 )
771 CV_Assert( CV_SEQ_ELTYPE(contour) == CV_32FC2 );
773 CvPoint2D32f *prev_pt = (CvPoint2D32f*)reader.prev_elem;
774 CvPoint2D32f *cur_pt = (CvPoint2D32f*)reader.ptr;
776 float dx0 = cur_pt->x - prev_pt->x;
777 float dy0 = cur_pt->y - prev_pt->y;
779 for( i = 0; i < contour->total; i++ )
785 CV_NEXT_SEQ_ELEM( sizeof(CvPoint2D32f), reader );
787 cur_pt = (CvPoint2D32f*) reader.ptr;
789 dx = cur_pt->x - prev_pt->x;
790 dy = cur_pt->y - prev_pt->y;
794 /* find orientation */
795 /*orient = -dy0 * dx + dx0 * dy;
796 orientation |= (orient > 0) ? 1 : 2;
798 orientation |= (dydx0 > dxdy0) ? 1 : ((dydx0 < dxdy0) ? 2 : 3);
800 if( orientation == 3 )