diff --git a/modules/core/CMakeLists.txt b/modules/core/CMakeLists.txt index 0dab95798c..d8a2b7ae7e 100644 --- a/modules/core/CMakeLists.txt +++ b/modules/core/CMakeLists.txt @@ -176,10 +176,6 @@ ocv_target_link_libraries(${the_module} PRIVATE "${OPENCV_HAL_LINKER_LIBS}" ) -if(OPENCV_CORE_EXCLUDE_C_API) - ocv_target_compile_definitions(${the_module} PRIVATE "OPENCV_EXCLUDE_C_API=1") -endif() - if(OPENCV_DISABLE_THREAD_SUPPORT) ocv_target_compile_definitions(${the_module} PUBLIC "OPENCV_DISABLE_THREAD_SUPPORT=1") endif() diff --git a/modules/core/include/opencv2/core/core_c.h b/modules/core/include/opencv2/core/core_c.h deleted file mode 100644 index 50625b34d3..0000000000 --- a/modules/core/include/opencv2/core/core_c.h +++ /dev/null @@ -1,2263 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - - -#ifndef OPENCV_CORE_C_H -#define OPENCV_CORE_C_H - -#include "opencv2/core/types_c.h" - -#ifdef __cplusplus -/* disable MSVC warning C4190 / clang-cl -Wreturn-type-c-linkage: - 'function' has C-linkage specified, but returns UDT 'typename' - which is incompatible with C - - It is OK to disable it because we only extend few plain structures with - C++ constructors for simpler interoperability with C++ API of the library -*/ -# if defined(__clang__) - // handle clang on Linux and clang-cl (i. e. clang on Windows) first -# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" -# elif defined(_MSC_VER) - // then handle MSVC -# pragma warning(disable:4190) -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup core_c - @{ -*/ - -/****************************************************************************************\ -* Array allocation, deallocation, initialization and access to elements * -\****************************************************************************************/ - -/** `malloc` wrapper. - If there is no enough memory, the function - (as well as other OpenCV functions that call cvAlloc) - raises an error. */ -CVAPI(void*) cvAlloc( size_t size ); - -/** `free` wrapper. - Here and further all the memory releasing functions - (that all call cvFree) take double pointer in order to - to clear pointer to the data after releasing it. - Passing pointer to NULL pointer is Ok: nothing happens in this case -*/ -CVAPI(void) cvFree_( void* ptr ); -#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) - -/** @brief Creates an image header but does not allocate the image data. - -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) - */ -CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); - -/** @brief Initializes an image header that was previously allocated. - -The returned IplImage\* points to the initialized header. -@param image Image header to initialize -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) -@param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL -@param align Alignment for image rows, typically 4 or 8 bytes - */ -CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, - int channels, int origin CV_DEFAULT(0), - int align CV_DEFAULT(4)); - -/** @brief Creates an image header and allocates the image data. - -This function call is equivalent to the following code: -@code - header = cvCreateImageHeader(size, depth, channels); - cvCreateData(header); -@endcode -@param size Image width and height -@param depth Bit depth of image elements. See IplImage for valid depths. -@param channels Number of channels per pixel. See IplImage for details. This function only creates -images with interleaved channels. - */ -CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); - -/** @brief Deallocates an image header. - -This call is an analogue of : -@code - if(image ) - { - iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); - *image = 0; - } -@endcode -but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). -@param image Double pointer to the image header - */ -CVAPI(void) cvReleaseImageHeader( IplImage** image ); - -/** @brief Deallocates the image header and the image data. - -This call is a shortened form of : -@code - if(*image ) - { - cvReleaseData(*image); - cvReleaseImageHeader(image); - } -@endcode -@param image Double pointer to the image header -*/ -CVAPI(void) cvReleaseImage( IplImage** image ); - -/** Creates a copy of IPL image (widthStep may differ) */ -CVAPI(IplImage*) cvCloneImage( const IplImage* image ); - -/** @brief Sets the channel of interest in an IplImage. - -If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do -*not* support the COI setting, so to process an individual image/matrix channel one may copy (via -cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result -back (via cvCopy or cvMerge) if needed. -@param image A pointer to the image header -@param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, -etc. Note that the channel indices become 1-based. - */ -CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); - -/** @brief Returns the index of the channel of interest. - -Returns the channel of interest of in an IplImage. Returned values correspond to the coi in -cvSetImageCOI. -@param image A pointer to the image header - */ -CVAPI(int) cvGetImageCOI( const IplImage* image ); - -/** @brief Sets an image Region Of Interest (ROI) for a given rectangle. - -If the original image ROI was NULL and the rect is not the whole image, the ROI structure is -allocated. - -Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For -example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the -ROI, not the original image. -@param image A pointer to the image header -@param rect The ROI rectangle - */ -CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); - -/** @brief Resets the image ROI to include the entire image and releases the ROI structure. - -This produces a similar result to the following, but in addition it releases the ROI structure. : -@code - cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); - cvSetImageCOI(image, 0); -@endcode -@param image A pointer to the image header - */ -CVAPI(void) cvResetImageROI( IplImage* image ); - -/** @brief Returns the image ROI. - -If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. -@param image A pointer to the image header - */ -CVAPI(CvRect) cvGetImageROI( const IplImage* image ); - -/** @brief Creates a matrix header but does not allocate the matrix data. - -The function allocates a new matrix header and returns a pointer to it. The matrix data can then be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat - */ -CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); - -/** @brief Initializes a pre-allocated matrix header. - -This function is often used to process raw data with OpenCV matrix functions. For example, the -following code computes the matrix product of two matrices, stored as ordinary arrays: -@code - double a[] = { 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12 }; - - double b[] = { 1, 5, 9, - 2, 6, 10, - 3, 7, 11, - 4, 8, 12 }; - - double c[9]; - CvMat Ma, Mb, Mc ; - - cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); - cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); - cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); - - cvMatMulAdd(&Ma, &Mb, 0, &Mc); - // the c array now contains the product of a (3x4) and b (4x3) -@endcode -@param mat A pointer to the matrix header to be initialized -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat . -@param data Optional: data pointer assigned to the matrix header -@param step Optional: full row width in bytes of the assigned data. By default, the minimal -possible step is used which assumes there are no gaps between subsequent rows of the matrix. - */ -CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, - int type, void* data CV_DEFAULT(NULL), - int step CV_DEFAULT(CV_AUTOSTEP) ); - -/** @brief Creates a matrix header and allocates the matrix data. - -The function call is equivalent to the following code: -@code - CvMat* mat = cvCreateMatHeader(rows, cols, type); - cvCreateData(mat); -@endcode -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type The type of the matrix elements in the form -CV_\\C\ , where S=signed, U=unsigned, F=float. For -example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ -32SC2 means the elements are 32-bit signed and there are 2 channels. - */ -CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); - -/** @brief Deallocates a matrix. - -The function decrements the matrix data reference counter and deallocates matrix header. If the data -reference counter is 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the matrix - */ -CVAPI(void) cvReleaseMat( CvMat** mat ); - -/** @brief Decrements an array data reference counter. - -The function decrements the data reference counter in a CvMat or CvMatND if the reference counter - -pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current -implementation the reference counter is not NULL only if the data was allocated using the -cvCreateData function. The counter will be NULL in other cases such as: external data was assigned -to the header using cvSetData, header is part of a larger matrix or image, or the header was -converted from an image or n-dimensional matrix header. -@param arr Pointer to an array header - */ -CV_INLINE void cvDecRefData( CvArr* arr ) -{ - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } -} - -/** @brief Increments array data reference counter. - -The function increments CvMat or CvMatND data reference counter and returns the new counter value if -the reference counter pointer is not NULL, otherwise it returns zero. -@param arr Array header - */ -CV_INLINE int cvIncRefData( CvArr* arr ) -{ - int refcount = 0; - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - return refcount; -} - - -/** Creates an exact copy of the input matrix (except, may be, step value) */ -CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); - - -/** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. - -The function returns header, corresponding to a specified rectangle of the input array. In other - -words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is -taken into account by the function so the sub-array of ROI is actually extracted. -@param arr Input array -@param submat Pointer to the resultant sub-array header -@param rect Zero-based coordinates of the rectangle of interest - */ -CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); -#define cvGetSubArr cvGetSubRect - -/** @brief Returns array row or row span. - -The function returns the header, corresponding to a specified row/row span of the input array. -cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_row Zero-based index of the starting row (inclusive) of the span -@param end_row Zero-based index of the ending row (exclusive) of the span -@param delta_row Index step in the row span. That is, the function extracts every delta_row -th -row from start_row and up to (but not including) end_row . - */ -CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, - int start_row, int end_row, - int delta_row CV_DEFAULT(1)); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param row Zero-based index of the selected row -*/ -CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) -{ - return cvGetRows( arr, submat, row, row + 1, 1 ); -} - - -/** @brief Returns one of more array columns. - -The function returns the header, corresponding to a specified column span of the input array. That - -is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. -If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for -cvGetCols(arr, submat, col, col+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_col Zero-based index of the starting column (inclusive) of the span -@param end_col Zero-based index of the ending column (exclusive) of the span - */ -CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, - int start_col, int end_col ); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param col Zero-based index of the selected column -*/ -CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) -{ - return cvGetCols( arr, submat, col, col + 1 ); -} - -/** low-level scalar <-> raw data conversion functions */ -CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, - int extend_to_12 CV_DEFAULT(0) ); - -CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); - -/** @brief Creates a new matrix header but does not allocate the matrix data. - -The function allocates a header for a multi-dimensional dense array. The array data can further be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param dims Number of array dimensions -@param sizes Array of dimension sizes -@param type Type of array elements, see cvCreateMat - */ -CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); - -/** @brief Creates the header and allocates the data for a multi-dimensional dense array. - -This function call is equivalent to the following code: -@code - CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); - cvCreateData(mat); -@endcode -@param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be -changed at build time). -@param sizes Array of dimension sizes. -@param type Type of array elements, see cvCreateMat . - */ -CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); - -/** @brief Initializes a pre-allocated multi-dimensional array header. - -@param mat A pointer to the array header to be initialized -@param dims The number of array dimensions -@param sizes An array of dimension sizes -@param type Type of array elements, see cvCreateMat -@param data Optional data pointer assigned to the matrix header - */ -CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, - int type, void* data CV_DEFAULT(NULL) ); - -/** @brief Deallocates a multi-dimensional array. - -The function decrements the array data reference counter and releases the array header. If the -reference counter reaches 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the array - */ -CV_INLINE void cvReleaseMatND( CvMatND** mat ) -{ - cvReleaseMat( (CvMat**)mat ); -} - -/** Creates a copy of CvMatND (except, may be, steps) */ -CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); - -/** @brief Creates sparse array. - -The function allocates a multi-dimensional sparse array. Initially the array contain no elements, -that is PtrND and other related functions will return 0 for every index. -@param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is -practically unlimited (up to \f$2^{16}\f$ ). -@param sizes Array of dimension sizes -@param type Type of array elements. The same as for CvMat - */ -CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); - -/** @brief Deallocates sparse array. - -The function releases the sparse array and clears the array pointer upon exit. -@param mat Double pointer to the array - */ -CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); - -/** Creates a copy of CvSparseMat (except, may be, zero items) */ -CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); - -/** @brief Initializes sparse array elements iterator. - -The function initializes iterator of sparse array elements and returns pointer to the first element, -or NULL if the array is empty. -@param mat Input array -@param mat_iterator Initialized iterator - */ -CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, - CvSparseMatIterator* mat_iterator ); - -/** @brief Returns the next sparse matrix element - -The function moves iterator to the next sparse matrix element and returns pointer to it. In the -current version there is no any particular order of the elements, because they are stored in the -hash table. The sample below demonstrates how to iterate through the sparse matrix: -@code - // print all the non-zero sparse matrix elements and compute their sum - double sum = 0; - int i, dims = cvGetDims(sparsemat); - CvSparseMatIterator it; - CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); - - for(; node != 0; node = cvGetNextSparseNode(&it)) - { - int* idx = CV_NODE_IDX(array, node); - float val = *(float*)CV_NODE_VAL(array, node); - printf("M"); - for(i = 0; i < dims; i++ ) - printf("[%d]", idx[i]); - printf("=%g\n", val); - - sum += val; - } - - printf("nTotal sum = %g\n", sum); -@endcode -@param mat_iterator Sparse array iterator - */ -CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) -{ - if( mat_iterator->node->next ) - return mat_iterator->node = mat_iterator->node->next; - else - { - int idx; - for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) - { - CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; - if( node ) - { - mat_iterator->curidx = idx; - return mat_iterator->node = node; - } - } - return NULL; - } -} - - -/** @brief Returns type of array elements. - -The function returns type of the array elements. In the case of IplImage the type is converted to -CvMat-like representation. For example, if the image has been created as: -@code - IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); -@endcode -The code cvGetElemType(img) will return CV_8UC3. -@param arr Input array - */ -CVAPI(int) cvGetElemType( const CvArr* arr ); - -/** @brief Return number of array dimensions - -The function returns the array dimensionality and the array of dimension sizes. In the case of -IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the -following code calculates total number of array elements: -@code - int sizes[CV_MAX_DIM]; - int i, total = 1; - int dims = cvGetDims(arr, size); - for(i = 0; i < dims; i++ ) - total *= sizes[i]; -@endcode -@param arr Input array -@param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows -(height) goes first, number of columns (width) next. - */ -CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); - - -/** @brief Returns array size along the specified dimension. - -@param arr Input array -@param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of -columns; for images 0 means height, 1 means width) - */ -CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); - - -/** @brief Return pointer to a particular array element. - -The functions return a pointer to a specific array element. Number of array dimension should match -to the number of indices passed to the function except for cvPtr1D function that can be used for -sequential access to 1D, 2D or nD dense arrays. - -The functions can be used for sparse arrays as well - if the requested node does not exist they -create it and set it to zero. - -All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet -, cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param type Optional output parameter: type of matrix elements - */ -CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); -/** @overload */ -CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); -/** @overload */ -CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, - int* type CV_DEFAULT(NULL)); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param type Optional output parameter: type of matrix elements -@param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter -means that the requested element is created if it does not exist already. -@param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, -the function does not recalculate the node hash value, but takes it from the specified location. -It is useful for speeding up pair-wise operations (TODO: provide an example) -*/ -CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), - int create_node CV_DEFAULT(1), - unsigned* precalc_hashval CV_DEFAULT(NULL)); - -/** @brief Return a specific array element. - -The functions return a specific array element. In the case of a sparse array the functions return 0 -if the requested node does not exist (no new node is created by the functions). -@param arr Input array -@param idx0 The first zero-based component of the element index - */ -CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array -@param idx Array of the element indices -*/ -CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); - -/** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. - -Returns a specific element of a single-channel array. If the array has multiple channels, a runtime -error is raised. Note that Get?D functions can be used safely for both single-channel and -multiple-channel arrays though they are a bit slower. - -In the case of a sparse array the functions return 0 if the requested node does not exist (no new -node is created by the functions). -@param arr Input array. Must have a single channel. -@param idx0 The first zero-based component of the element index - */ -CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array. Must have a single channel. -@param idx Array of the element indices -*/ -CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); - -/** @brief Change the particular array element. - -The functions assign the new value to a particular array element. In the case of a sparse array the -functions create the node if it does not exist yet. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); - -/** @brief Change a specific array element. - -The functions assign a new value to a specific element of a single-channel array. If the array has -multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for -both single-channel and multiple-channel arrays, though they are a bit slower. - -In the case of a sparse array the functions create the node if it does not yet exist. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); -/** @overload */ -CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); -/** @overload */ -CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, - int idx1, int idx2, double value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); - -/** clears element of ND dense array, - in case of sparse arrays it deletes the specified node */ -CVAPI(void) cvClearND( CvArr* arr, const int* idx ); - -/** @brief Returns matrix header for arbitrary array. - -The function returns a matrix header for the input array that can be a matrix - CvMat, an image - -IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if -allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of -IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI -and returns &header. Because COI is not supported by CvMat, it is returned separately. - -The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same -code. Input array must have non-zero data pointer, otherwise the function will report an error. - -@note If the input array is IplImage with planar data layout and COI set, the function returns the -pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures -with planar data layout, even though OpenCV does not support such images. -@param arr Input array -@param header Pointer to CvMat structure used as a temporary buffer -@param coi Optional output parameter for storing COI -@param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and -returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or -more than 2 dimensions). The CvMatND array must be continuous. -@sa cvGetImage, cvarrToMat. - */ -CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, - int* coi CV_DEFAULT(NULL), - int allowND CV_DEFAULT(0)); - -/** @brief Returns image header for arbitrary array. - -The function returns the image header for the input array that can be a matrix (CvMat) or image -(IplImage). In the case of an image the function simply returns the input pointer. In the case of -CvMat it initializes an image_header structure with the parameters of the input matrix. Note that -if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using -this function, we will get different headers if the ROI is set in the original image. -@param arr Input array -@param image_header Pointer to IplImage structure used as a temporary buffer - */ -CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); - - -#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ - cvReshapeMatND( (arr), sizeof(*(header)), (header), \ - (new_cn), (new_dims), (new_sizes)) - -/** @brief Changes shape of matrix/image without copying data. - -The function initializes the CvMat header so that it points to the same data as the original array -but has a different shape - different number of channels, different number of rows, or both. - -The following example code creates one image buffer and two image headers, the first is for a -320x240x3 image and the second is for a 960x240x1 image: -@code - IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); - CvMat gray_mat_hdr; - IplImage gray_img_hdr, *gray_img; - cvReshape(color_img, &gray_mat_hdr, 1); - gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); -@endcode -And the next example converts a 3x3 matrix to a single 1x9 vector: -@code - CvMat* mat = cvCreateMat(3, 3, CV_32F); - CvMat row_header, *row; - row = cvReshape(mat, &row_header, 0, 1); -@endcode -@param arr Input array -@param header Output header to be filled -@param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains -unchanged. -@param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains -unchanged unless it needs to be changed according to new_cn value. -*/ -CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, - int new_cn, int new_rows CV_DEFAULT(0) ); - -/** @brief Allocates array data - -The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of -matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless -CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used -to allocate the data. -@param arr Array header - */ -CVAPI(void) cvCreateData( CvArr* arr ); - -/** @brief Releases array data. - -The function releases the array data. In the case of CvMat or CvMatND it simply calls -cvDecRefData(), that is the function can not deallocate external data. See also the note to -cvCreateData . -@param arr Array header - */ -CVAPI(void) cvReleaseData( CvArr* arr ); - -/** @brief Assigns user data to the array header. - -The function assigns user data to the array header. Header should be initialized before using -cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, -cvInitImageHeader or cvInitMatNDHeader. -@param arr Array header -@param data User data -@param step Full row length in bytes - */ -CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); - -/** @brief Retrieves low-level information about the array. - -The function fills output variables with low-level information about the array data. All output - -parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with -ROI set, the parameters of ROI are returned. - -The following example shows how to get access to array elements. It computes absolute values of the -array elements : -@code - float* data; - int step; - CvSize size; - - cvGetRawData(array, (uchar**)&data, &step, &size); - step /= sizeof(data[0]); - - for(int y = 0; y < size.height; y++, data += step ) - for(int x = 0; x < size.width; x++ ) - data[x] = (float)fabs(data[x]); -@endcode -@param arr Array header -@param data Output pointer to the whole image origin or ROI origin if ROI is set -@param step Output full row length in bytes -@param roi_size Output ROI size - */ -CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, - int* step CV_DEFAULT(NULL), - CvSize* roi_size CV_DEFAULT(NULL)); - -/** @brief Returns size of matrix or image ROI. - -The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the -input matrix or image. In the case of image the size of ROI is returned. -@param arr array header - */ -CVAPI(CvSize) cvGetSize( const CvArr* arr ); - -/** @brief Copies one array to another. - -The function copies selected elements from an input array to an output array: - -\f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] - -If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays -must have the same type, the same number of dimensions, and the same size. The function can also -copy sparse arrays (mask is not supported in this case). -@param src The source array -@param dst The destination array -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination array -to be changed - */ -CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Sets every element of an array to a given value. - -The function copies the scalar value to every selected element of the destination array: -\f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] -If array arr is of IplImage type, then is ROI used, but COI must not be set. -@param arr The destination array -@param value Fill value -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination -array to be changed - */ -CVAPI(void) cvSet( CvArr* arr, CvScalar value, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Clears the array. - -The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), -cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the -elements are removed. -@param arr Array to be cleared - */ -CVAPI(void) cvSetZero( CvArr* arr ); -#define cvZero cvSetZero - - -/** Splits a multi-channel array into the set of single-channel arrays or - extracts particular [color] plane */ -CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, - CvArr* dst2, CvArr* dst3 ); - -/** Merges a set of single-channel arrays into the single multi-channel array - or inserts one particular [color] plane to the array */ -CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, - const CvArr* src2, const CvArr* src3, - CvArr* dst ); - -/** Copies several channels from input arrays to - certain channels of output arrays */ -CVAPI(void) cvMixChannels( const CvArr** src, int src_count, - CvArr** dst, int dst_count, - const int* from_to, int pair_count ); - -/** @brief Converts one array to another with optional linear transformation. - -The function has several different purposes, and thus has several different names. It copies one -array to another with optional scaling, which is performed first, and/or optional type conversion, -performed after: - -\f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] - -All the channels of multi-channel arrays are processed independently. - -The type of conversion is done with rounding and saturation, that is if the result of scaling + -conversion can not be represented exactly by a value of the destination array element type, it is -set to the nearest representable value on the real axis. -@param src Source array -@param dst Destination array -@param scale Scale factor -@param shift Value added to the scaled source array elements - */ -CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScale cvConvertScale -#define cvScale cvConvertScale -#define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) - - -/** Performs linear transformation on every source array element, - stores absolute value of the result: - dst(x,y,c) = abs(scale*src(x,y,c)+shift). - destination array must have 8u type. - In other cases one may use cvConvertScale + cvAbsDiffS */ -CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScaleAbs cvConvertScaleAbs - - -/** checks termination criteria validity and - sets eps to default_eps (if it is not set), - max_iter to default_max_iters (if it is not set) -*/ -CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, - double default_eps, - int default_max_iters ); - -/****************************************************************************************\ -* Arithmetic, logic and comparison operations * -\****************************************************************************************/ - -/** dst(mask) = src1(mask) + src2(mask) */ -CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) + value */ -CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src1(mask) - src2(mask) */ -CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) - value = src(mask) + (-value) */ -CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)) -{ - cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), - dst, mask ); -} - -/** dst(mask) = value - src(mask) */ -CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) * src2(idx) * scale - (scaled element-wise multiplication of 2 arrays) */ -CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1) ); - -/** element-wise division/inversion with scaling: - dst(idx) = src1(idx) * scale / src2(idx) - or dst(idx) = scale / src2(idx) if src1 == 0 */ -CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1)); - -/** dst = src1 * scale + src2 */ -CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, - const CvArr* src2, CvArr* dst ); - -/** @brief Calculates the dot product of two arrays in Euclidean metrics. - -The function calculates and returns the Euclidean dot product of two arrays. - -\f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] - -In the case of multiple channel arrays, the results for all channels are accumulated. In particular, -cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can -process multi-dimensional arrays, row by row, layer by layer, and so on. -@param src1 The first source array -@param src2 The second source array - */ -CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); - -/** dst(idx) = src1(idx) & src2(idx) */ -CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) & value */ -CVAPI(void) cvAndS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) | src2(idx) */ -CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) | value */ -CVAPI(void) cvOrS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) ^ src2(idx) */ -CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) ^ value */ -CVAPI(void) cvXorS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = ~src(idx) */ -CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); - -#define CV_CMP_EQ 0 -#define CV_CMP_GT 1 -#define CV_CMP_GE 2 -#define CV_CMP_LT 3 -#define CV_CMP_LE 4 -#define CV_CMP_NE 5 - -/** The comparison operation support single-channel arrays only. - Destination image should be 8uC1 or 8sC1 */ - -/** dst(idx) = src1(idx) _cmp_op_ value */ -CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); - -/****************************************************************************************\ -* Math operations * -\****************************************************************************************/ - -/** Does powering: dst(idx) = src(idx)^power */ -CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); - -/** Does exponention: dst(idx) = exp(src(idx)). - Overflow is not handled yet. Underflow is handled. - Maximal relative error is ~7e-6 for single-precision input */ -CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); - - -#define CV_CHECK_RANGE 1 -#define CV_CHECK_QUIET 2 -/** Checks array values for NaNs, Infs or simply for too large numbers - (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, - no runtime errors is raised (function returns zero value in case of "bad" values). - */ -CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), - double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); -#define cvCheckArray cvCheckArr - -#define CV_RAND_UNI 0 -#define CV_RAND_NORMAL 1 - -#define CV_SORT_EVERY_ROW 0 -#define CV_SORT_EVERY_COLUMN 1 -#define CV_SORT_ASCENDING 0 -#define CV_SORT_DESCENDING 16 - -/** Finds all real and complex roots of a polynomial equation */ -CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, - int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); - -/****************************************************************************************\ -* Matrix operations * -\****************************************************************************************/ - -/** @brief Calculates the cross product of two 3D vectors. - -The function calculates the cross product of two 3D vectors: -\f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] -or: -\f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] -@param src1 The first source vector -@param src2 The second source vector -@param dst The destination vector - */ -CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** Matrix transform: dst = A*B + C, C is optional */ -#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) -#define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) - -#define CV_GEMM_A_T 1 -#define CV_GEMM_B_T 2 -#define CV_GEMM_C_T 4 -/** Extended matrix transform: - dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ -CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, - const CvArr* src3, double beta, CvArr* dst, - int tABC CV_DEFAULT(0)); -#define cvMatMulAddEx cvGEMM - -/** Transforms each element of source array and stores - resultant vectors in destination array */ -CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, - const CvMat* transmat, - const CvMat* shiftvec CV_DEFAULT(NULL)); -#define cvMatMulAddS cvTransform - -/** Does perspective transform on every element of input array */ -CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, - const CvMat* mat ); - -/** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ -CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, - const CvArr* delta CV_DEFAULT(NULL), - double scale CV_DEFAULT(1.) ); - -/** Transposes matrix. Square matrices can be transposed in-place */ -CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); -#define cvT cvTranspose - -/** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ -CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); - -/** Mirror array data around horizontal (flip=0), - vertical (flip=1) or both(flip=-1) axises: - cvFlip(src) flips images vertically and sequences horizontally (inplace) */ -CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), - int flip_mode CV_DEFAULT(0)); -#define cvMirror cvFlip - - -#define CV_SVD_MODIFY_A 1 -#define CV_SVD_U_T 2 -#define CV_SVD_V_T 4 - -/** Performs Singular Value Decomposition of a matrix */ -CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), - CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); - -/** Performs Singular Value Back Substitution (solves A*X = B): - flags must be the same as in cvSVD */ -CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, - const CvArr* V, const CvArr* B, - CvArr* X, int flags ); - -#define CV_LU 0 -#define CV_SVD 1 -#define CV_SVD_SYM 2 -#define CV_CHOLESKY 3 -#define CV_QR 4 -#define CV_NORMAL 16 - -/** Inverts matrix */ -CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, - int method CV_DEFAULT(CV_LU)); -#define cvInv cvInvert - -/** Solves linear system (src1)*(dst) = (src2) - (returns 0 if src1 is a singular and CV_LU method is used) */ -CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, - int method CV_DEFAULT(CV_LU)); - -/** Calculates determinant of input matrix */ -CVAPI(double) cvDet( const CvArr* mat ); - -/** Calculates trace of the matrix (sum of elements on the main diagonal) */ -CVAPI(CvScalar) cvTrace( const CvArr* mat ); - -/** Finds eigen values and vectors of a symmetric matrix */ -CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, - double eps CV_DEFAULT(0), - int lowindex CV_DEFAULT(-1), - int highindex CV_DEFAULT(-1)); - -///* Finds selected eigen values and vectors of a symmetric matrix */ -//CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, -// int lowindex, int highindex ); - -/** Makes an identity matrix (mat_ij = i == j) */ -CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); - -/** Fills matrix with given range of numbers */ -CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); - -/** @anchor core_c_CovarFlags -@name Flags for cvCalcCovarMatrix -@see cvCalcCovarMatrix - @{ -*/ - -/** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ -#define CV_COVAR_SCRAMBLED 0 - -/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ -#define CV_COVAR_NORMAL 1 - -/** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead - (useful for calculating covariance matrix by parts) */ -#define CV_COVAR_USE_AVG 2 - -/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ -#define CV_COVAR_SCALE 4 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ -#define CV_COVAR_ROWS 8 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ -#define CV_COVAR_COLS 16 - -/** @} */ - -/** Calculates covariation matrix for a set of vectors -@see @ref core_c_CovarFlags "flags" -*/ -CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, - CvArr* cov_mat, CvArr* avg, int flags ); - -#define CV_PCA_DATA_AS_ROW 0 -#define CV_PCA_DATA_AS_COL 1 -#define CV_PCA_USE_AVG 2 -CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, - CvArr* eigenvals, CvArr* eigenvects, int flags ); - -CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -/** Calculates Mahalanobis(weighted) distance */ -CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); -#define cvMahalonobis cvMahalanobis - -/****************************************************************************************\ -* Array Statistics * -\****************************************************************************************/ - -/** Finds sum of array elements */ -CVAPI(CvScalar) cvSum( const CvArr* arr ); - -/** Calculates number of non-zero pixels */ -CVAPI(int) cvCountNonZero( const CvArr* arr ); - -/** Calculates mean value of array elements */ -CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); - -/** Calculates mean and standard deviation of pixel values */ -CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** Finds global minimum, maximum and their positions */ -CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, - CvPoint* min_loc CV_DEFAULT(NULL), - CvPoint* max_loc CV_DEFAULT(NULL), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_NormFlags - @name Flags for cvNorm and cvNormalize - @{ -*/ -#define CV_C 1 -#define CV_L1 2 -#define CV_L2 4 -#define CV_NORM_MASK 7 -#define CV_RELATIVE 8 -#define CV_DIFF 16 -#define CV_MINMAX 32 - -#define CV_DIFF_C (CV_DIFF | CV_C) -#define CV_DIFF_L1 (CV_DIFF | CV_L1) -#define CV_DIFF_L2 (CV_DIFF | CV_L2) -#define CV_RELATIVE_C (CV_RELATIVE | CV_C) -#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) -#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) -/** @} */ - -/** Finds norm, difference norm or relative difference norm for an array (or two arrays) -@see ref core_c_NormFlags "flags" -*/ -CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @see ref core_c_NormFlags "flags" */ -CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, - double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_ReduceFlags - @name Flags for cvReduce - @{ -*/ -#define CV_REDUCE_SUM 0 -#define CV_REDUCE_AVG 1 -#define CV_REDUCE_MAX 2 -#define CV_REDUCE_MIN 3 -/** @} */ - -/** @see @ref core_c_ReduceFlags "flags" */ -CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), - int op CV_DEFAULT(CV_REDUCE_SUM) ); - -/****************************************************************************************\ -* Discrete Linear Transforms and Related Functions * -\****************************************************************************************/ - -/** @anchor core_c_DftFlags - @name Flags for cvDFT, cvDCT and cvMulSpectrums - @{ - */ -#define CV_DXT_FORWARD 0 -#define CV_DXT_INVERSE 1 -#define CV_DXT_SCALE 2 /**< divide result by size of array */ -#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) -#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE -#define CV_DXT_ROWS 4 /**< transform each row individually */ -#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ -/** @} */ - -/** Discrete Fourier Transform: - complex->complex, - real->ccs (forward), - ccs->real (inverse) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, - int nonzero_rows CV_DEFAULT(0) ); -#define cvFFT cvDFT - -/** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, - CvArr* dst, int flags ); - -/** Finds optimal DFT vector size >= size0 */ -CVAPI(int) cvGetOptimalDFTSize( int size0 ); - -/** Discrete Cosine Transform -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); - -/****************************************************************************************\ -* Dynamic data structures * -\****************************************************************************************/ - -/** Calculates length of sequence slice (with support of negative indices). */ -CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); - - -/** Creates new memory storage. - block_size == 0 means that default, - somewhat optimal size, is used (currently, it is 64K) */ -CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); - - -/** Creates a memory storage that will borrow memory blocks from parent storage */ -CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); - - -/** Releases memory storage. All the children of a parent must be released before - the parent. A child storage returns all the blocks to parent when it is released */ -CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); - - -/** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) - to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... - do not free any memory. - A child storage returns all the blocks to the parent when it is cleared */ -CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); - -/** Remember a storage "free memory" position */ -CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Restore a storage "free memory" position */ -CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Allocates continuous buffer of the specified size in the storage */ -CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); - -/** Allocates string in memory storage */ -//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, -// int len CV_DEFAULT(-1) ); - -/** Creates new empty sequence that will reside in the specified storage */ -CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, - size_t elem_size, CvMemStorage* storage ); - -/** Changes default size (granularity) of sequence blocks. - The default size is ~1Kbyte */ -CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); - - -/** Adds new element to the end of sequence. Returns pointer to the element */ -CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Adds new element to the beginning of sequence. Returns pointer to it */ -CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Removes the last element from sequence and optionally saves it */ -CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -/** Removes the first element from sequence and optioanally saves it */ -CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -#define CV_FRONT 1 -#define CV_BACK 0 -/** Adds several new elements to the end of sequence */ -CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Removes several elements from the end of sequence and optionally saves them */ -CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Inserts a new element in the middle of sequence. - cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ -CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, - const void* element CV_DEFAULT(NULL)); - -/** Removes specified sequence element */ -CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); - - -/** Removes all the elements from the sequence. The freed memory - can be reused later only by the same sequence unless cvClearMemStorage - or cvRestoreMemStoragePos is called */ -CVAPI(void) cvClearSeq( CvSeq* seq ); - - -/** Retrieves pointer to specified sequence element. - Negative indices are supported and mean counting from the end - (e.g -1 means the last sequence element) */ -CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); - -/** Calculates index of the specified sequence element. - Returns -1 if element does not belong to the sequence */ -CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, - CvSeqBlock** block CV_DEFAULT(NULL) ); - -/** Initializes sequence writer. The new elements will be added to the end of sequence */ -CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); - - -/** Combination of cvCreateSeq and cvStartAppendToSeq */ -CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, - int elem_size, CvMemStorage* storage, - CvSeqWriter* writer ); - -/** Closes sequence writer, updates sequence header and returns pointer - to the resultant sequence - (which may be useful if the sequence was created using cvStartWriteSeq)) -*/ -CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); - - -/** Updates sequence header. May be useful to get access to some of previously - written elements via cvGetSeqElem or sequence reader */ -CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); - - -/** Initializes sequence reader. - The sequence can be read in forward or backward direction */ -CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, - int reverse CV_DEFAULT(0) ); - - -/** Returns current sequence reader position (currently observed sequence element) */ -CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); - - -/** Changes sequence reader position. It may seek to an absolute or - to relative to the current position */ -CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, - int is_relative CV_DEFAULT(0)); - -/** Copies sequence content to a continuous piece of memory */ -CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, - CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); - -/** Creates sequence header for array. - After that all the operations on sequences that do not alter the content - can be applied to the resultant sequence */ -CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, - int elem_size, void* elements, int total, - CvSeq* seq, CvSeqBlock* block ); - -/** Extracts sequence slice (with or without copying sequence elements) */ -CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, - CvMemStorage* storage CV_DEFAULT(NULL), - int copy_data CV_DEFAULT(0)); - -CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) -{ - return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); -} - -/** Removes sequence slice */ -CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); - -/** Inserts a sequence or array into another sequence */ -CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -/** a < b ? -1 : a > b ? 1 : 0 */ -typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); - -/** Sorts sequence in-place given element comparison function */ -CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); - -/** Finds element in a [sorted] sequence */ -CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, - int is_sorted, int* elem_idx, - void* userdata CV_DEFAULT(NULL) ); - -/** Reverses order of sequence elements in-place */ -CVAPI(void) cvSeqInvert( CvSeq* seq ); - -/** Splits sequence into one or more equivalence classes using the specified criteria */ -CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, - CvSeq** labels, CvCmpFunc is_equal, void* userdata ); - -/************ Internal sequence functions ************/ -CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); -CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); - - -/** Creates a new set */ -CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, - int elem_size, CvMemStorage* storage ); - -/** Adds new element to the set and returns pointer to it */ -CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), - CvSetElem** inserted_elem CV_DEFAULT(NULL) ); - -/** Fast variant of cvSetAdd */ -CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) -{ - CvSetElem* elem = set_header->free_elems; - if( elem ) - { - set_header->free_elems = elem->next_free; - elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; - set_header->active_count++; - } - else - cvSetAdd( set_header, NULL, &elem ); - return elem; -} - -/** Removes set element given its pointer */ -CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) -{ - CvSetElem* _elem = (CvSetElem*)elem; - assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); - _elem->next_free = set_header->free_elems; - _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; - set_header->free_elems = _elem; - set_header->active_count--; -} - -/** Removes element from the set by its index */ -CVAPI(void) cvSetRemove( CvSet* set_header, int index ); - -/** Returns a set element by index. If the element doesn't belong to the set, - NULL is returned */ -CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) -{ - CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); - return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; -} - -/** Removes all the elements from the set */ -CVAPI(void) cvClearSet( CvSet* set_header ); - -/** Creates new graph */ -CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, - int vtx_size, int edge_size, - CvMemStorage* storage ); - -/** Adds new vertex to the graph */ -CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), - CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); - - -/** Removes vertex from the graph together with all incident edges */ -CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); -CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); - - -/** Link two vertices specified by indices or pointers if they - are not connected or return pointer to already existing edge - connecting the vertices. - Functions return 1 if a new edge was created, 0 otherwise */ -CVAPI(int) cvGraphAddEdge( CvGraph* graph, - int start_idx, int end_idx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, - CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -/** Remove edge connecting two vertices */ -CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); -CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, - CvGraphVtx* end_vtx ); - -/** Find edge connecting two vertices */ -CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); -CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, - const CvGraphVtx* start_vtx, - const CvGraphVtx* end_vtx ); -#define cvGraphFindEdge cvFindGraphEdge -#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr - -/** Remove all vertices and edges from the graph */ -CVAPI(void) cvClearGraph( CvGraph* graph ); - - -/** Count number of edges incident to the vertex */ -CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); -CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); - - -/** Retrieves graph vertex by given index */ -#define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) - -/** Retrieves index of a graph vertex given its pointer */ -#define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) - -/** Retrieves index of a graph edge given its pointer */ -#define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) - -#define cvGraphGetVtxCount( graph ) ((graph)->active_count) -#define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) - -#define CV_GRAPH_VERTEX 1 -#define CV_GRAPH_TREE_EDGE 2 -#define CV_GRAPH_BACK_EDGE 4 -#define CV_GRAPH_FORWARD_EDGE 8 -#define CV_GRAPH_CROSS_EDGE 16 -#define CV_GRAPH_ANY_EDGE 30 -#define CV_GRAPH_NEW_TREE 32 -#define CV_GRAPH_BACKTRACKING 64 -#define CV_GRAPH_OVER -1 - -#define CV_GRAPH_ALL_ITEMS -1 - -/** flags for graph vertices and edges */ -#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) -#define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ - (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_IS_GRAPH_EDGE_VISITED(edge) \ - (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) -#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) - -typedef struct CvGraphScanner -{ - CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ - CvGraphVtx* dst; /* current graph edge destination vertex */ - CvGraphEdge* edge; /* current edge */ - - CvGraph* graph; /* the graph */ - CvSeq* stack; /* the graph vertex stack */ - int index; /* the lower bound of certainly visited vertices */ - int mask; /* event mask */ -} -CvGraphScanner; - -/** Creates new graph scanner. */ -CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, - CvGraphVtx* vtx CV_DEFAULT(NULL), - int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); - -/** Releases graph scanner. */ -CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); - -/** Get next graph element */ -CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); - -/** Creates a copy of graph */ -CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); - - -/** Does look-up transformation. Elements of the source array - (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ -CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); - - -/******************* Iteration through the sequence tree *****************/ -typedef struct CvTreeNodeIterator -{ - const void* node; - int level; - int max_level; -} -CvTreeNodeIterator; - -CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, - const void* first, int max_level ); -CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); -CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); - -/** Inserts sequence into tree with specified "parent" sequence. - If parent is equal to frame (e.g. the most external contour), - then added contour will have null pointer to parent. */ -CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); - -/** Removes contour from tree (together with the contour children). */ -CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); - -/** Gathers pointers to all the sequences, - accessible from the `first`, to the single sequence */ -CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, - CvMemStorage* storage ); - -/****************************************************************************************\ -* System functions * -\****************************************************************************************/ - -typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) - (int,int,int,char*,char*,int,int,int,int,int, - IplROI*,IplImage*,void*,IplTileInfo*); -typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); -typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); -typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); -typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); - -/** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. - -Normally, the function is not called directly. Instead, a simple macro -CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers -to IPL allocation functions. : -@code - ... - CV_TURN_ON_IPL_COMPATIBILITY() - ... -@endcode -@param create_header pointer to a function, creating IPL image header. -@param allocate_data pointer to a function, allocating IPL image data. -@param deallocate pointer to a function, deallocating IPL image. -@param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). -@param clone_image pointer to a function, cloning an IPL image. - */ -CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, - Cv_iplAllocateImageData allocate_data, - Cv_iplDeallocate deallocate, - Cv_iplCreateROI create_roi, - Cv_iplCloneImage clone_image ); - -#define CV_TURN_ON_IPL_COMPATIBILITY() \ - cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ - iplDeallocate, iplCreateROI, iplCloneImage ) - - -/** @brief Releases an object. - - The function finds the type of a given object and calls release with the double pointer. - @param struct_ptr Double pointer to the object - */ -CVAPI(void) cvRelease( void** struct_ptr ); - - -/********************************** Error Handling **************************************/ - -/** Get current OpenCV error status */ -CVAPI(int) cvGetErrStatus( void ); - -/** Sets error status silently */ -CVAPI(void) cvSetErrStatus( int status ); - -#define CV_ErrModeLeaf 0 /* Print error and exit program */ -#define CV_ErrModeParent 1 /* Print error and continue */ -#define CV_ErrModeSilent 2 /* Don't print and continue */ - -/** Retrieves current error processing mode */ -CVAPI(int) cvGetErrMode( void ); - -/** Sets error processing mode, returns previously used mode */ -CVAPI(int) cvSetErrMode( int mode ); - - -/** Retrieves detailed information about the last error occurred */ -CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, - const char** filename, int* line ); - -/** Maps IPP error codes to the counterparts from OpenCV */ -CVAPI(int) cvErrorFromIppStatus( int ipp_status ); - - -#define OPENCV_ERROR(status,func,context) \ -cv::error((status),(func),(context),__FILE__,__LINE__) - -#define OPENCV_ASSERT(expr,func,context) \ -{if (! (expr)) \ -{OPENCV_ERROR(CV_StsInternal,(func),(context));}} - -#define OPENCV_CALL( Func ) \ -{ \ -Func; \ -} - -/** - CV_CHECK macro checks error status after CV (or IPL) - function call. If error detected, control will be transferred to the exit - label. - */ -#define CV_CHECK() \ -{ \ - if( cvGetErrStatus() < 0 ) \ - CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ -} - - -/** - CV_CALL macro calls CV (or IPL) function, checks error status and - signals a error if the function failed. Useful in "parent node" - error processing mode - */ -#define CV_CALL( Func ) \ -{ \ - Func; \ - CV_CHECK(); \ -} - - -/** Runtime assertion macro */ -#define CV_ASSERT( Condition ) \ -{ \ - if( !(Condition) ) \ - CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ -} - -#define __CV_BEGIN__ { -#define __CV_END__ goto exit; exit: ; } -#define __CV_EXIT__ goto exit - -/** @} core_c */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#ifdef __cplusplus - -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @addtogroup core_c_glue -//! @{ - -/////////////////////////////////////////// glue /////////////////////////////////////////// - -//! converts array (CvMat or IplImage) to cv::Mat -CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, - bool allowND=true, int coiMode=0, - AutoBuffer* buf=0); - - -//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. -CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); - - -////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// - -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(IplImage* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; - -////////////// convenient wrappers for operating old-style dynamic structures ////////////// - -template class SeqIterator; - -typedef Ptr MemStorage; - -/*! - Template Sequence Class derived from CvSeq - - The class provides more convenient access to sequence elements, - STL-style operations and iterators. - - \note The class is targeted for simple data types, - i.e. no constructors or destructors - are called for the sequence elements. -*/ -template class Seq -{ -public: - typedef SeqIterator<_Tp> iterator; - typedef SeqIterator<_Tp> const_iterator; - - //! the default constructor - Seq(); - //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. - Seq(const CvSeq* seq); - //! creates the empty sequence that resides in the specified storage - Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); - //! returns read-write reference to the specified element - _Tp& operator [](int idx); - //! returns read-only reference to the specified element - const _Tp& operator[](int idx) const; - //! returns iterator pointing to the beginning of the sequence - SeqIterator<_Tp> begin() const; - //! returns iterator pointing to the element following the last sequence element - SeqIterator<_Tp> end() const; - //! returns the number of elements in the sequence - size_t size() const; - //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) - int type() const; - //! returns the depth of sequence elements (CV_8U ... CV_64F) - int depth() const; - //! returns the number of channels in each sequence element - int channels() const; - //! returns the size of each sequence element - size_t elemSize() const; - //! returns index of the specified sequence element - size_t index(const _Tp& elem) const; - //! appends the specified element to the end of the sequence - void push_back(const _Tp& elem); - //! appends the specified element to the front of the sequence - void push_front(const _Tp& elem); - //! appends zero or more elements to the end of the sequence - void push_back(const _Tp* elems, size_t count); - //! appends zero or more elements to the front of the sequence - void push_front(const _Tp* elems, size_t count); - //! inserts the specified element to the specified position - void insert(int idx, const _Tp& elem); - //! inserts zero or more elements to the specified position - void insert(int idx, const _Tp* elems, size_t count); - //! removes element at the specified position - void remove(int idx); - //! removes the specified subsequence - void remove(const Range& r); - - //! returns reference to the first sequence element - _Tp& front(); - //! returns read-only reference to the first sequence element - const _Tp& front() const; - //! returns reference to the last sequence element - _Tp& back(); - //! returns read-only reference to the last sequence element - const _Tp& back() const; - //! returns true iff the sequence contains no elements - bool empty() const; - - //! removes all the elements from the sequence - void clear(); - //! removes the first element from the sequence - void pop_front(); - //! removes the last element from the sequence - void pop_back(); - //! removes zero or more elements from the beginning of the sequence - void pop_front(_Tp* elems, size_t count); - //! removes zero or more elements from the end of the sequence - void pop_back(_Tp* elems, size_t count); - - //! copies the whole sequence or the sequence slice to the specified vector - void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; - //! returns the vector containing all the sequence elements - operator std::vector<_Tp>() const; - - CvSeq* seq; -}; - - -/*! - STL-style Sequence Iterator inherited from the CvSeqReader structure -*/ -template class SeqIterator : public CvSeqReader -{ -public: - //! the default constructor - SeqIterator(); - //! the constructor setting the iterator to the beginning or to the end of the sequence - SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); - //! positions the iterator within the sequence - void seek(size_t pos); - //! reports the current iterator position - size_t tell() const; - //! returns reference to the current sequence element - _Tp& operator *(); - //! returns read-only reference to the current sequence element - const _Tp& operator *() const; - //! moves iterator to the next sequence element - SeqIterator& operator ++(); - //! moves iterator to the next sequence element - SeqIterator operator ++(int) const; - //! moves iterator to the previous sequence element - SeqIterator& operator --(); - //! moves iterator to the previous sequence element - SeqIterator operator --(int) const; - - //! moves iterator forward by the specified offset (possibly negative) - SeqIterator& operator +=(int); - //! moves iterator backward by the specified offset (possibly negative) - SeqIterator& operator -=(int); - - // this is index of the current element module seq->total*2 - // (to distinguish between 0 and seq->total) - int index; -}; - - - -// bridge C++ => C Seq API -CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); -CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); -CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, - int count, int in_front=0 ); -CV_EXPORTS void seqRemove( CvSeq* seq, int index ); -CV_EXPORTS void clearSeq( CvSeq* seq ); -CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); -CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); -CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -template inline Seq<_Tp>::Seq() : seq(0) {} -template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) -{ - CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); -} - -template inline Seq<_Tp>::Seq( MemStorage& storage, - int headerSize ) -{ - CV_Assert(headerSize >= (int)sizeof(CvSeq)); - seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); -} - -template inline _Tp& Seq<_Tp>::operator [](int idx) -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline const _Tp& Seq<_Tp>::operator [](int idx) const -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline SeqIterator<_Tp> Seq<_Tp>::begin() const -{ return SeqIterator<_Tp>(*this); } - -template inline SeqIterator<_Tp> Seq<_Tp>::end() const -{ return SeqIterator<_Tp>(*this, true); } - -template inline size_t Seq<_Tp>::size() const -{ return seq ? seq->total : 0; } - -template inline int Seq<_Tp>::type() const -{ return seq ? CV_MAT_TYPE(seq->flags) : 0; } - -template inline int Seq<_Tp>::depth() const -{ return seq ? CV_MAT_DEPTH(seq->flags) : 0; } - -template inline int Seq<_Tp>::channels() const -{ return seq ? CV_MAT_CN(seq->flags) : 0; } - -template inline size_t Seq<_Tp>::elemSize() const -{ return seq ? seq->elem_size : 0; } - -template inline size_t Seq<_Tp>::index(const _Tp& elem) const -{ return cvSeqElemIdx(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp& elem) -{ cvSeqPush(seq, &elem); } - -template inline void Seq<_Tp>::push_front(const _Tp& elem) -{ cvSeqPushFront(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 1); } - -template inline _Tp& Seq<_Tp>::back() -{ return *(_Tp*)getSeqElem(seq, -1); } - -template inline const _Tp& Seq<_Tp>::back() const -{ return *(const _Tp*)getSeqElem(seq, -1); } - -template inline _Tp& Seq<_Tp>::front() -{ return *(_Tp*)getSeqElem(seq, 0); } - -template inline const _Tp& Seq<_Tp>::front() const -{ return *(const _Tp*)getSeqElem(seq, 0); } - -template inline bool Seq<_Tp>::empty() const -{ return !seq || seq->total == 0; } - -template inline void Seq<_Tp>::clear() -{ if(seq) clearSeq(seq); } - -template inline void Seq<_Tp>::pop_back() -{ seqPop(seq); } - -template inline void Seq<_Tp>::pop_front() -{ seqPopFront(seq); } - -template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 1); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) -{ seqInsert(seq, idx, &elem); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) -{ - CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); - seqInsertSlice(seq, idx, &m); -} - -template inline void Seq<_Tp>::remove(int idx) -{ seqRemove(seq, idx); } - -template inline void Seq<_Tp>::remove(const Range& r) -{ seqRemoveSlice(seq, cvSlice(r.start, r.end)); } - -template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const -{ - size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; - vec.resize(len); - if( seq && len ) - cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); -} - -template inline Seq<_Tp>::operator std::vector<_Tp>() const -{ - std::vector<_Tp> vec; - copyTo(vec); - return vec; -} - -template inline SeqIterator<_Tp>::SeqIterator() -{ memset(this, 0, sizeof(*this)); } - -template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) -{ - cvStartReadSeq(_seq.seq, this); - index = seekEnd ? _seq.seq->total : 0; -} - -template inline void SeqIterator<_Tp>::seek(size_t pos) -{ - cvSetSeqReaderPos(this, (int)pos, false); - index = pos; -} - -template inline size_t SeqIterator<_Tp>::tell() const -{ return index; } - -template inline _Tp& SeqIterator<_Tp>::operator *() -{ return *(_Tp*)ptr; } - -template inline const _Tp& SeqIterator<_Tp>::operator *() const -{ return *(const _Tp*)ptr; } - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() -{ - CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); - if( ++index >= seq->total*2 ) - index = 0; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const -{ - SeqIterator<_Tp> it = *this; - ++*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() -{ - CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); - if( --index < 0 ) - index = seq->total*2-1; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const -{ - SeqIterator<_Tp> it = *this; - --*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) -{ - cvSetSeqReaderPos(this, delta, 1); - index += delta; - int n = seq->total*2; - if( index < 0 ) - index += n; - if( index >= n ) - index -= n; - return *this; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) -{ - return (*this += -delta); -} - -template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - ptrdiff_t delta = a.index - b.index, n = a.seq->total; - if( delta > n || delta < -n ) - delta += delta < 0 ? n : -n; - return delta; -} - -template inline bool operator == (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return a.seq == b.seq && a.index == b.index; -} - -template inline bool operator != (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return !(a == b); -} - -//! @} - -} // cv - -#endif - -#endif diff --git a/modules/core/include/opencv2/core/types_c.h b/modules/core/include/opencv2/core/types_c.h deleted file mode 100644 index 2fcc2cdd01..0000000000 --- a/modules/core/include/opencv2/core/types_c.h +++ /dev/null @@ -1,1910 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_TYPES_H -#define OPENCV_CORE_TYPES_H - -#ifdef CV__ENABLE_C_API_CTORS // invalid C API ctors (must be removed) -#if defined(_WIN32) && !defined(CV__SKIP_MESSAGE_MALFORMED_C_API_CTORS) -#error "C API ctors don't work on Win32: https://github.com/opencv/opencv/issues/15990" -#endif -#endif - -//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only - -#ifdef __cplusplus - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#define CV_STRUCT_INITIALIZER {0,} -#else -#if defined(__GNUC__) && __GNUC__ == 4 // GCC 4.x warns on "= {}" initialization, fixed in GCC 5.0 -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif -#define CV_STRUCT_INITIALIZER {} -#endif - -#else -#define CV_STRUCT_INITIALIZER {0} -#endif - - -#ifdef HAVE_IPL -# ifndef __IPL_H__ -# if defined _WIN32 -# include -# else -# include -# endif -# endif -#elif defined __IPL_H__ -# define HAVE_IPL -#endif - -#include "opencv2/core/cvdef.h" - -#ifndef SKIP_INCLUDES -#include -#include -#include -#include -#endif // SKIP_INCLUDES - - - -#ifndef CV_DEFAULT -# ifdef __cplusplus -# define CV_DEFAULT(val) = val -# else -# define CV_DEFAULT(val) -# endif -#endif - -#ifndef CV_EXTERN_C_FUNCPTR -# ifdef __cplusplus -# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } -# else -# define CV_EXTERN_C_FUNCPTR(x) typedef x -# endif -#endif - -#ifndef CVAPI -# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL -#endif - -#ifndef CV_IMPL -# define CV_IMPL CV_EXTERN_C -#endif - -#ifdef __cplusplus -# include "opencv2/core.hpp" -#endif - -/** @addtogroup core_c - @{ -*/ - -/** @brief This is the "metatype" used *only* as a function parameter. - -It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even -CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 -bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. - */ -typedef void CvArr; - -typedef int CVStatus; - -/** @see cv::Error::Code */ -enum { - CV_StsOk= 0, /**< everything is ok */ - CV_StsBackTrace= -1, /**< pseudo error for back trace */ - CV_StsError= -2, /**< unknown /unspecified error */ - CV_StsInternal= -3, /**< internal error (bad state) */ - CV_StsNoMem= -4, /**< insufficient memory */ - CV_StsBadArg= -5, /**< function arg/param is bad */ - CV_StsBadFunc= -6, /**< unsupported function */ - CV_StsNoConv= -7, /**< iter. didn't converge */ - CV_StsAutoTrace= -8, /**< tracing */ - CV_HeaderIsNull= -9, /**< image header is NULL */ - CV_BadImageSize= -10, /**< image size is invalid */ - CV_BadOffset= -11, /**< offset is invalid */ - CV_BadDataPtr= -12, /**/ - CV_BadStep= -13, /**< image step is wrong, this may happen for a non-continuous matrix */ - CV_BadModelOrChSeq= -14, /**/ - CV_BadNumChannels= -15, /**< bad number of channels, for example, some functions accept only single channel matrices */ - CV_BadNumChannel1U= -16, /**/ - CV_BadDepth= -17, /**< input image depth is not supported by the function */ - CV_BadAlphaChannel= -18, /**/ - CV_BadOrder= -19, /**< number of dimensions is out of range */ - CV_BadOrigin= -20, /**< incorrect input origin */ - CV_BadAlign= -21, /**< incorrect input align */ - CV_BadCallBack= -22, /**/ - CV_BadTileSize= -23, /**/ - CV_BadCOI= -24, /**< input COI is not supported */ - CV_BadROISize= -25, /**< incorrect input roi */ - CV_MaskIsTiled= -26, /**/ - CV_StsNullPtr= -27, /**< null pointer */ - CV_StsVecLengthErr= -28, /**< incorrect vector length */ - CV_StsFilterStructContentErr= -29, /**< incorrect filter structure content */ - CV_StsKernelStructContentErr= -30, /**< incorrect transform kernel content */ - CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ - CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ - CV_StsDivByZero= -202, /**< division by zero */ - CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ - CV_StsObjectNotFound= -204, /**< request can't be completed */ - CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ - CV_StsBadFlag= -206, /**< flag is wrong or not supported */ - CV_StsBadPoint= -207, /**< bad CvPoint */ - CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ - CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ - CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ - CV_StsOutOfRange= -211, /**< some of parameters are out of range */ - CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ - CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ - CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ - CV_StsAssert= -215, /**< assertion failed */ - CV_GpuNotSupported= -216, /**< no CUDA support */ - CV_GpuApiCallError= -217, /**< GPU API call error */ - CV_OpenGlNotSupported= -218, /**< no OpenGL support */ - CV_OpenGlApiCallError= -219, /**< OpenGL API call error */ - CV_OpenCLApiCallError= -220, /**< OpenCL API call error */ - CV_OpenCLDoubleNotSupported= -221, - CV_OpenCLInitError= -222, /**< OpenCL initialization error */ - CV_OpenCLNoAMDBlasFft= -223 -}; - -/****************************************************************************************\ -* Common macros and inline functions * -\****************************************************************************************/ - -/** absolute value without jumps */ -#ifndef __cplusplus -# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) -#else -# define CV_IABS(a) abs(a) -#endif - - -#define cvInvSqrt(value) ((float)(1./sqrt(value))) -#define cvSqrt(value) ((float)sqrt(value)) - - -/*************** Random number generation *******************/ - -typedef uint64 CvRNG; - -#define CV_RNG_COEFF 4164903690U - -/** @brief Initializes a random number generator state. - -The function initializes a random number generator and returns the state. The pointer to the state -can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current -implementation a multiply-with-carry generator is used. -@param seed 64-bit value used to initiate a random sequence -@sa the C++ class RNG replaced CvRNG. - */ -CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) -{ - CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; - return rng; -} - -/** @brief Returns a 32-bit unsigned integer and updates RNG. - -The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG -state. It is similar to the rand() function from the C runtime library, except that OpenCV functions -always generates a 32-bit random number, regardless of the platform. -@param rng CvRNG state initialized by cvRNG. - */ -CV_INLINE unsigned cvRandInt( CvRNG* rng ) -{ - uint64 temp = *rng; - temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); - *rng = temp; - return (unsigned)temp; -} - -/** @brief Returns a floating-point random number and updates RNG. - -The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not -included). -@param rng RNG state initialized by cvRNG - */ -CV_INLINE double cvRandReal( CvRNG* rng ) -{ - return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; -} - -/****************************************************************************************\ -* Image type (IplImage) * -\****************************************************************************************/ - -#ifndef HAVE_IPL - -/* - * The following definitions (until #endif) - * is an extract from IPL headers. - * Copyright (c) 1995 Intel Corporation. - */ -#define IPL_DEPTH_SIGN 0x80000000 - -#define IPL_DEPTH_1U 1 -#define IPL_DEPTH_8U 8 -#define IPL_DEPTH_16U 16 -#define IPL_DEPTH_32F 32 - -#define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) -#define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) -#define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) - -#define IPL_DATA_ORDER_PIXEL 0 -#define IPL_DATA_ORDER_PLANE 1 - -#define IPL_ORIGIN_TL 0 -#define IPL_ORIGIN_BL 1 - -#define IPL_ALIGN_4BYTES 4 -#define IPL_ALIGN_8BYTES 8 -#define IPL_ALIGN_16BYTES 16 -#define IPL_ALIGN_32BYTES 32 - -#define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES -#define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES - -#define IPL_BORDER_CONSTANT 0 -#define IPL_BORDER_REPLICATE 1 -#define IPL_BORDER_REFLECT 2 -#define IPL_BORDER_WRAP 3 - -#ifdef __cplusplus -typedef struct _IplImage IplImage; -CV_EXPORTS _IplImage cvIplImage(const cv::Mat& m); -#endif - -/** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV -only supports a subset of possible IplImage formats, as outlined in the parameter list above. - -In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require -that the image size or ROI size of all source and destination images match exactly. On the other -hand, the Intel Image Processing Library processes the area of intersection between the source and -destination images (or ROIs), allowing them to vary independently. -*/ -typedef struct -_IplImage -{ - int nSize; /**< sizeof(IplImage) */ - int ID; /**< version (=0)*/ - int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ - int alphaChannel; /**< Ignored by OpenCV */ - int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, - IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ - char colorModel[4]; /**< Ignored by OpenCV */ - char channelSeq[4]; /**< ditto */ - int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. - cvCreateImage can only create interleaved images */ - int origin; /**< 0 - top-left origin, - 1 - bottom-left origin (Windows bitmaps style). */ - int align; /**< Alignment of image rows (4 or 8). - OpenCV ignores it and uses widthStep instead. */ - int width; /**< Image width in pixels. */ - int height; /**< Image height in pixels. */ - struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ - struct _IplImage *maskROI; /**< Must be NULL. */ - void *imageId; /**< " " */ - struct _IplTileInfo *tileInfo; /**< " " */ - int imageSize; /**< Image data size in bytes - (==image->height*image->widthStep - in case of interleaved data)*/ - char *imageData; /**< Pointer to aligned image data. */ - int widthStep; /**< Size of aligned image row in bytes. */ - int BorderMode[4]; /**< Ignored by OpenCV. */ - int BorderConst[4]; /**< Ditto. */ - char *imageDataOrigin; /**< Pointer to very origin of image data - (not necessarily aligned) - - needed for correct deallocation */ - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - _IplImage() - { - memset(this, 0, sizeof(*this)); // valid for POD structure - nSize = sizeof(IplImage); - } - _IplImage(const cv::Mat& m) { *this = cvIplImage(m); } -#endif -} -IplImage; - -CV_INLINE IplImage cvIplImage() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - IplImage self = CV_STRUCT_INITIALIZER; self.nSize = sizeof(IplImage); return self; -#else - return _IplImage(); -#endif -} - -typedef struct _IplTileInfo IplTileInfo; - -typedef struct _IplROI -{ - int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ - int xOffset; - int yOffset; - int width; - int height; -} -IplROI; - -typedef struct _IplConvKernel -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - int *values; - int nShiftR; -} -IplConvKernel; - -typedef struct _IplConvKernelFP -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - float *values; -} -IplConvKernelFP; - -#define IPL_IMAGE_HEADER 1 -#define IPL_IMAGE_DATA 2 -#define IPL_IMAGE_ROI 4 - -#endif/*HAVE_IPL*/ - -/** extra border mode */ -#define IPL_BORDER_REFLECT_101 4 -#define IPL_BORDER_TRANSPARENT 5 - -#define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) -#define CV_TYPE_NAME_IMAGE "opencv-image" - -#define CV_IS_IMAGE_HDR(img) \ - ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) - -#define CV_IS_IMAGE(img) \ - (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) - -/** for storing double-precision - floating point data in IplImage's */ -#define IPL_DEPTH_64F 64 - -/** get reference to pixel at (col,row), - for multi-channel images (col) should be multiplied by number of channels */ -#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ - (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) - -/****************************************************************************************\ -* Matrix type (CvMat) * -\****************************************************************************************/ - -#define CV_AUTO_STEP 0x7fffffff -#define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) - -#define CV_MAGIC_MASK 0xFFFF0000 -#define CV_MAT_MAGIC_VAL 0x42420000 -#define CV_TYPE_NAME_MAT "opencv-matrix" - -#ifdef __cplusplus -typedef struct CvMat CvMat; -CV_INLINE CvMat cvMat(const cv::Mat& m); -#endif - -/** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column -index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: - - uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) - CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; - -To access multiple-channel matrices, you can use -CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). - -@deprecated CvMat is now obsolete; consider using Mat instead. - */ -typedef struct CvMat -{ - int type; - int step; - - /* for internal use only */ - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - short* s; - int* i; - float* fl; - double* db; - } data; - -#ifdef __cplusplus - union - { - int rows; - int height; - }; - - union - { - int cols; - int width; - }; -#else - int rows; - int cols; -#endif - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMat() {} - CvMat(const cv::Mat& m) { *this = cvMat(m); } -#endif -} -CvMat; - - -#define CV_IS_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) - -#define CV_IS_MAT_HDR_Z(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) - -#define CV_IS_MAT(mat) \ - (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) - -#define CV_IS_MASK_ARR(mat) \ - (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) - -#define CV_ARE_TYPES_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) - -#define CV_ARE_CNS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) - -#define CV_ARE_DEPTHS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) - -#define CV_ARE_SIZES_EQ(mat1, mat2) \ - ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) - -#define CV_IS_MAT_CONST(mat) \ - (((mat)->rows|(mat)->cols) == 1) - -#define IPL2CV_DEPTH(depth) \ - ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ - (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ - (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) - -/** Inline constructor. No data is allocated internally!!! - * (Use together with cvCreateData, or use cvCreateMat instead to - * get a matrix with allocated data): - */ -CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) -{ - CvMat m; - - assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); - type = CV_MAT_TYPE(type); - m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; - m.cols = cols; - m.rows = rows; - m.step = m.cols*CV_ELEM_SIZE(type); - m.data.ptr = (uchar*)data; - m.refcount = NULL; - m.hdr_refcount = 0; - - return m; -} - -#ifdef __cplusplus - -CV_INLINE CvMat cvMat(const cv::Mat& m) -{ - CvMat self; - CV_DbgAssert(m.dims <= 2); - self = cvMat(m.dims == 1 ? 1 : m.rows, m.cols, m.type(), m.data); - self.step = (int)m.step[0]; - self.type = (self.type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); - return self; -} -CV_INLINE CvMat cvMat() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMat(); -#endif -} -CV_INLINE CvMat cvMat(const CvMat& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; memcpy(&self, &m, sizeof(self)); return self; -#else - return CvMat(m); -#endif -} - -#endif // __cplusplus - - -#define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ - (assert( (unsigned)(row) < (unsigned)(mat).rows && \ - (unsigned)(col) < (unsigned)(mat).cols ), \ - (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) - -#define CV_MAT_ELEM_PTR( mat, row, col ) \ - CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) - -#define CV_MAT_ELEM( mat, elemtype, row, col ) \ - (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) - -/** @brief Returns the particular element of single-channel floating-point matrix. - -The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat Input matrix -@param row The zero-based index of row -@param col The zero-based index of column - */ -CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) -{ - int type; - - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - else - { - assert( type == CV_64FC1 ); - return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - } -} - -/** @brief Sets a specific element of a single-channel floating-point matrix. - -The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat The matrix -@param row The zero-based index of row -@param col The zero-based index of column -@param value The new value of the matrix element - */ -CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) -{ - int type; - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; - else - { - assert( type == CV_64FC1 ); - ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; - } -} - - -CV_INLINE int cvIplDepth( int type ) -{ - int depth = CV_MAT_DEPTH(type); - return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || - depth == CV_32S ? IPL_DEPTH_SIGN : 0); -} - - -/****************************************************************************************\ -* Multi-dimensional dense array (CvMatND) * -\****************************************************************************************/ - -#define CV_MATND_MAGIC_VAL 0x42430000 -#define CV_TYPE_NAME_MATND "opencv-nd-matrix" - -#ifdef __cplusplus -typedef struct CvMatND CvMatND; -CV_EXPORTS CvMatND cvMatND(const cv::Mat& m); -#endif - -/** - @deprecated consider using cv::Mat instead - */ -typedef struct -CvMatND -{ - int type; - int dims; - - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - float* fl; - double* db; - int* i; - short* s; - } data; - - struct - { - int size; - int step; - } - dim[CV_MAX_DIM]; - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMatND() {} - CvMatND(const cv::Mat& m) { *this = cvMatND(m); } -#endif -} -CvMatND; - - -CV_INLINE CvMatND cvMatND() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvMatND self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMatND(); -#endif -} - -#define CV_IS_MATND_HDR(mat) \ - ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) - -#define CV_IS_MATND(mat) \ - (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) - - -/****************************************************************************************\ -* Multi-dimensional sparse array (CvSparseMat) * -\****************************************************************************************/ - -#define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 -#define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" - -struct CvSet; - -typedef struct CvSparseMat -{ - int type; - int dims; - int* refcount; - int hdr_refcount; - - struct CvSet* heap; - void** hashtable; - int hashsize; - int valoffset; - int idxoffset; - int size[CV_MAX_DIM]; - -#ifdef __cplusplus - CV_EXPORTS void copyToSparseMat(cv::SparseMat& m) const; -#endif -} -CvSparseMat; - -#ifdef __cplusplus -CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); -#endif - -#define CV_IS_SPARSE_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) - -#define CV_IS_SPARSE_MAT(mat) \ - CV_IS_SPARSE_MAT_HDR(mat) - -/**************** iteration through a sparse array *****************/ - -typedef struct CvSparseNode -{ - unsigned hashval; - struct CvSparseNode* next; -} -CvSparseNode; - -typedef struct CvSparseMatIterator -{ - CvSparseMat* mat; - CvSparseNode* node; - int curidx; -} -CvSparseMatIterator; - -#define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) -#define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) - -/****************************************************************************************\ -* Histogram * -\****************************************************************************************/ - -typedef int CvHistType; - -#define CV_HIST_MAGIC_VAL 0x42450000 -#define CV_HIST_UNIFORM_FLAG (1 << 10) - -/** indicates whether bin ranges are set already or not */ -#define CV_HIST_RANGES_FLAG (1 << 11) - -#define CV_HIST_ARRAY 0 -#define CV_HIST_SPARSE 1 -#define CV_HIST_TREE CV_HIST_SPARSE - -/** should be used as a parameter only, - it turns to CV_HIST_UNIFORM_FLAG of hist->type */ -#define CV_HIST_UNIFORM 1 - -typedef struct CvHistogram -{ - int type; - CvArr* bins; - float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ - float** thresh2; /**< For non-uniform histograms. */ - CvMatND mat; /**< Embedded matrix header for array histograms. */ -} -CvHistogram; - -#define CV_IS_HIST( hist ) \ - ((hist) != NULL && \ - (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ - (hist)->bins != NULL) - -#define CV_IS_UNIFORM_HIST( hist ) \ - (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) - -#define CV_IS_SPARSE_HIST( hist ) \ - CV_IS_SPARSE_MAT((hist)->bins) - -#define CV_HIST_HAS_RANGES( hist ) \ - (((hist)->type & CV_HIST_RANGES_FLAG) != 0) - -/****************************************************************************************\ -* Other supplementary data type definitions * -\****************************************************************************************/ - -/*************************************** CvRect *****************************************/ -/** @sa Rect_ */ -typedef struct CvRect -{ - int x; - int y; - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvRect() __attribute__(( warning("Non-initialized variable") )) {}; - template CvRect(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - x = y = width = height = 0; - if (list.size() == 4) - { - x = list.begin()[0]; y = list.begin()[1]; width = list.begin()[2]; height = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} - template - CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } -#endif -} -CvRect; - -/** constructs CvRect structure. */ -CV_INLINE CvRect cvRect( int x, int y, int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvRect r = {x, y, width, height}; -#else - CvRect r(x, y , width, height); -#endif - return r; -} -#ifdef __cplusplus -CV_INLINE CvRect cvRect(const cv::Rect& rc) { return cvRect(rc.x, rc.y, rc.width, rc.height); } -#endif - -CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) -{ - IplROI roi; - roi.xOffset = rect.x; - roi.yOffset = rect.y; - roi.width = rect.width; - roi.height = rect.height; - roi.coi = coi; - - return roi; -} - - -CV_INLINE CvRect cvROIToRect( IplROI roi ) -{ - return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); -} - -/*********************************** CvTermCriteria *************************************/ - -#define CV_TERMCRIT_ITER 1 -#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER -#define CV_TERMCRIT_EPS 2 - -/** @sa TermCriteria - */ -typedef struct CvTermCriteria -{ - int type; /**< may be combination of - CV_TERMCRIT_ITER - CV_TERMCRIT_EPS */ - int max_iter; - double epsilon; -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} - CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} -#endif -#ifdef __cplusplus - operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } -#endif -} -CvTermCriteria; - -CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvTermCriteria t = { type, max_iter, (float)epsilon}; -#else - CvTermCriteria t(type, max_iter, epsilon); -#endif - return t; -} -#ifdef __cplusplus -CV_INLINE CvTermCriteria cvTermCriteria(const cv::TermCriteria& t) { return cvTermCriteria(t.type, t.maxCount, t.epsilon); } -#endif - - -/******************************* CvPoint and variants ***********************************/ - -typedef struct CvPoint -{ - int x; - int y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} - template - CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint; - -/** constructs CvPoint structure. */ -CV_INLINE CvPoint cvPoint( int x, int y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint p = {x, y}; -#else - CvPoint p(x, y); -#endif - return p; -} -#ifdef __cplusplus -CV_INLINE CvPoint cvPoint(const cv::Point& pt) { return cvPoint(pt.x, pt.y); } -#endif - -typedef struct CvPoint2D32f -{ - float x; - float y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} - template - CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint2D32f; - -/** constructs CvPoint2D32f structure. */ -CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)x, (float)y }; -#else - CvPoint2D32f p((float)x, (float)y); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint2D32f cvPoint2D32f(const cv::Point_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)pt.x, (float)pt.y }; -#else - CvPoint2D32f p((float)pt.x, (float)pt.y); -#endif - return p; -} -#endif - -/** converts CvPoint to CvPoint2D32f. */ -CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) -{ - return cvPoint2D32f( (float)point.x, (float)point.y ); -} - -/** converts CvPoint2D32f to CvPoint. */ -CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint ipt = { cvRound(point.x), cvRound(point.y) }; -#else - CvPoint ipt(cvRound(point.x), cvRound(point.y)); -#endif - return ipt; -} - - -typedef struct CvPoint3D32f -{ - float x; - float y; - float z; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} - template - CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} -#endif -#ifdef __cplusplus - template - operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } -#endif -} -CvPoint3D32f; - -/** constructs CvPoint3D32f structure. */ -CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)x, (float)y, (float)z }; -#else - CvPoint3D32f p((float)x, (float)y, (float)z); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint3D32f cvPoint3D32f(const cv::Point3_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)pt.x, (float)pt.y, (float)pt.z }; -#else - CvPoint3D32f p((float)pt.x, (float)pt.y, (float)pt.z); -#endif - return p; -} -#endif - - -typedef struct CvPoint2D64f -{ - double x; - double y; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#endif -} -CvPoint2D64f; - -/** constructs CvPoint2D64f structure.*/ -CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) -{ - CvPoint2D64f p = { x, y }; - return p; -} - - -typedef struct CvPoint3D64f -{ - double x; - double y; - double z; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#endif -} -CvPoint3D64f; - -/** constructs CvPoint3D64f structure. */ -CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) -{ - CvPoint3D64f p = { x, y, z }; - return p; -} - - -/******************************** CvSize's & CvBox **************************************/ - -typedef struct CvSize -{ - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize(int w = 0, int h = 0): width(w), height(h) {} - template - CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize; - -/** constructs CvSize structure. */ -CV_INLINE CvSize cvSize( int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { width, height }; -#else - CvSize s(width, height); -#endif - return s; -} - -#ifdef __cplusplus -CV_INLINE CvSize cvSize(const cv::Size& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { sz.width, sz.height }; -#else - CvSize s(sz.width, sz.height); -#endif - return s; -} -#endif - -typedef struct CvSize2D32f -{ - float width; - float height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} - template - CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize2D32f; - -/** constructs CvSize2D32f structure. */ -CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)width, (float)height }; -#else - CvSize2D32f s((float)width, (float)height); -#endif - return s; -} -#ifdef __cplusplus -template -CvSize2D32f cvSize2D32f(const cv::Size_<_Tp>& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)sz.width, (float)sz.height }; -#else - CvSize2D32f s((float)sz.width, (float)sz.height); -#endif - return s; -} -#endif - - -/** Line iterator state: */ -typedef struct CvLineIterator -{ - /** Pointer to the current point: */ - uchar* ptr; - - /* Bresenham algorithm state: */ - int err; - int plus_delta; - int minus_delta; - int plus_step; - int minus_step; -} -CvLineIterator; - - - -/************************************* CvSlice ******************************************/ -#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff -#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) - -typedef struct CvSlice -{ - int start_index, end_index; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSlice() __attribute__(( warning("Non-initialized variable") )) {} - template CvSlice(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - start_index = end_index = 0; - if (list.size() == 2) - { - start_index = list.begin()[0]; end_index = list.begin()[1]; - } - }; -#endif -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__) - CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} - CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } - operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } -#endif -} -CvSlice; - -CV_INLINE CvSlice cvSlice( int start, int end ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) - CvSlice slice = { start, end }; -#else - CvSlice slice(start, end); -#endif - return slice; -} - -#if defined(__cplusplus) -CV_INLINE CvSlice cvSlice(const cv::Range& r) -{ - CvSlice slice = (r.start != INT_MIN && r.end != INT_MAX) ? cvSlice(r.start, r.end) : cvSlice(0, CV_WHOLE_SEQ_END_INDEX); - return slice; -} -#endif - - -/************************************* CvScalar *****************************************/ -/** @sa Scalar_ - */ -typedef struct CvScalar -{ - double val[4]; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvScalar() __attribute__(( warning("Non-initialized variable") )) {} - CvScalar(const std::initializer_list list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - val[0] = val[1] = val[2] = val[3] = 0; - if (list.size() == 4) - { - val[0] = list.begin()[0]; val[1] = list.begin()[1]; val[2] = list.begin()[2]; val[3] = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvScalar() {} - CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } - template - CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } - template - CvScalar(const cv::Vec<_Tp, cn>& v) - { - int i; - for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; - for( ; i < 4; i++ ) val[i] = 0; - } -#endif -#ifdef __cplusplus - template - operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } -#endif -} -CvScalar; - -CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), - double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; scalar.val[1] = val1; - scalar.val[2] = val2; scalar.val[3] = val3; - return scalar; -} - -#ifdef __cplusplus -CV_INLINE CvScalar cvScalar() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} -CV_INLINE CvScalar cvScalar(const cv::Scalar& s) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = s.val[0]; - scalar.val[1] = s.val[1]; - scalar.val[2] = s.val[2]; - scalar.val[3] = s.val[3]; - return scalar; -} -#endif - -CV_INLINE CvScalar cvRealScalar( double val0 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} - -CV_INLINE CvScalar cvScalarAll( double val0123 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0123; - scalar.val[1] = val0123; - scalar.val[2] = val0123; - scalar.val[3] = val0123; - return scalar; -} - -/****************************************************************************************\ -* Dynamic Data structures * -\****************************************************************************************/ - -/******************************** Memory storage ****************************************/ - -typedef struct CvMemBlock -{ - struct CvMemBlock* prev; - struct CvMemBlock* next; -} -CvMemBlock; - -#define CV_STORAGE_MAGIC_VAL 0x42890000 - -typedef struct CvMemStorage -{ - int signature; - CvMemBlock* bottom; /**< First allocated block. */ - CvMemBlock* top; /**< Current memory block - top of the stack. */ - struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ - int block_size; /**< Block size. */ - int free_space; /**< Remaining free space in current block. */ -} -CvMemStorage; - -#define CV_IS_STORAGE(storage) \ - ((storage) != NULL && \ - (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) - - -typedef struct CvMemStoragePos -{ - CvMemBlock* top; - int free_space; -} -CvMemStoragePos; - - -/*********************************** Sequence *******************************************/ - -typedef struct CvSeqBlock -{ - struct CvSeqBlock* prev; /**< Previous sequence block. */ - struct CvSeqBlock* next; /**< Next sequence block. */ - int start_index; /**< Index of the first element in the block + */ - /**< sequence->first->start_index. */ - int count; /**< Number of elements in the block. */ - schar* data; /**< Pointer to the first element of the block. */ -} -CvSeqBlock; - - -#define CV_TREE_NODE_FIELDS(node_type) \ - int flags; /**< Miscellaneous flags. */ \ - int header_size; /**< Size of sequence header. */ \ - struct node_type* h_prev; /**< Previous sequence. */ \ - struct node_type* h_next; /**< Next sequence. */ \ - struct node_type* v_prev; /**< 2nd previous sequence. */ \ - struct node_type* v_next /**< 2nd next sequence. */ - -/** - Read/Write sequence. - Elements can be dynamically inserted to or deleted from the sequence. -*/ -#define CV_SEQUENCE_FIELDS() \ - CV_TREE_NODE_FIELDS(CvSeq); \ - int total; /**< Total number of elements. */ \ - int elem_size; /**< Size of sequence element in bytes. */ \ - schar* block_max; /**< Maximal bound of the last block. */ \ - schar* ptr; /**< Current write pointer. */ \ - int delta_elems; /**< Grow seq this many at a time. */ \ - CvMemStorage* storage; /**< Where the seq is stored. */ \ - CvSeqBlock* free_blocks; /**< Free blocks list. */ \ - CvSeqBlock* first; /**< Pointer to the first sequence block. */ - -typedef struct CvSeq -{ - CV_SEQUENCE_FIELDS() -} -CvSeq; - -#define CV_TYPE_NAME_SEQ "opencv-sequence" -#define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" - -/*************************************** Set ********************************************/ -/** @brief Set - Order is not preserved. There can be gaps between sequence elements. - After the element has been inserted it stays in the same place all the time. - The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. -*/ -#define CV_SET_ELEM_FIELDS(elem_type) \ - int flags; \ - struct elem_type* next_free; - -typedef struct CvSetElem -{ - CV_SET_ELEM_FIELDS(CvSetElem) -} -CvSetElem; - -#define CV_SET_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvSetElem* free_elems; \ - int active_count; - -typedef struct CvSet -{ - CV_SET_FIELDS() -} -CvSet; - - -#define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) -#define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) - -/** Checks whether the element pointed by ptr belongs to a set or not */ -#define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) - -/************************************* Graph ********************************************/ - -/** @name Graph - -We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, -pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in -another set. There is a singly-linked list of incoming/outcoming edges for each vertex. - -Each edge consists of: - -- Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). - - A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not -distinguished during search operations. - -- Two pointers to next edges for the starting and ending vertices, where next[0] points to the -next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] -adjacency list. - -@see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph -@{ -*/ -#define CV_GRAPH_EDGE_FIELDS() \ - int flags; \ - float weight; \ - struct CvGraphEdge* next[2]; \ - struct CvGraphVtx* vtx[2]; - - -#define CV_GRAPH_VERTEX_FIELDS() \ - int flags; \ - struct CvGraphEdge* first; - - -typedef struct CvGraphEdge -{ - CV_GRAPH_EDGE_FIELDS() -} -CvGraphEdge; - -typedef struct CvGraphVtx -{ - CV_GRAPH_VERTEX_FIELDS() -} -CvGraphVtx; - -typedef struct CvGraphVtx2D -{ - CV_GRAPH_VERTEX_FIELDS() - CvPoint2D32f* ptr; -} -CvGraphVtx2D; - -/** - Graph is "derived" from the set (this is set a of vertices) - and includes another set (edges) -*/ -#define CV_GRAPH_FIELDS() \ - CV_SET_FIELDS() \ - CvSet* edges; - -typedef struct CvGraph -{ - CV_GRAPH_FIELDS() -} -CvGraph; - -#define CV_TYPE_NAME_GRAPH "opencv-graph" - -/** @} */ - -/*********************************** Chain/Contour *************************************/ - -typedef struct CvChain -{ - CV_SEQUENCE_FIELDS() - CvPoint origin; -} -CvChain; - -#define CV_CONTOUR_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvRect rect; \ - int color; \ - int reserved[3]; - -typedef struct CvContour -{ - CV_CONTOUR_FIELDS() -} -CvContour; - -typedef CvContour CvPoint2DSeq; - -/****************************************************************************************\ -* Sequence types * -\****************************************************************************************/ - -#define CV_SEQ_MAGIC_VAL 0x42990000 - -#define CV_IS_SEQ(seq) \ - ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) - -#define CV_SET_MAGIC_VAL 0x42980000 -#define CV_IS_SET(set) \ - ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) - -#define CV_SEQ_ELTYPE_BITS 12 -#define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) - -#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ -#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ -#define CV_SEQ_ELTYPE_GENERIC 0 -#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) -#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ -#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ -#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ -#define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ -#define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ -#define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ -#define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ - -#define CV_SEQ_KIND_BITS 2 -#define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) -#define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) - -/** flag checking */ -#define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) - -#define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) -#define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) -#define CV_IS_SEQ_CONVEX( seq ) 0 -#define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) -#define CV_IS_SEQ_SIMPLE( seq ) 1 - -/** type checking macros */ -#define CV_IS_SEQ_POINT_SET( seq ) \ - ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) - -#define CV_IS_SEQ_POINT_SUBSET( seq ) \ - (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) - -#define CV_IS_SEQ_POLYLINE( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) - -#define CV_IS_SEQ_POLYGON( seq ) \ - (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) - -#define CV_IS_SEQ_CHAIN( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) - -#define CV_IS_SEQ_CONTOUR( seq ) \ - (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) - -#define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ - (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) - -#define CV_IS_SEQ_POLYGON_TREE( seq ) \ - (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ - CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) - -#define CV_IS_GRAPH( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) - -#define CV_IS_GRAPH_ORIENTED( seq ) \ - (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) - -#define CV_IS_SUBDIV2D( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) - -/****************************************************************************************/ -/* Sequence writer & reader */ -/****************************************************************************************/ - -#define CV_SEQ_WRITER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< the sequence written */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to free space */ \ - schar* block_min; /**< pointer to the beginning of block*/\ - schar* block_max; /**< pointer to the end of block */ - -typedef struct CvSeqWriter -{ - CV_SEQ_WRITER_FIELDS() -} -CvSeqWriter; - - -#define CV_SEQ_READER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< sequence, beign read */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to element be read next */ \ - schar* block_min; /**< pointer to the beginning of block */\ - schar* block_max; /**< pointer to the end of block */ \ - int delta_index;/**< = seq->first->start_index */ \ - schar* prev_elem; /**< pointer to previous element */ - -typedef struct CvSeqReader -{ - CV_SEQ_READER_FIELDS() -} -CvSeqReader; - -/****************************************************************************************/ -/* Operations on sequences */ -/****************************************************************************************/ - -#define CV_SEQ_ELEM( seq, elem_type, index ) \ -/** assert gives some guarantee that parameter is valid */ \ -( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ - (seq)->elem_size == sizeof(elem_type)), \ - (elem_type*)((seq)->first && (unsigned)index < \ - (unsigned)((seq)->first->count) ? \ - (seq)->first->data + (index) * sizeof(elem_type) : \ - cvGetSeqElem( (CvSeq*)(seq), (index) ))) -#define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) - -/** Add element to sequence: */ -#define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ -{ \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ - (writer).ptr += (writer).seq->elem_size; \ -} - -#define CV_WRITE_SEQ_ELEM( elem, writer ) \ -{ \ - assert( (writer).seq->elem_size == sizeof(elem)); \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ - memcpy((writer).ptr, &(elem), sizeof(elem)); \ - (writer).ptr += sizeof(elem); \ -} - - -/** Move reader position forward: */ -#define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ - { \ - cvChangeSeqBlock( &(reader), 1 ); \ - } \ -} - - -/** Move reader position backward: */ -#define CV_PREV_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ - { \ - cvChangeSeqBlock( &(reader), -1 ); \ - } \ -} - -/** Read element and move read position forward: */ -#define CV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy( &(elem), (reader).ptr, sizeof((elem))); \ - CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ -} - -/** Read element and move read position backward: */ -#define CV_REV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy(&(elem), (reader).ptr, sizeof((elem))); \ - CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ -} - - -#define CV_READ_CHAIN_POINT( _pt, reader ) \ -{ \ - (_pt) = (reader).pt; \ - if( (reader).ptr ) \ - { \ - CV_READ_SEQ_ELEM( (reader).code, (reader)); \ - assert( ((reader).code & ~7) == 0 ); \ - (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ - (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ - } \ -} - -#define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) -#define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) - -#define CV_READ_EDGE( pt1, pt2, reader ) \ -{ \ - assert( sizeof(pt1) == sizeof(CvPoint) && \ - sizeof(pt2) == sizeof(CvPoint) && \ - reader.seq->elem_size == sizeof(CvPoint)); \ - (pt1) = CV_PREV_POINT( reader ); \ - (pt2) = CV_CURRENT_POINT( reader ); \ - (reader).prev_elem = (reader).ptr; \ - CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ -} - -/************ Graph macros ************/ - -/** Return next graph edge for given vertex: */ -#define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ - (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ - (edge)->next[(edge)->vtx[1] == (vertex)]) - - -/** @} */ - -#endif /*OPENCV_CORE_TYPES_H*/ - -/* End of file. */ diff --git a/modules/core/src/alloc.cpp b/modules/core/src/alloc.cpp index f6abeeb098..7221fc12e6 100644 --- a/modules/core/src/alloc.cpp +++ b/modules/core/src/alloc.cpp @@ -236,15 +236,4 @@ void fastFree(void* ptr) #endif // OPENCV_ALLOC_ENABLE_STATISTICS } // namespace - -CV_IMPL void* cvAlloc( size_t size ) -{ - return cv::fastMalloc( size ); -} - -CV_IMPL void cvFree_( void* ptr ) -{ - cv::fastFree( ptr ); -} - /* End of file. */ diff --git a/modules/core/src/arithm.cpp b/modules/core/src/arithm.cpp index 30f57c17fc..9ac11ed0b9 100644 --- a/modules/core/src/arithm.cpp +++ b/modules/core/src/arithm.cpp @@ -2233,168 +2233,4 @@ void cv::inRange(InputArray _src, InputArray _lowerb, } } } - - -#ifndef OPENCV_EXCLUDE_C_API - -/****************************************************************************************\ -* Earlier API: cvAdd etc. * -\****************************************************************************************/ - -CV_IMPL void -cvNot( const CvArr* srcarr, CvArr* dstarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.size == dst.size && src.type() == dst.type() ); - cv::bitwise_not( src, dst ); -} - - -CV_IMPL void -cvAnd( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_and( src1, src2, dst, mask ); -} - - -CV_IMPL void -cvOr( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_or( src1, src2, dst, mask ); -} - - -CV_IMPL void -cvXor( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_xor( src1, src2, dst, mask ); -} - - -CV_IMPL void -cvAndS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src.size == dst.size && src.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_and( src, (const cv::Scalar&)s, dst, mask ); -} - - -CV_IMPL void -cvOrS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src.size == dst.size && src.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_or( src, (const cv::Scalar&)s, dst, mask ); -} - - -CV_IMPL void -cvXorS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src.size == dst.size && src.type() == dst.type() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::bitwise_xor( src, (const cv::Scalar&)s, dst, mask ); -} - - -CV_IMPL void cvAdd( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::add( src1, src2, dst, mask, dst.type() ); -} - - -CV_IMPL void cvSub( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::subtract( src1, src2, dst, mask, dst.type() ); -} - - -CV_IMPL void cvAddS( const CvArr* srcarr1, CvScalar value, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::add( src1, (const cv::Scalar&)value, dst, mask, dst.type() ); -} - - -CV_IMPL void cvSubRS( const CvArr* srcarr1, CvScalar value, CvArr* dstarr, const CvArr* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() ); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::subtract( (const cv::Scalar&)value, src1, dst, mask, dst.type() ); -} - - -CV_IMPL void cvMul( const CvArr* srcarr1, const CvArr* srcarr2, - CvArr* dstarr, double scale ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr); - CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() ); - cv::multiply( src1, src2, dst, scale, dst.type() ); -} - - -CV_IMPL void cvDiv( const CvArr* srcarr1, const CvArr* srcarr2, - CvArr* dstarr, double scale ) -{ - cv::Mat src2 = cv::cvarrToMat(srcarr2), - dst = cv::cvarrToMat(dstarr), mask; - CV_Assert( src2.size == dst.size && src2.channels() == dst.channels() ); - - if( srcarr1 ) - cv::divide( cv::cvarrToMat(srcarr1), src2, dst, scale, dst.type() ); - else - cv::divide( scale, src2, dst, dst.type() ); -} - - -CV_IMPL void -cvCmpS( const void* srcarr1, double value, void* dstarr, int cmp_op ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr); - CV_Assert( src1.size == dst.size && dst.type() == CV_8U ); - - cv::compare( src1, value, dst, cmp_op ); -} - -#endif // OPENCV_EXCLUDE_C_API /* End of file. */ diff --git a/modules/core/src/array.cpp b/modules/core/src/array.cpp deleted file mode 100644 index b0e979b37f..0000000000 --- a/modules/core/src/array.cpp +++ /dev/null @@ -1,2787 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* //////////////////////////////////////////////////////////////////// -// -// CvMat, CvMatND, CvSparceMat and IplImage support functions -// (creation, deletion, copying, retrieving and setting elements etc.) -// -// */ - -#include "precomp.hpp" - -#ifndef OPENCV_EXCLUDE_C_API - -#define CV_ORIGIN_TL 0 -#define CV_ORIGIN_BL 1 - -/* default image row align (in bytes) */ -#define CV_DEFAULT_IMAGE_ROW_ALIGN 4 - - -static struct -{ - Cv_iplCreateImageHeader createHeader; - Cv_iplAllocateImageData allocateData; - Cv_iplDeallocate deallocate; - Cv_iplCreateROI createROI; - Cv_iplCloneImage cloneImage; -} -CvIPL; - -// Makes the library use native IPL image allocators -CV_IMPL void -cvSetIPLAllocators( Cv_iplCreateImageHeader createHeader, - Cv_iplAllocateImageData allocateData, - Cv_iplDeallocate deallocate, - Cv_iplCreateROI createROI, - Cv_iplCloneImage cloneImage ) -{ - int count = (createHeader != 0) + (allocateData != 0) + (deallocate != 0) + - (createROI != 0) + (cloneImage != 0); - - if( count != 0 && count != 5 ) - CV_Error( cv::Error::StsBadArg, "Either all the pointers should be null or " - "they all should be non-null" ); - - CvIPL.createHeader = createHeader; - CvIPL.allocateData = allocateData; - CvIPL.deallocate = deallocate; - CvIPL.createROI = createROI; - CvIPL.cloneImage = cloneImage; -} - - -/****************************************************************************************\ -* CvMat creation and basic operations * -\****************************************************************************************/ - -// Creates CvMat and underlying data -CV_IMPL CvMat* -cvCreateMat( int height, int width, int type ) -{ - CvMat* arr = cvCreateMatHeader( height, width, type ); - cvCreateData( arr ); - - return arr; -} - - -static void icvCheckHuge( CvMat* arr ) -{ - if( (int64)arr->step*arr->rows > INT_MAX ) - arr->type &= ~CV_MAT_CONT_FLAG; -} - -// Creates CvMat header only -CV_IMPL CvMat* -cvCreateMatHeader( int rows, int cols, int type ) -{ - type = CV_MAT_TYPE(type); - - if( rows < 0 || cols < 0 ) - CV_Error( cv::Error::StsBadSize, "Non-positive width or height" ); - - int min_step = CV_ELEM_SIZE(type); - if( min_step <= 0 ) - CV_Error( cv::Error::StsUnsupportedFormat, "Invalid matrix type" ); - min_step *= cols; - - CvMat* arr = (CvMat*)cvAlloc( sizeof(*arr)); - - arr->step = min_step; - arr->type = CV_MAT_MAGIC_VAL | type | CV_MAT_CONT_FLAG; - arr->rows = rows; - arr->cols = cols; - arr->data.ptr = 0; - arr->refcount = 0; - arr->hdr_refcount = 1; - - icvCheckHuge( arr ); - return arr; -} - - -// Initializes CvMat header, allocated by the user -CV_IMPL CvMat* -cvInitMatHeader( CvMat* arr, int rows, int cols, - int type, void* data, int step ) -{ - if( !arr ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( (unsigned)CV_MAT_DEPTH(type) > CV_DEPTH_MAX ) - CV_Error( cv::Error::BadNumChannels, "" ); - - if( rows < 0 || cols < 0 ) - CV_Error( cv::Error::StsBadSize, "Non-positive cols or rows" ); - - type = CV_MAT_TYPE( type ); - arr->type = type | CV_MAT_MAGIC_VAL; - arr->rows = rows; - arr->cols = cols; - arr->data.ptr = (uchar*)data; - arr->refcount = 0; - arr->hdr_refcount = 0; - - int pix_size = CV_ELEM_SIZE(type); - int min_step = arr->cols*pix_size; - - if( step != CV_AUTOSTEP && step != 0 ) - { - if( step < min_step ) - CV_Error( cv::Error::BadStep, "" ); - arr->step = step; - } - else - { - arr->step = min_step; - } - - arr->type = CV_MAT_MAGIC_VAL | type | - (arr->rows == 1 || arr->step == min_step ? CV_MAT_CONT_FLAG : 0); - - icvCheckHuge( arr ); - return arr; -} - - -// Deallocates the CvMat structure and underlying data -CV_IMPL void -cvReleaseMat( CvMat** array ) -{ - if( !array ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - if( *array ) - { - CvMat* arr = *array; - - if( !CV_IS_MAT_HDR_Z(arr) && !CV_IS_MATND_HDR(arr) ) - CV_Error( cv::Error::StsBadFlag, "" ); - - *array = 0; - - cvDecRefData( arr ); - cvFree( &arr ); - } -} - - -// Creates a copy of matrix -CV_IMPL CvMat* -cvCloneMat( const CvMat* src ) -{ - if( !CV_IS_MAT_HDR( src )) - CV_Error( cv::Error::StsBadArg, "Bad CvMat header" ); - - CvMat* dst = cvCreateMatHeader( src->rows, src->cols, src->type ); - - if( src->data.ptr ) - { - cvCreateData( dst ); - cvCopy( src, dst ); - } - - return dst; -} - - -/****************************************************************************************\ -* CvMatND creation and basic operations * -\****************************************************************************************/ - -CV_IMPL CvMatND* -cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, - int type, void* data ) -{ - type = CV_MAT_TYPE(type); - int64 esz = CV_ELEM_SIZE(type), step = esz; - - if( !mat ) - CV_Error( cv::Error::StsNullPtr, "NULL matrix header pointer" ); - - if( step == 0 ) - CV_Error( cv::Error::StsUnsupportedFormat, "invalid array data type" ); - - if( !sizes ) - CV_Error( cv::Error::StsNullPtr, "NULL pointer" ); - - if( dims <= 0 || dims > CV_MAX_DIM ) - CV_Error( cv::Error::StsOutOfRange, - "non-positive or too large number of dimensions" ); - - for( int i = dims - 1; i >= 0; i-- ) - { - if( sizes[i] < 0 ) - CV_Error( cv::Error::StsBadSize, "one of dimension sizes is non-positive" ); - mat->dim[i].size = sizes[i]; - if( step > INT_MAX ) - CV_Error( cv::Error::StsOutOfRange, "The array is too big" ); - mat->dim[i].step = (int)step; - step *= sizes[i]; - } - - mat->type = CV_MATND_MAGIC_VAL | (step <= INT_MAX ? CV_MAT_CONT_FLAG : 0) | type; - mat->dims = dims; - if (dims < 2) { - mat->dims = 2; - mat->dim[1].size = dims == 0 ? 1 : mat->dim[0].size; - mat->dim[1].step = (int)esz; - mat->dim[0].size = 1; - mat->dim[0].step = (int)(mat->dim[1].size*esz); - } - mat->data.ptr = (uchar*)data; - mat->refcount = 0; - mat->hdr_refcount = 0; - return mat; -} - - -// Creates CvMatND and underlying data -CV_IMPL CvMatND* -cvCreateMatND( int dims, const int* sizes, int type ) -{ - CvMatND* arr = cvCreateMatNDHeader( dims, sizes, type ); - cvCreateData( arr ); - - return arr; -} - - -// Creates CvMatND header only -CV_IMPL CvMatND* -cvCreateMatNDHeader( int dims, const int* sizes, int type ) -{ - if( dims <= 0 || dims > CV_MAX_DIM ) - CV_Error( cv::Error::StsOutOfRange, - "non-positive or too large number of dimensions" ); - - CvMatND* arr = (CvMatND*)cvAlloc( sizeof(*arr) ); - - cvInitMatNDHeader( arr, dims, sizes, type, 0 ); - arr->hdr_refcount = 1; - return arr; -} - - -// Creates a copy of nD array -CV_IMPL CvMatND* -cvCloneMatND( const CvMatND* src ) -{ - if( !CV_IS_MATND_HDR( src )) - CV_Error( cv::Error::StsBadArg, "Bad CvMatND header" ); - - CV_Assert( src->dims <= CV_MAX_DIM ); - int sizes[CV_MAX_DIM]; - - for( int i = 0; i < src->dims; i++ ) - sizes[i] = src->dim[i].size; - - CvMatND* dst = cvCreateMatNDHeader( src->dims, sizes, src->type ); - - if( src->data.ptr ) - { - cvCreateData( dst ); - cv::Mat _src = cv::cvarrToMat(src); - cv::Mat _dst = cv::cvarrToMat(dst); - uchar* data0 = dst->data.ptr; - _src.copyTo(_dst); - CV_Assert(_dst.data == data0); - //cvCopy( src, dst ); - } - - return dst; -} - - -/****************************************************************************************\ -* CvSparseMat creation and basic operations * -\****************************************************************************************/ - - -// Creates CvMatND and underlying data -CV_IMPL CvSparseMat* -cvCreateSparseMat( int dims, const int* sizes, int type ) -{ - type = CV_MAT_TYPE( type ); - int pix_size1 = CV_ELEM_SIZE1(type); - int pix_size = pix_size1*CV_MAT_CN(type); - int i, size; - CvMemStorage* storage; - - if( pix_size == 0 ) - CV_Error( cv::Error::StsUnsupportedFormat, "invalid array data type" ); - - if( dims <= 0 || dims > CV_MAX_DIM ) - CV_Error( cv::Error::StsOutOfRange, "bad number of dimensions" ); - - if( !sizes ) - CV_Error( cv::Error::StsNullPtr, "NULL pointer" ); - - for( i = 0; i < dims; i++ ) - { - if( sizes[i] <= 0 ) - CV_Error( cv::Error::StsBadSize, "one of dimension sizes is non-positive" ); - } - - CvSparseMat* arr = (CvSparseMat*)cvAlloc(sizeof(*arr)+MAX(0,dims-CV_MAX_DIM)*sizeof(arr->size[0])); - - arr->type = CV_SPARSE_MAT_MAGIC_VAL | type; - arr->dims = dims; - arr->refcount = 0; - arr->hdr_refcount = 1; - memcpy( arr->size, sizes, dims*sizeof(sizes[0])); - - arr->valoffset = (int)cvAlign(sizeof(CvSparseNode), pix_size1); - arr->idxoffset = (int)cvAlign(arr->valoffset + pix_size, sizeof(int)); - size = (int)cvAlign(arr->idxoffset + dims*sizeof(int), sizeof(CvSetElem)); - - storage = cvCreateMemStorage( CV_SPARSE_MAT_BLOCK ); - arr->heap = cvCreateSet( 0, sizeof(CvSet), size, storage ); - - arr->hashsize = CV_SPARSE_HASH_SIZE0; - size = arr->hashsize*sizeof(arr->hashtable[0]); - - arr->hashtable = (void**)cvAlloc( size ); - memset( arr->hashtable, 0, size ); - - return arr; -} - - -// Creates CvMatND and underlying data -CV_IMPL void -cvReleaseSparseMat( CvSparseMat** array ) -{ - if( !array ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - if( *array ) - { - CvSparseMat* arr = *array; - - if( !CV_IS_SPARSE_MAT_HDR(arr) ) - CV_Error( cv::Error::StsBadFlag, "" ); - - *array = 0; - - CvMemStorage* storage = arr->heap->storage; - cvReleaseMemStorage( &storage ); - cvFree( &arr->hashtable ); - cvFree( &arr ); - } -} - - -// Creates CvMatND and underlying data -CV_IMPL CvSparseMat* -cvCloneSparseMat( const CvSparseMat* src ) -{ - if( !CV_IS_SPARSE_MAT_HDR(src) ) - CV_Error( cv::Error::StsBadArg, "Invalid sparse array header" ); - - CvSparseMat* dst = cvCreateSparseMat( src->dims, src->size, src->type ); - cvCopy( src, dst ); - return dst; -} - - -CvSparseNode* -cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* iterator ) -{ - CvSparseNode* node = 0; - int idx; - - if( !CV_IS_SPARSE_MAT( mat )) - CV_Error( cv::Error::StsBadArg, "Invalid sparse matrix header" ); - - if( !iterator ) - CV_Error( cv::Error::StsNullPtr, "NULL iterator pointer" ); - - iterator->mat = (CvSparseMat*)mat; - iterator->node = 0; - - for( idx = 0; idx < mat->hashsize; idx++ ) - if( mat->hashtable[idx] ) - { - node = iterator->node = (CvSparseNode*)mat->hashtable[idx]; - break; - } - - iterator->curidx = idx; - return node; -} - -#define ICV_SPARSE_MAT_HASH_MULTIPLIER cv::SparseMat::HASH_SCALE - -static uchar* -icvGetNodePtr( CvSparseMat* mat, const int* idx, int* _type, - int create_node, unsigned* precalc_hashval ) -{ - uchar* ptr = 0; - int i, tabidx; - unsigned hashval = 0; - CvSparseNode *node; - CV_Assert( CV_IS_SPARSE_MAT( mat )); - - if( !precalc_hashval ) - { - for( i = 0; i < mat->dims; i++ ) - { - int t = idx[i]; - if( (unsigned)t >= (unsigned)mat->size[i] ) - CV_Error( cv::Error::StsOutOfRange, "One of indices is out of range" ); - hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t; - } - } - else - { - hashval = *precalc_hashval; - } - - tabidx = hashval & (mat->hashsize - 1); - hashval &= INT_MAX; - - if( create_node >= -1 ) - { - for( node = (CvSparseNode*)mat->hashtable[tabidx]; - node != 0; node = node->next ) - { - if( node->hashval == hashval ) - { - int* nodeidx = CV_NODE_IDX(mat,node); - for( i = 0; i < mat->dims; i++ ) - if( idx[i] != nodeidx[i] ) - break; - if( i == mat->dims ) - { - ptr = (uchar*)CV_NODE_VAL(mat,node); - break; - } - } - } - } - - if( !ptr && create_node ) - { - if( mat->heap->active_count >= mat->hashsize*CV_SPARSE_HASH_RATIO ) - { - void** newtable; - int newsize = MAX( mat->hashsize*2, CV_SPARSE_HASH_SIZE0); - int newrawsize = newsize*sizeof(newtable[0]); - - CvSparseMatIterator iterator; - CV_Assert( (newsize & (newsize - 1)) == 0 ); - - // resize hash table - newtable = (void**)cvAlloc( newrawsize ); - memset( newtable, 0, newrawsize ); - - node = cvInitSparseMatIterator( mat, &iterator ); - while( node ) - { - CvSparseNode* next = cvGetNextSparseNode( &iterator ); - int newidx = node->hashval & (newsize - 1); - node->next = (CvSparseNode*)newtable[newidx]; - newtable[newidx] = node; - node = next; - } - - cvFree( &mat->hashtable ); - mat->hashtable = newtable; - mat->hashsize = newsize; - tabidx = hashval & (newsize - 1); - } - - node = (CvSparseNode*)cvSetNew( mat->heap ); - node->hashval = hashval; - node->next = (CvSparseNode*)mat->hashtable[tabidx]; - mat->hashtable[tabidx] = node; - memcpy(CV_NODE_IDX(mat,node), idx, mat->dims*sizeof(idx[0])); - ptr = (uchar*)CV_NODE_VAL(mat,node); - if( create_node > 0 ) - memset( ptr, 0, CV_ELEM_SIZE(mat->type)); - } - - if( _type ) - *_type = CV_MAT_TYPE(mat->type); - - return ptr; -} - - -static void -icvDeleteNode( CvSparseMat* mat, const int* idx, unsigned* precalc_hashval ) -{ - int i, tabidx; - unsigned hashval = 0; - CvSparseNode *node, *prev = 0; - CV_Assert( CV_IS_SPARSE_MAT( mat )); - - if( !precalc_hashval ) - { - for( i = 0; i < mat->dims; i++ ) - { - int t = idx[i]; - if( (unsigned)t >= (unsigned)mat->size[i] ) - CV_Error( cv::Error::StsOutOfRange, "One of indices is out of range" ); - hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t; - } - } - else - { - hashval = *precalc_hashval; - } - - tabidx = hashval & (mat->hashsize - 1); - hashval &= INT_MAX; - - for( node = (CvSparseNode*)mat->hashtable[tabidx]; - node != 0; prev = node, node = node->next ) - { - if( node->hashval == hashval ) - { - int* nodeidx = CV_NODE_IDX(mat,node); - for( i = 0; i < mat->dims; i++ ) - if( idx[i] != nodeidx[i] ) - break; - if( i == mat->dims ) - break; - } - } - - if( node ) - { - if( prev ) - prev->next = node->next; - else - mat->hashtable[tabidx] = node->next; - cvSetRemoveByPtr( mat->heap, node ); - } -} - - -/****************************************************************************************\ -* Common for multiple array types operations * -\****************************************************************************************/ - -// Allocates underlying array data -CV_IMPL void -cvCreateData( CvArr* arr ) -{ - if( CV_IS_MAT_HDR_Z( arr )) - { - size_t step, total_size; - CvMat* mat = (CvMat*)arr; - step = mat->step; - - if( mat->rows == 0 || mat->cols == 0 ) - return; - - if( mat->data.ptr != 0 ) - CV_Error( cv::Error::StsError, "Data is already allocated" ); - - if( step == 0 ) - step = CV_ELEM_SIZE(mat->type)*mat->cols; - - int64 _total_size = (int64)step*mat->rows + sizeof(int) + CV_MALLOC_ALIGN; - total_size = (size_t)_total_size; - if(_total_size != (int64)total_size) - CV_Error(cv::Error::StsNoMem, "Too big buffer is allocated" ); - mat->refcount = (int*)cvAlloc( (size_t)total_size ); - mat->data.ptr = (uchar*)cvAlignPtr( mat->refcount + 1, CV_MALLOC_ALIGN ); - *mat->refcount = 1; - } - else if( CV_IS_IMAGE_HDR(arr)) - { - IplImage* img = (IplImage*)arr; - - if( img->imageData != 0 ) - CV_Error( cv::Error::StsError, "Data is already allocated" ); - - if( !CvIPL.allocateData ) - { - const int64 imageSize_tmp = (int64)img->widthStep*(int64)img->height; - if( (int64)img->imageSize != imageSize_tmp ) - CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" ); - img->imageData = img->imageDataOrigin = - (char*)cvAlloc( (size_t)img->imageSize ); - } - else - { - int depth = img->depth; - int width = img->width; - - if( img->depth == IPL_DEPTH_32F || img->depth == IPL_DEPTH_64F ) - { - img->width *= img->depth == IPL_DEPTH_32F ? sizeof(float) : sizeof(double); - img->depth = IPL_DEPTH_8U; - } - - CvIPL.allocateData( img, 0, 0 ); - - img->width = width; - img->depth = depth; - } - } - else if( CV_IS_MATND_HDR( arr )) - { - CvMatND* mat = (CvMatND*)arr; - size_t total_size = CV_ELEM_SIZE(mat->type); - - if( mat->dim[0].size == 0 ) - return; - - if( mat->data.ptr != 0 ) - CV_Error( cv::Error::StsError, "Data is already allocated" ); - - if( CV_IS_MAT_CONT( mat->type )) - { - total_size = (size_t)mat->dim[0].size*(mat->dim[0].step != 0 ? - (size_t)mat->dim[0].step : total_size); - } - else - { - int i; - for( i = mat->dims - 1; i >= 0; i-- ) - { - size_t size = (size_t)mat->dim[i].step*mat->dim[i].size; - - if( total_size < size ) - total_size = size; - } - } - - mat->refcount = (int*)cvAlloc( total_size + - sizeof(int) + CV_MALLOC_ALIGN ); - mat->data.ptr = (uchar*)cvAlignPtr( mat->refcount + 1, CV_MALLOC_ALIGN ); - *mat->refcount = 1; - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); -} - - -// Assigns external data to array -CV_IMPL void -cvSetData( CvArr* arr, void* data, int step ) -{ - int pix_size, min_step; - - if( CV_IS_MAT_HDR(arr) || CV_IS_MATND_HDR(arr) ) - cvReleaseData( arr ); - - if( CV_IS_MAT_HDR( arr )) - { - CvMat* mat = (CvMat*)arr; - - int type = CV_MAT_TYPE(mat->type); - pix_size = CV_ELEM_SIZE(type); - min_step = mat->cols*pix_size; - - if( step != CV_AUTOSTEP && step != 0 ) - { - if( step < min_step && data != 0 ) - CV_Error( cv::Error::BadStep, "" ); - mat->step = step; - } - else - mat->step = min_step; - - mat->data.ptr = (uchar*)data; - mat->type = CV_MAT_MAGIC_VAL | type | - (mat->rows == 1 || mat->step == min_step ? CV_MAT_CONT_FLAG : 0); - icvCheckHuge( mat ); - } - else if( CV_IS_IMAGE_HDR( arr )) - { - IplImage* img = (IplImage*)arr; - - pix_size = ((img->depth & 255) >> 3)*img->nChannels; - min_step = img->width*pix_size; - - if( step != CV_AUTOSTEP && img->height > 1 ) - { - if( step < min_step && data != 0 ) - CV_Error( cv::Error::BadStep, "" ); - img->widthStep = step; - } - else - { - img->widthStep = min_step; - } - - const int64 imageSize_tmp = (int64)img->widthStep*(int64)img->height; - img->imageSize = (int)imageSize_tmp; - if( (int64)img->imageSize != imageSize_tmp ) - CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" ); - img->imageData = img->imageDataOrigin = (char*)data; - - if( (((int)(size_t)data | step) & 7) == 0 && - cvAlign(img->width * pix_size, 8) == step ) - img->align = 8; - else - img->align = 4; - } - else if( CV_IS_MATND_HDR( arr )) - { - CvMatND* mat = (CvMatND*)arr; - int i; - int64 cur_step; - - if( step != CV_AUTOSTEP ) - CV_Error( cv::Error::BadStep, - "For multidimensional array only CV_AUTOSTEP is allowed here" ); - - mat->data.ptr = (uchar*)data; - cur_step = CV_ELEM_SIZE(mat->type); - - for( i = mat->dims - 1; i >= 0; i-- ) - { - if( cur_step > INT_MAX ) - CV_Error( cv::Error::StsOutOfRange, "The array is too big" ); - mat->dim[i].step = (int)cur_step; - cur_step *= mat->dim[i].size; - } - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); -} - - -// Deallocates array's data -CV_IMPL void -cvReleaseData( CvArr* arr ) -{ - if( CV_IS_MAT_HDR( arr ) || CV_IS_MATND_HDR( arr )) - { - CvMat* mat = (CvMat*)arr; - cvDecRefData( mat ); - } - else if( CV_IS_IMAGE_HDR( arr )) - { - IplImage* img = (IplImage*)arr; - - if( !CvIPL.deallocate ) - { - char* ptr = img->imageDataOrigin; - img->imageData = img->imageDataOrigin = 0; - cvFree( &ptr ); - } - else - { - CvIPL.deallocate( img, IPL_IMAGE_DATA ); - } - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); -} - -static inline cv::Size cvGetMatSize( const CvMat* mat ) -{ - return cv::Size(mat->cols, mat->rows); -} - -// Retrieves essential information about image ROI or CvMat data -CV_IMPL void -cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size ) -{ - if( CV_IS_MAT( arr )) - { - CvMat *mat = (CvMat*)arr; - - if( step ) - *step = mat->step; - - if( data ) - *data = mat->data.ptr; - - if( roi_size ) - *roi_size = cvSize(cvGetMatSize( mat )); - } - else if( CV_IS_IMAGE( arr )) - { - IplImage* img = (IplImage*)arr; - - if( step ) - *step = img->widthStep; - - if( data ) - *data = cvPtr2D( img, 0, 0 ); - - if( roi_size ) - { - if( img->roi ) - { - *roi_size = cvSize( img->roi->width, img->roi->height ); - } - else - { - *roi_size = cvSize( img->width, img->height ); - } - } - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - - if( !CV_IS_MAT_CONT( mat->type )) - CV_Error( cv::Error::StsBadArg, "Only continuous nD arrays are supported here" ); - - if( data ) - *data = mat->data.ptr; - - if( roi_size || step ) - { - if( roi_size ) - { - int size1 = mat->dim[0].size, size2 = 1; - - if( mat->dims > 2 ) - { - int i; - for( i = 1; i < mat->dims; i++ ) - size1 *= mat->dim[i].size; - } - else - size2 = mat->dim[1].size; - - roi_size->width = size2; - roi_size->height = size1; - } - - if( step ) - *step = mat->dim[0].step; - } - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); -} - - -CV_IMPL int -cvGetElemType( const CvArr* arr ) -{ - int type = -1; - if( CV_IS_MAT_HDR(arr) || CV_IS_MATND_HDR(arr) || CV_IS_SPARSE_MAT_HDR(arr)) - type = CV_MAT_TYPE( ((CvMat*)arr)->type ); - else if( CV_IS_IMAGE(arr)) - { - IplImage* img = (IplImage*)arr; - type = CV_MAKETYPE( IPL2CV_DEPTH(img->depth), img->nChannels ); - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - - return type; -} - - -// Returns a number of array dimensions -CV_IMPL int -cvGetDims( const CvArr* arr, int* sizes ) -{ - int dims = -1; - if( CV_IS_MAT_HDR( arr )) - { - CvMat* mat = (CvMat*)arr; - - dims = 2; - if( sizes ) - { - sizes[0] = mat->rows; - sizes[1] = mat->cols; - } - } - else if( CV_IS_IMAGE( arr )) - { - IplImage* img = (IplImage*)arr; - dims = 2; - - if( sizes ) - { - sizes[0] = img->height; - sizes[1] = img->width; - } - } - else if( CV_IS_MATND_HDR( arr )) - { - CvMatND* mat = (CvMatND*)arr; - dims = mat->dims; - - if( sizes ) - { - int i; - for( i = 0; i < dims; i++ ) - sizes[i] = mat->dim[i].size; - } - } - else if( CV_IS_SPARSE_MAT_HDR( arr )) - { - CvSparseMat* mat = (CvSparseMat*)arr; - dims = mat->dims; - - if( sizes ) - memcpy( sizes, mat->size, dims*sizeof(sizes[0])); - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - - return dims; -} - - -// Returns the size of particular array dimension -CV_IMPL int -cvGetDimSize( const CvArr* arr, int index ) -{ - int size = -1; - - if( CV_IS_MAT( arr )) - { - CvMat *mat = (CvMat*)arr; - - switch( index ) - { - case 0: - size = mat->rows; - break; - case 1: - size = mat->cols; - break; - default: - CV_Error( cv::Error::StsOutOfRange, "bad dimension index" ); - } - } - else if( CV_IS_IMAGE( arr )) - { - IplImage* img = (IplImage*)arr; - - switch( index ) - { - case 0: - size = !img->roi ? img->height : img->roi->height; - break; - case 1: - size = !img->roi ? img->width : img->roi->width; - break; - default: - CV_Error( cv::Error::StsOutOfRange, "bad dimension index" ); - } - } - else if( CV_IS_MATND_HDR( arr )) - { - CvMatND* mat = (CvMatND*)arr; - - if( (unsigned)index >= (unsigned)mat->dims ) - CV_Error( cv::Error::StsOutOfRange, "bad dimension index" ); - - size = mat->dim[index].size; - } - else if( CV_IS_SPARSE_MAT_HDR( arr )) - { - CvSparseMat* mat = (CvSparseMat*)arr; - - if( (unsigned)index >= (unsigned)mat->dims ) - CV_Error( cv::Error::StsOutOfRange, "bad dimension index" ); - - size = mat->size[index]; - } - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - - return size; -} - - -// Returns the size of CvMat or IplImage -CV_IMPL CvSize -cvGetSize( const CvArr* arr ) -{ - CvSize size = {0, 0}; - - if( CV_IS_MAT_HDR_Z( arr )) - { - CvMat *mat = (CvMat*)arr; - - size.width = mat->cols; - size.height = mat->rows; - } - else if( CV_IS_IMAGE_HDR( arr )) - { - IplImage* img = (IplImage*)arr; - - if( img->roi ) - { - size.width = img->roi->width; - size.height = img->roi->height; - } - else - { - size.width = img->width; - size.height = img->height; - } - } - else - CV_Error( cv::Error::StsBadArg, "Array should be CvMat or IplImage" ); - - return size; -} - - -// Selects sub-array (no data is copied) -CV_IMPL CvMat* -cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ) -{ - CvMat* res = 0; - CvMat stub, *mat = (CvMat*)arr; - - if( !CV_IS_MAT( mat )) - mat = cvGetMat( mat, &stub ); - - if( !submat ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( (rect.x|rect.y|rect.width|rect.height) < 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - if( rect.x + rect.width > mat->cols || - rect.y + rect.height > mat->rows ) - CV_Error( cv::Error::StsBadSize, "" ); - - { - /* - int* refcount = mat->refcount; - - if( refcount ) - ++*refcount; - - cvDecRefData( submat ); - */ - submat->data.ptr = mat->data.ptr + (size_t)rect.y*mat->step + - rect.x*CV_ELEM_SIZE(mat->type); - submat->step = mat->step; - submat->type = (mat->type & (rect.width < mat->cols ? ~CV_MAT_CONT_FLAG : -1)) | - (rect.height <= 1 ? CV_MAT_CONT_FLAG : 0); - submat->rows = rect.height; - submat->cols = rect.width; - submat->refcount = 0; - res = submat; - } - - return res; -} - - -// Selects array's row span. -CV_IMPL CvMat* -cvGetRows( const CvArr* arr, CvMat* submat, - int start_row, int end_row, int delta_row ) -{ - CvMat* res = 0; - CvMat stub, *mat = (CvMat*)arr; - - if( !CV_IS_MAT( mat )) - mat = cvGetMat( mat, &stub ); - - if( !submat ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( (unsigned)start_row >= (unsigned)mat->rows || - (unsigned)end_row > (unsigned)mat->rows || delta_row <= 0 ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - { - /* - int* refcount = mat->refcount; - - if( refcount ) - ++*refcount; - - cvDecRefData( submat ); - */ - if( delta_row == 1 ) - { - submat->rows = end_row - start_row; - submat->step = mat->step; - } - else - { - submat->rows = (end_row - start_row + delta_row - 1)/delta_row; - submat->step = mat->step * delta_row; - } - - submat->cols = mat->cols; - submat->step &= submat->rows > 1 ? -1 : 0; - submat->data.ptr = mat->data.ptr + (size_t)start_row*mat->step; - submat->type = (mat->type | (submat->rows == 1 ? CV_MAT_CONT_FLAG : 0)) & - (delta_row != 1 && submat->rows > 1 ? ~CV_MAT_CONT_FLAG : -1); - submat->refcount = 0; - submat->hdr_refcount = 0; - res = submat; - } - - return res; -} - - -// Selects array's column span. -CV_IMPL CvMat* -cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col ) -{ - CvMat* res = 0; - CvMat stub, *mat = (CvMat*)arr; - int cols; - - if( !CV_IS_MAT( mat )) - mat = cvGetMat( mat, &stub ); - - if( !submat ) - CV_Error( cv::Error::StsNullPtr, "" ); - - cols = mat->cols; - if( (unsigned)start_col >= (unsigned)cols || - (unsigned)end_col > (unsigned)cols ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - { - /* - int* refcount = mat->refcount; - - if( refcount ) - ++*refcount; - - cvDecRefData( submat ); - */ - submat->rows = mat->rows; - submat->cols = end_col - start_col; - submat->step = mat->step; - submat->data.ptr = mat->data.ptr + (size_t)start_col*CV_ELEM_SIZE(mat->type); - submat->type = mat->type & (submat->rows > 1 && submat->cols < cols ? ~CV_MAT_CONT_FLAG : -1); - submat->refcount = 0; - submat->hdr_refcount = 0; - res = submat; - } - - return res; -} - - -/****************************************************************************************\ -* Operations on CvScalar and accessing array elements * -\****************************************************************************************/ - -// Converts CvScalar to specified type -CV_IMPL void -cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_12 ) -{ - type = CV_MAT_TYPE(type); - int cn = CV_MAT_CN( type ); - int depth = type & CV_MAT_DEPTH_MASK; - - CV_Assert( scalar && data ); - if( (unsigned)(cn - 1) >= 4 ) - CV_Error( cv::Error::StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" ); - - switch( depth ) - { - case CV_8UC1: - while( cn-- ) - { - int t = cvRound( scalar->val[cn] ); - ((uchar*)data)[cn] = cv::saturate_cast(t); - } - break; - case CV_8SC1: - while( cn-- ) - { - int t = cvRound( scalar->val[cn] ); - ((char*)data)[cn] = cv::saturate_cast(t); - } - break; - case CV_16UC1: - while( cn-- ) - { - int t = cvRound( scalar->val[cn] ); - ((ushort*)data)[cn] = cv::saturate_cast(t); - } - break; - case CV_16SC1: - while( cn-- ) - { - int t = cvRound( scalar->val[cn] ); - ((short*)data)[cn] = cv::saturate_cast(t); - } - break; - case CV_32SC1: - while( cn-- ) - ((int*)data)[cn] = cvRound( scalar->val[cn] ); - break; - case CV_32FC1: - while( cn-- ) - ((float*)data)[cn] = (float)(scalar->val[cn]); - break; - case CV_64FC1: - while( cn-- ) - ((double*)data)[cn] = (double)(scalar->val[cn]); - break; - default: - CV_Assert(0); - CV_Error( cv::Error::BadDepth, "" ); - } - - if( extend_to_12 ) - { - int pix_size = CV_ELEM_SIZE(type); - int offset = CV_ELEM_SIZE1(depth)*12; - - do - { - offset -= pix_size; - memcpy((char*)data + offset, data, pix_size); - } - while( offset > pix_size ); - } -} - - -// Converts data of specified type to CvScalar -CV_IMPL void -cvRawDataToScalar( const void* data, int flags, CvScalar* scalar ) -{ - int cn = CV_MAT_CN( flags ); - - CV_Assert( scalar && data ); - - if( (unsigned)(cn - 1) >= 4 ) - CV_Error( cv::Error::StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" ); - - memset( scalar->val, 0, sizeof(scalar->val)); - - switch( CV_MAT_DEPTH( flags )) - { - case CV_8U: - while( cn-- ) - scalar->val[cn] = CV_8TO32F(((uchar*)data)[cn]); - break; - case CV_8S: - while( cn-- ) - scalar->val[cn] = CV_8TO32F(((char*)data)[cn]); - break; - case CV_16U: - while( cn-- ) - scalar->val[cn] = ((ushort*)data)[cn]; - break; - case CV_16S: - while( cn-- ) - scalar->val[cn] = ((short*)data)[cn]; - break; - case CV_32S: - while( cn-- ) - scalar->val[cn] = ((int*)data)[cn]; - break; - case CV_32F: - while( cn-- ) - scalar->val[cn] = ((float*)data)[cn]; - break; - case CV_64F: - while( cn-- ) - scalar->val[cn] = ((double*)data)[cn]; - break; - default: - CV_Assert(0); - CV_Error( cv::Error::BadDepth, "" ); - } -} - - -static double icvGetReal( const void* data, int type ) -{ - switch( type ) - { - case CV_8U: - return *(uchar*)data; - case CV_8S: - return *(char*)data; - case CV_16U: - return *(ushort*)data; - case CV_16S: - return *(short*)data; - case CV_32S: - return *(int*)data; - case CV_32F: - return *(float*)data; - case CV_64F: - return *(double*)data; - } - - return 0; -} - - -static void icvSetReal( double value, const void* data, int type ) -{ - if( type < CV_32F ) - { - int ivalue = cvRound(value); - switch( type ) - { - case CV_8U: - *(uchar*)data = cv::saturate_cast(ivalue); - break; - case CV_8S: - *(schar*)data = cv::saturate_cast(ivalue); - break; - case CV_16U: - *(ushort*)data = cv::saturate_cast(ivalue); - break; - case CV_16S: - *(short*)data = cv::saturate_cast(ivalue); - break; - case CV_32S: - *(int*)data = cv::saturate_cast(ivalue); - break; - } - } - else - { - switch( type ) - { - case CV_32F: - *(float*)data = (float)value; - break; - case CV_64F: - *(double*)data = value; - break; - } - } -} - - -// Returns pointer to specified element of array (linear index is used) -CV_IMPL uchar* -cvPtr1D( const CvArr* arr, int idx, int* _type ) -{ - uchar* ptr = 0; - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - - int type = CV_MAT_TYPE(mat->type); - int pix_size = CV_ELEM_SIZE(type); - - if( _type ) - *_type = type; - - // the first part is mul-free sufficient check - // that the index is within the matrix - if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) && - (unsigned)idx >= (unsigned)(mat->rows*mat->cols)) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - if( CV_IS_MAT_CONT(mat->type)) - { - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else - { - int row, col; - if( mat->cols == 1 ) - row = idx, col = 0; - else - row = idx/mat->cols, col = idx - row*mat->cols; - ptr = mat->data.ptr + (size_t)row*mat->step + col*pix_size; - } - } - else if( CV_IS_IMAGE_HDR( arr )) - { - IplImage* img = (IplImage*)arr; - int width = !img->roi ? img->width : img->roi->width; - int y = idx/width, x = idx - y*width; - - ptr = cvPtr2D( arr, y, x, _type ); - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - int j, type = CV_MAT_TYPE(mat->type); - size_t size = mat->dim[0].size; - - if( _type ) - *_type = type; - - for( j = 1; j < mat->dims; j++ ) - size *= mat->dim[j].size; - - if((unsigned)idx >= (unsigned)size ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - if( CV_IS_MAT_CONT(mat->type)) - { - int pix_size = CV_ELEM_SIZE(type); - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else - { - ptr = mat->data.ptr; - for( j = mat->dims - 1; j >= 0; j-- ) - { - int sz = mat->dim[j].size; - if( sz ) - { - int t = idx/sz; - ptr += (idx - t*sz)*mat->dim[j].step; - idx = t; - } - } - } - } - else if( CV_IS_SPARSE_MAT( arr )) - { - CvSparseMat* m = (CvSparseMat*)arr; - if( m->dims == 1 ) - ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, _type, 1, 0 ); - else - { - int i, n = m->dims; - CV_DbgAssert( n <= CV_MAX_DIM ); - int _idx[CV_MAX_DIM]; - - for( i = n - 1; i >= 0; i-- ) - { - int t = idx / m->size[i]; - _idx[i] = idx - t*m->size[i]; - idx = t; - } - ptr = icvGetNodePtr( (CvSparseMat*)arr, _idx, _type, 1, 0 ); - } - } - else - { - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - } - - return ptr; -} - - -// Returns pointer to specified element of 2d array -CV_IMPL uchar* -cvPtr2D( const CvArr* arr, int y, int x, int* _type ) -{ - uchar* ptr = 0; - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - int type; - - if( (unsigned)y >= (unsigned)(mat->rows) || - (unsigned)x >= (unsigned)(mat->cols) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - type = CV_MAT_TYPE(mat->type); - if( _type ) - *_type = type; - - ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type); - } - else if( CV_IS_IMAGE( arr )) - { - IplImage* img = (IplImage*)arr; - int pix_size = (img->depth & 255) >> 3; - int width, height; - ptr = (uchar*)img->imageData; - - if( img->dataOrder == 0 ) - pix_size *= img->nChannels; - - if( img->roi ) - { - width = img->roi->width; - height = img->roi->height; - - ptr += img->roi->yOffset*img->widthStep + - img->roi->xOffset*pix_size; - - if( img->dataOrder ) - { - int coi = img->roi->coi; - if( !coi ) - CV_Error( cv::Error::BadCOI, - "COI must be non-null in case of planar images" ); - ptr += (coi - 1)*img->imageSize; - } - } - else - { - width = img->width; - height = img->height; - } - - if( (unsigned)y >= (unsigned)height || - (unsigned)x >= (unsigned)width ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr += y*img->widthStep + x*pix_size; - - if( _type ) - { - int type = IPL2CV_DEPTH(img->depth); - if( type < 0 || (unsigned)(img->nChannels - 1) > 3 ) - CV_Error( cv::Error::StsUnsupportedFormat, "" ); - - *_type = CV_MAKETYPE( type, img->nChannels ); - } - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - - if( mat->dims != 2 || - (unsigned)y >= (unsigned)(mat->dim[0].size) || - (unsigned)x >= (unsigned)(mat->dim[1].size) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)y*mat->dim[0].step + x*mat->dim[1].step; - if( _type ) - *_type = CV_MAT_TYPE(mat->type); - } - else if( CV_IS_SPARSE_MAT( arr )) - { - CV_Assert(((CvSparseMat*)arr)->dims == 2); - int idx[] = { y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, _type, 1, 0 ); - } - else - { - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - } - - return ptr; -} - - -// Returns pointer to specified element of 3d array -CV_IMPL uchar* -cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type ) -{ - uchar* ptr = 0; - if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - - if( mat->dims != 3 || - (unsigned)z >= (unsigned)(mat->dim[0].size) || - (unsigned)y >= (unsigned)(mat->dim[1].size) || - (unsigned)x >= (unsigned)(mat->dim[2].size) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)z*mat->dim[0].step + - (size_t)y*mat->dim[1].step + x*mat->dim[2].step; - - if( _type ) - *_type = CV_MAT_TYPE(mat->type); - } - else if( CV_IS_SPARSE_MAT( arr )) - { - int idx[] = { z, y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, _type, 1, 0 ); - } - else - { - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - } - - return ptr; -} - - -// Returns pointer to specified element of n-d array -CV_IMPL uchar* -cvPtrND( const CvArr* arr, const int* idx, int* _type, - int create_node, unsigned* precalc_hashval ) -{ - uchar* ptr = 0; - if( !idx ) - CV_Error( cv::Error::StsNullPtr, "NULL pointer to indices" ); - - if( CV_IS_SPARSE_MAT( arr )) - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, - _type, create_node, precalc_hashval ); - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - int i; - ptr = mat->data.ptr; - - for( i = 0; i < mat->dims; i++ ) - { - if( (unsigned)idx[i] >= (unsigned)(mat->dim[i].size) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - ptr += (size_t)idx[i]*mat->dim[i].step; - } - - if( _type ) - *_type = CV_MAT_TYPE(mat->type); - } - else if( CV_IS_MAT_HDR(arr) || CV_IS_IMAGE_HDR(arr) ) - ptr = cvPtr2D( arr, idx[0], idx[1], _type ); - else - CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" ); - - return ptr; -} - - -// Returns specified element of n-D array given linear index -CV_IMPL CvScalar -cvGet1D( const CvArr* arr, int idx ) -{ - CvScalar scalar = cvScalar(); - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr ) && CV_IS_MAT_CONT( ((CvMat*)arr)->type )) - { - CvMat* mat = (CvMat*)arr; - - type = CV_MAT_TYPE(mat->type); - int pix_size = CV_ELEM_SIZE(type); - - // the first part is mul-free sufficient check - // that the index is within the matrix - if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) && - (unsigned)idx >= (unsigned)(mat->rows*mat->cols)) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else if( !CV_IS_SPARSE_MAT( arr ) || ((CvSparseMat*)arr)->dims > 1 ) - ptr = cvPtr1D( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, 0, 0 ); - - if( ptr ) - cvRawDataToScalar( ptr, type, &scalar ); - - return scalar; -} - - -// Returns specified element of 2D array -CV_IMPL CvScalar -cvGet2D( const CvArr* arr, int y, int x ) -{ - CvScalar scalar = cvScalar(); - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - - if( (unsigned)y >= (unsigned)(mat->rows) || - (unsigned)x >= (unsigned)(mat->cols) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - type = CV_MAT_TYPE(mat->type); - ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type); - } - else if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr2D( arr, y, x, &type ); - else - { - int idx[] = { y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - } - - if( ptr ) - cvRawDataToScalar( ptr, type, &scalar ); - - return scalar; -} - - -// Returns specified element of 3D array -CV_IMPL CvScalar -cvGet3D( const CvArr* arr, int z, int y, int x ) -{ - CvScalar scalar = cvScalar(); - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr3D( arr, z, y, x, &type ); - else - { - int idx[] = { z, y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - } - - if( ptr ) - cvRawDataToScalar( ptr, type, &scalar ); - return scalar; -} - - -// Returns specified element of nD array -CV_IMPL CvScalar -cvGetND( const CvArr* arr, const int* idx ) -{ - CvScalar scalar = cvScalar(); - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtrND( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - - if( ptr ) - cvRawDataToScalar( ptr, type, &scalar ); - - return scalar; -} - - -// Returns specified element of n-D array given linear index -CV_IMPL double -cvGetReal1D( const CvArr* arr, int idx ) -{ - double value = 0; - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr ) && CV_IS_MAT_CONT( ((CvMat*)arr)->type )) - { - CvMat* mat = (CvMat*)arr; - - type = CV_MAT_TYPE(mat->type); - int pix_size = CV_ELEM_SIZE(type); - - // the first part is mul-free sufficient check - // that the index is within the matrix - if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) && - (unsigned)idx >= (unsigned)(mat->rows*mat->cols)) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else if( !CV_IS_SPARSE_MAT( arr ) || ((CvSparseMat*)arr)->dims > 1 ) - ptr = cvPtr1D( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, 0, 0 ); - - if( ptr ) - { - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" ); - - value = icvGetReal( ptr, type ); - } - return value; -} - - -// Returns specified element of 2D array -CV_IMPL double -cvGetReal2D( const CvArr* arr, int y, int x ) -{ - double value = 0; - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - - if( (unsigned)y >= (unsigned)(mat->rows) || - (unsigned)x >= (unsigned)(mat->cols) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - type = CV_MAT_TYPE(mat->type); - ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type); - } - else if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr2D( arr, y, x, &type ); - else - { - int idx[] = { y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - } - - if( ptr ) - { - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" ); - - value = icvGetReal( ptr, type ); - } - - return value; -} - - -// Returns specified element of 3D array -CV_IMPL double -cvGetReal3D( const CvArr* arr, int z, int y, int x ) -{ - double value = 0; - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr3D( arr, z, y, x, &type ); - else - { - int idx[] = { z, y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - } - - if( ptr ) - { - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" ); - - value = icvGetReal( ptr, type ); - } - - return value; -} - - -// Returns specified element of nD array -CV_IMPL double -cvGetRealND( const CvArr* arr, const int* idx ) -{ - double value = 0; - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtrND( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 ); - - if( ptr ) - { - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" ); - - value = icvGetReal( ptr, type ); - } - - return value; -} - - -// Assigns new value to specified element of nD array given linear index -CV_IMPL void -cvSet1D( CvArr* arr, int idx, CvScalar scalar ) -{ - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr ) && CV_IS_MAT_CONT( ((CvMat*)arr)->type )) - { - CvMat* mat = (CvMat*)arr; - - type = CV_MAT_TYPE(mat->type); - int pix_size = CV_ELEM_SIZE(type); - - // the first part is mul-free sufficient check - // that the index is within the matrix - if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) && - (unsigned)idx >= (unsigned)(mat->rows*mat->cols)) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else if( !CV_IS_SPARSE_MAT( arr ) || ((CvSparseMat*)arr)->dims > 1 ) - ptr = cvPtr1D( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, -1, 0 ); - - cvScalarToRawData( &scalar, ptr, type ); -} - - -// Assigns new value to specified element of 2D array -CV_IMPL void -cvSet2D( CvArr* arr, int y, int x, CvScalar scalar ) -{ - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - - if( (unsigned)y >= (unsigned)(mat->rows) || - (unsigned)x >= (unsigned)(mat->cols) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - type = CV_MAT_TYPE(mat->type); - ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type); - } - else if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr2D( arr, y, x, &type ); - else - { - int idx[] = { y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - } - cvScalarToRawData( &scalar, ptr, type ); -} - - -// Assigns new value to specified element of 3D array -CV_IMPL void -cvSet3D( CvArr* arr, int z, int y, int x, CvScalar scalar ) -{ - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr3D( arr, z, y, x, &type ); - else - { - int idx[] = { z, y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - } - cvScalarToRawData( &scalar, ptr, type ); -} - - -// Assigns new value to specified element of nD array -CV_IMPL void -cvSetND( CvArr* arr, const int* idx, CvScalar scalar ) -{ - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtrND( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - cvScalarToRawData( &scalar, ptr, type ); -} - - -CV_IMPL void -cvSetReal1D( CvArr* arr, int idx, double value ) -{ - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr ) && CV_IS_MAT_CONT( ((CvMat*)arr)->type )) - { - CvMat* mat = (CvMat*)arr; - - type = CV_MAT_TYPE(mat->type); - int pix_size = CV_ELEM_SIZE(type); - - // the first part is mul-free sufficient check - // that the index is within the matrix - if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) && - (unsigned)idx >= (unsigned)(mat->rows*mat->cols)) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - ptr = mat->data.ptr + (size_t)idx*pix_size; - } - else if( !CV_IS_SPARSE_MAT( arr ) || ((CvSparseMat*)arr)->dims > 1 ) - ptr = cvPtr1D( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, -1, 0 ); - - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" ); - - if( ptr ) - icvSetReal( value, ptr, type ); -} - - -CV_IMPL void -cvSetReal2D( CvArr* arr, int y, int x, double value ) -{ - int type = 0; - uchar* ptr; - - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - - if( (unsigned)y >= (unsigned)(mat->rows) || - (unsigned)x >= (unsigned)(mat->cols) ) - CV_Error( cv::Error::StsOutOfRange, "index is out of range" ); - - type = CV_MAT_TYPE(mat->type); - ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type); - } - else if( !CV_IS_SPARSE_MAT( arr )) - { - ptr = cvPtr2D( arr, y, x, &type ); - } - else - { - int idx[] = { y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - } - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" ); - - if( ptr ) - icvSetReal( value, ptr, type ); -} - - -CV_IMPL void -cvSetReal3D( CvArr* arr, int z, int y, int x, double value ) -{ - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtr3D( arr, z, y, x, &type ); - else - { - int idx[] = { z, y, x }; - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - } - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" ); - - if( ptr ) - icvSetReal( value, ptr, type ); -} - - -CV_IMPL void -cvSetRealND( CvArr* arr, const int* idx, double value ) -{ - int type = 0; - uchar* ptr; - - if( !CV_IS_SPARSE_MAT( arr )) - ptr = cvPtrND( arr, idx, &type ); - else - ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 ); - - if( CV_MAT_CN( type ) > 1 ) - CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" ); - - if( ptr ) - icvSetReal( value, ptr, type ); -} - - -CV_IMPL void -cvClearND( CvArr* arr, const int* idx ) -{ - if( !CV_IS_SPARSE_MAT( arr )) - { - int type; - uchar* ptr; - ptr = cvPtrND( arr, idx, &type ); - if( ptr ) - memset( ptr, 0, CV_ELEM_SIZE(type) ); - } - else - icvDeleteNode( (CvSparseMat*)arr, idx, 0 ); -} - - -/****************************************************************************************\ -* Conversion to CvMat or IplImage * -\****************************************************************************************/ - -// convert array (CvMat or IplImage) to CvMat -CV_IMPL CvMat* -cvGetMat( const CvArr* array, CvMat* mat, - int* pCOI, int allowND ) -{ - CvMat* result = 0; - CvMat* src = (CvMat*)array; - int coi = 0; - - if( !mat || !src ) - CV_Error( cv::Error::StsNullPtr, "NULL array pointer is passed" ); - - if( CV_IS_MAT_HDR(src)) - { - if( !src->data.ptr ) - CV_Error( cv::Error::StsNullPtr, "The matrix has NULL data pointer" ); - - result = (CvMat*)src; - } - else if( CV_IS_IMAGE_HDR(src) ) - { - const IplImage* img = (const IplImage*)src; - int depth, order; - - if( img->imageData == 0 ) - CV_Error( cv::Error::StsNullPtr, "The image has NULL data pointer" ); - - depth = IPL2CV_DEPTH( img->depth ); - if( depth < 0 ) - CV_Error( cv::Error::BadDepth, "" ); - - order = img->dataOrder & (img->nChannels > 1 ? -1 : 0); - - if( img->roi ) - { - if( order == IPL_DATA_ORDER_PLANE ) - { - int type = depth; - - if( img->roi->coi == 0 ) - CV_Error( cv::Error::StsBadFlag, - "Images with planar data layout should be used with COI selected" ); - - cvInitMatHeader( mat, img->roi->height, - img->roi->width, type, - img->imageData + (img->roi->coi-1)*img->imageSize + - img->roi->yOffset*img->widthStep + - img->roi->xOffset*CV_ELEM_SIZE(type), - img->widthStep ); - } - else /* pixel order */ - { - int type = CV_MAKETYPE( depth, img->nChannels ); - coi = img->roi->coi; - - if( img->nChannels > CV_CN_MAX ) - CV_Error( cv::Error::BadNumChannels, - "The image is interleaved and has over CV_CN_MAX channels" ); - - cvInitMatHeader( mat, img->roi->height, img->roi->width, - type, img->imageData + - img->roi->yOffset*img->widthStep + - img->roi->xOffset*CV_ELEM_SIZE(type), - img->widthStep ); - } - } - else - { - int type = CV_MAKETYPE( depth, img->nChannels ); - - if( order != IPL_DATA_ORDER_PIXEL ) - CV_Error( cv::Error::StsBadFlag, "Pixel order should be used with coi == 0" ); - - cvInitMatHeader( mat, img->height, img->width, type, - img->imageData, img->widthStep ); - } - - result = mat; - } - else if( allowND && CV_IS_MATND_HDR(src) ) - { - CvMatND* matnd = (CvMatND*)src; - int size1 = matnd->dim[0].size, size2 = 1; - - if( !src->data.ptr ) - CV_Error( cv::Error::StsNullPtr, "Input array has NULL data pointer" ); - - if( !CV_IS_MAT_CONT( matnd->type )) - CV_Error( cv::Error::StsBadArg, "Only continuous nD arrays are supported here" ); - - if( matnd->dims > 2 ) - { - int i; - for( i = 1; i < matnd->dims; i++ ) - size2 *= matnd->dim[i].size; - } - else - size2 = matnd->dims == 1 ? 1 : matnd->dim[1].size; - - mat->refcount = 0; - mat->hdr_refcount = 0; - mat->data.ptr = matnd->data.ptr; - mat->rows = size1; - mat->cols = size2; - mat->type = CV_MAT_TYPE(matnd->type) | CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG; - mat->step = size2*CV_ELEM_SIZE(matnd->type); - mat->step &= size1 > 1 ? -1 : 0; - - icvCheckHuge( mat ); - result = mat; - } - else - CV_Error( cv::Error::StsBadFlag, "Unrecognized or unsupported array type" ); - - if( pCOI ) - *pCOI = coi; - - return result; -} - - -CV_IMPL CvMat* -cvReshape( const CvArr* array, CvMat* header, - int new_cn, int new_rows ) -{ - CvMat* result = 0; - CvMat *mat = (CvMat*)array; - int total_width, new_width; - - if( !header ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !CV_IS_MAT( mat )) - { - int coi = 0; - mat = cvGetMat( mat, header, &coi, 1 ); - if( coi ) - CV_Error( cv::Error::BadCOI, "COI is not supported" ); - } - - if( new_cn == 0 ) - new_cn = CV_MAT_CN(mat->type); - else if( (unsigned)(new_cn - 1) > 3 ) - CV_Error( cv::Error::BadNumChannels, "" ); - - if( mat != header ) - { - int hdr_refcount = header->hdr_refcount; - *header = *mat; - header->refcount = 0; - header->hdr_refcount = hdr_refcount; - } - - total_width = mat->cols * CV_MAT_CN( mat->type ); - - if( (new_cn > total_width || total_width % new_cn != 0) && new_rows == 0 ) - new_rows = mat->rows * total_width / new_cn; - - if( new_rows == 0 || new_rows == mat->rows ) - { - header->rows = mat->rows; - header->step = mat->step; - } - else - { - int total_size = total_width * mat->rows; - if( !CV_IS_MAT_CONT( mat->type )) - CV_Error( cv::Error::BadStep, - "The matrix is not continuous, thus its number of rows can not be changed" ); - - if( (unsigned)new_rows > (unsigned)total_size ) - CV_Error( cv::Error::StsOutOfRange, "Bad new number of rows" ); - - total_width = total_size / new_rows; - - if( total_width * new_rows != total_size ) - CV_Error( cv::Error::StsBadArg, "The total number of matrix elements " - "is not divisible by the new number of rows" ); - - header->rows = new_rows; - header->step = total_width * CV_ELEM_SIZE1(mat->type); - } - - new_width = total_width / new_cn; - - if( new_width * new_cn != total_width ) - CV_Error( cv::Error::BadNumChannels, - "The total width is not divisible by the new number of channels" ); - - header->cols = new_width; - header->type = (mat->type & ~CV_MAT_TYPE_MASK) | CV_MAKETYPE(mat->type, new_cn); - - result = header; - return result; -} - - -// convert array (CvMat or IplImage) to IplImage -CV_IMPL IplImage* -cvGetImage( const CvArr* array, IplImage* img ) -{ - IplImage* result = 0; - const IplImage* src = (const IplImage*)array; - - if( !img ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !CV_IS_IMAGE_HDR(src) ) - { - const CvMat* mat = (const CvMat*)src; - - if( !CV_IS_MAT_HDR(mat)) - CV_Error( cv::Error::StsBadFlag, "" ); - - if( mat->data.ptr == 0 ) - CV_Error( cv::Error::StsNullPtr, "" ); - - int depth = cvIplDepth(mat->type); - - cvInitImageHeader( img, cvSize(mat->cols, mat->rows), - depth, CV_MAT_CN(mat->type) ); - cvSetData( img, mat->data.ptr, mat->step ); - - result = img; - } - else - { - result = (IplImage*)src; - } - - return result; -} - - -/****************************************************************************************\ -* IplImage-specific functions * -\****************************************************************************************/ - -static IplROI* icvCreateROI( int coi, int xOffset, int yOffset, int width, int height ) -{ - IplROI *roi = 0; - if( !CvIPL.createROI ) - { - roi = (IplROI*)cvAlloc( sizeof(*roi)); - - roi->coi = coi; - roi->xOffset = xOffset; - roi->yOffset = yOffset; - roi->width = width; - roi->height = height; - } - else - { - roi = CvIPL.createROI( coi, xOffset, yOffset, width, height ); - } - - return roi; -} - -static void -icvGetColorModel( int nchannels, const char** colorModel, const char** channelSeq ) -{ - static const char* tab[][2] = - { - {"GRAY", "GRAY"}, - {"",""}, - {"RGB","BGR"}, - {"RGB","BGRA"} - }; - - nchannels--; - *colorModel = *channelSeq = ""; - - if( (unsigned)nchannels <= 3 ) - { - *colorModel = tab[nchannels][0]; - *channelSeq = tab[nchannels][1]; - } -} - - -// create IplImage header -CV_IMPL IplImage * -cvCreateImageHeader( CvSize size, int depth, int channels ) -{ - IplImage *img = 0; - - if( !CvIPL.createHeader ) - { - img = (IplImage *)cvAlloc( sizeof( *img )); - cvInitImageHeader( img, size, depth, channels, IPL_ORIGIN_TL, - CV_DEFAULT_IMAGE_ROW_ALIGN ); - } - else - { - const char *colorModel, *channelSeq; - - icvGetColorModel( channels, &colorModel, &channelSeq ); - - img = CvIPL.createHeader( channels, 0, depth, (char*)colorModel, (char*)channelSeq, - IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, - CV_DEFAULT_IMAGE_ROW_ALIGN, - size.width, size.height, 0, 0, 0, 0 ); - } - - return img; -} - - -// create IplImage header and allocate underlying data -CV_IMPL IplImage * -cvCreateImage( CvSize size, int depth, int channels ) -{ - IplImage *img = cvCreateImageHeader( size, depth, channels ); - CV_Assert( img ); - cvCreateData( img ); - - return img; -} - - -// initialize IplImage header, allocated by the user -CV_IMPL IplImage* -cvInitImageHeader( IplImage * image, CvSize size, int depth, - int channels, int origin, int align ) -{ - const char *colorModel, *channelSeq; - - if( !image ) - CV_Error( cv::Error::HeaderIsNull, "null pointer to header" ); - - *image = cvIplImage(); - - icvGetColorModel( channels, &colorModel, &channelSeq ); - for (int i = 0; i < 4; i++) - { - image->colorModel[i] = colorModel[i]; - if (colorModel[i] == 0) - break; - } - for (int i = 0; i < 4; i++) - { - image->channelSeq[i] = channelSeq[i]; - if (channelSeq[i] == 0) - break; - } - - if( size.width < 0 || size.height < 0 ) - CV_Error( cv::Error::BadROISize, "Bad input roi" ); - - if( (depth != (int)IPL_DEPTH_1U && depth != (int)IPL_DEPTH_8U && - depth != (int)IPL_DEPTH_8S && depth != (int)IPL_DEPTH_16U && - depth != (int)IPL_DEPTH_16S && depth != (int)IPL_DEPTH_32S && - depth != (int)IPL_DEPTH_32F && depth != (int)IPL_DEPTH_64F) || - channels < 0 ) - CV_Error( cv::Error::BadDepth, "Unsupported format" ); - if( origin != CV_ORIGIN_BL && origin != CV_ORIGIN_TL ) - CV_Error( cv::Error::BadOrigin, "Bad input origin" ); - - if( align != 4 && align != 8 ) - CV_Error( cv::Error::BadAlign, "Bad input align" ); - - image->width = size.width; - image->height = size.height; - - if( image->roi ) - { - image->roi->coi = 0; - image->roi->xOffset = image->roi->yOffset = 0; - image->roi->width = size.width; - image->roi->height = size.height; - } - - image->nChannels = MAX( channels, 1 ); - image->depth = depth; - image->align = align; - image->widthStep = (((image->width * image->nChannels * - (image->depth & ~IPL_DEPTH_SIGN) + 7)/8)+ align - 1) & (~(align - 1)); - image->origin = origin; - const int64 imageSize_tmp = (int64)image->widthStep*(int64)image->height; - image->imageSize = (int)imageSize_tmp; - if( (int64)image->imageSize != imageSize_tmp ) - CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" ); - - return image; -} - - -CV_IMPL void -cvReleaseImageHeader( IplImage** image ) -{ - if( !image ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( *image ) - { - IplImage* img = *image; - *image = 0; - - if( !CvIPL.deallocate ) - { - cvFree( &img->roi ); - cvFree( &img ); - } - else - { - CvIPL.deallocate( img, IPL_IMAGE_HEADER | IPL_IMAGE_ROI ); - } - } -} - - -CV_IMPL void -cvReleaseImage( IplImage ** image ) -{ - if( !image ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( *image ) - { - IplImage* img = *image; - *image = 0; - - cvReleaseData( img ); - cvReleaseImageHeader( &img ); - } -} - - -CV_IMPL void -cvSetImageROI( IplImage* image, CvRect rect ) -{ - if( !image ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - // allow zero ROI width or height - CV_Assert( rect.width >= 0 && rect.height >= 0 && - rect.x < image->width && rect.y < image->height && - rect.x + rect.width >= (int)(rect.width > 0) && - rect.y + rect.height >= (int)(rect.height > 0) ); - - rect.width += rect.x; - rect.height += rect.y; - - rect.x = std::max(rect.x, 0); - rect.y = std::max(rect.y, 0); - rect.width = std::min(rect.width, image->width); - rect.height = std::min(rect.height, image->height); - - rect.width -= rect.x; - rect.height -= rect.y; - - if( image->roi ) - { - image->roi->xOffset = rect.x; - image->roi->yOffset = rect.y; - image->roi->width = rect.width; - image->roi->height = rect.height; - } - else - image->roi = icvCreateROI( 0, rect.x, rect.y, rect.width, rect.height ); -} - - -CV_IMPL void -cvResetImageROI( IplImage* image ) -{ - if( !image ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - if( image->roi ) - { - if( !CvIPL.deallocate ) - { - cvFree( &image->roi ); - } - else - { - CvIPL.deallocate( image, IPL_IMAGE_ROI ); - image->roi = 0; - } - } -} - - -CV_IMPL CvRect -cvGetImageROI( const IplImage* img ) -{ - CvRect rect = {0, 0, 0, 0}; - if( !img ) - CV_Error( cv::Error::StsNullPtr, "Null pointer to image" ); - - if( img->roi ) - rect = cvRect( img->roi->xOffset, img->roi->yOffset, - img->roi->width, img->roi->height ); - else - rect = cvRect( 0, 0, img->width, img->height ); - - return rect; -} - - -CV_IMPL void -cvSetImageCOI( IplImage* image, int coi ) -{ - if( !image ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - if( (unsigned)coi > (unsigned)(image->nChannels) ) - CV_Error( cv::Error::BadCOI, "" ); - - if( image->roi || coi != 0 ) - { - if( image->roi ) - { - image->roi->coi = coi; - } - else - { - image->roi = icvCreateROI( coi, 0, 0, image->width, image->height ); - } - } -} - - -CV_IMPL int -cvGetImageCOI( const IplImage* image ) -{ - if( !image ) - CV_Error( cv::Error::HeaderIsNull, "" ); - - return image->roi ? image->roi->coi : 0; -} - - -CV_IMPL IplImage* -cvCloneImage( const IplImage* src ) -{ - IplImage* dst = 0; - - if( !CV_IS_IMAGE_HDR( src )) - CV_Error( cv::Error::StsBadArg, "Bad image header" ); - - if( !CvIPL.cloneImage ) - { - dst = (IplImage*)cvAlloc( sizeof(*dst)); - - memcpy( dst, src, sizeof(*src)); - dst->nSize = sizeof(IplImage); - dst->imageData = dst->imageDataOrigin = 0; - dst->roi = 0; - - if( src->roi ) - { - dst->roi = icvCreateROI( src->roi->coi, src->roi->xOffset, - src->roi->yOffset, src->roi->width, src->roi->height ); - } - - if( src->imageData ) - { - int size = src->imageSize; - cvCreateData( dst ); - memcpy( dst->imageData, src->imageData, size ); - } - } - else - dst = CvIPL.cloneImage( src ); - - return dst; -} - - -/****************************************************************************************\ -* Additional operations on CvTermCriteria * -\****************************************************************************************/ - -CV_IMPL CvTermCriteria -cvCheckTermCriteria( CvTermCriteria criteria, double default_eps, - int default_max_iters ) -{ - CvTermCriteria crit; - - crit.type = CV_TERMCRIT_ITER|CV_TERMCRIT_EPS; - crit.max_iter = default_max_iters; - crit.epsilon = (float)default_eps; - - if( (criteria.type & ~(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) != 0 ) - CV_Error( cv::Error::StsBadArg, - "Unknown type of term criteria" ); - - if( (criteria.type & CV_TERMCRIT_ITER) != 0 ) - { - if( criteria.max_iter <= 0 ) - CV_Error( cv::Error::StsBadArg, - "Iterations flag is set and maximum number of iterations is <= 0" ); - crit.max_iter = criteria.max_iter; - } - - if( (criteria.type & CV_TERMCRIT_EPS) != 0 ) - { - if( criteria.epsilon < 0 ) - CV_Error( cv::Error::StsBadArg, "Accuracy flag is set and epsilon is < 0" ); - - crit.epsilon = criteria.epsilon; - } - - if( (criteria.type & (CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) == 0 ) - CV_Error( cv::Error::StsBadArg, - "Neither accuracy nor maximum iterations " - "number flags are set in criteria type" ); - - crit.epsilon = (float)MAX( 0, crit.epsilon ); - crit.max_iter = MAX( 1, crit.max_iter ); - - return crit; -} - -namespace cv -{ - -void DefaultDeleter::operator ()(CvMat* obj) const { cvReleaseMat(&obj); } -void DefaultDeleter::operator ()(IplImage* obj) const { cvReleaseImage(&obj); } -void DefaultDeleter::operator ()(CvMatND* obj) const { cvReleaseMatND(&obj); } -void DefaultDeleter::operator ()(CvSparseMat* obj) const { cvReleaseSparseMat(&obj); } -void DefaultDeleter::operator ()(CvMemStorage* obj) const { cvReleaseMemStorage(&obj); } - -} // cv:: - - -/* universal functions */ -CV_IMPL void -cvRelease( void** struct_ptr ) -{ - if( !struct_ptr ) - CV_Error( cv::Error::StsNullPtr, "NULL double pointer" ); - - if( *struct_ptr ) - { - if( CV_IS_MAT(*struct_ptr) ) - cvReleaseMat((CvMat**)struct_ptr); - else if( CV_IS_IMAGE(*struct_ptr)) - cvReleaseImage((IplImage**)struct_ptr); - else - CV_Error( cv::Error::StsError, "Unknown object type" ); - } -} - - -#endif // OPENCV_EXCLUDE_C_API -/* End of file. */ diff --git a/modules/core/src/convert_c.cpp b/modules/core/src/convert_c.cpp deleted file mode 100644 index 96beffccc6..0000000000 --- a/modules/core/src/convert_c.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - - -#include "precomp.hpp" - -#ifndef OPENCV_EXCLUDE_C_API - -CV_IMPL void -cvSplit( const void* srcarr, void* dstarr0, void* dstarr1, void* dstarr2, void* dstarr3 ) -{ - void* dptrs[] = { dstarr0, dstarr1, dstarr2, dstarr3 }; - cv::Mat src = cv::cvarrToMat(srcarr); - int i, j, nz = 0; - for( i = 0; i < 4; i++ ) - nz += dptrs[i] != 0; - CV_Assert( nz > 0 ); - std::vector dvec(nz); - std::vector pairs(nz*2); - - for( i = j = 0; i < 4; i++ ) - { - if( dptrs[i] != 0 ) - { - dvec[j] = cv::cvarrToMat(dptrs[i]); - CV_Assert( dvec[j].size() == src.size() ); - CV_Assert( dvec[j].depth() == src.depth() ); - CV_Assert( dvec[j].channels() == 1 ); - CV_Assert( i < src.channels() ); - pairs[j*2] = i; - pairs[j*2+1] = j; - j++; - } - } - if( nz == src.channels() ) - cv::split( src, dvec ); - else - { - cv::mixChannels( &src, 1, &dvec[0], nz, &pairs[0], nz ); - } -} - - -CV_IMPL void -cvMerge( const void* srcarr0, const void* srcarr1, const void* srcarr2, - const void* srcarr3, void* dstarr ) -{ - const void* sptrs[] = { srcarr0, srcarr1, srcarr2, srcarr3 }; - cv::Mat dst = cv::cvarrToMat(dstarr); - int i, j, nz = 0; - for( i = 0; i < 4; i++ ) - nz += sptrs[i] != 0; - CV_Assert( nz > 0 ); - std::vector svec(nz); - std::vector pairs(nz*2); - - for( i = j = 0; i < 4; i++ ) - { - if( sptrs[i] != 0 ) - { - svec[j] = cv::cvarrToMat(sptrs[i]); - CV_Assert( svec[j].size == dst.size && - svec[j].depth() == dst.depth() && - svec[j].channels() == 1 && i < dst.channels() ); - pairs[j*2] = j; - pairs[j*2+1] = i; - j++; - } - } - - if( nz == dst.channels() ) - cv::merge( svec, dst ); - else - { - cv::mixChannels( &svec[0], nz, &dst, 1, &pairs[0], nz ); - } -} - - -CV_IMPL void -cvMixChannels( const CvArr** src, int src_count, - CvArr** dst, int dst_count, - const int* from_to, int pair_count ) -{ - cv::AutoBuffer buf(src_count + dst_count); - - int i; - for( i = 0; i < src_count; i++ ) - buf[i] = cv::cvarrToMat(src[i]); - for( i = 0; i < dst_count; i++ ) - buf[i+src_count] = cv::cvarrToMat(dst[i]); - cv::mixChannels(&buf[0], src_count, &buf[src_count], dst_count, from_to, pair_count); -} - - -CV_IMPL void -cvConvertScaleAbs( const void* srcarr, void* dstarr, - double scale, double shift ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.size == dst.size && dst.type() == CV_8UC(src.channels())); - cv::convertScaleAbs( src, dst, scale, shift ); -} - - -CV_IMPL void -cvConvertScale( const void* srcarr, void* dstarr, - double scale, double shift ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.size == dst.size && src.channels() == dst.channels() ); - src.convertTo(dst, dst.type(), scale, shift); -} - - -CV_IMPL void cvLUT( const void* srcarr, void* dstarr, const void* lutarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), lut = cv::cvarrToMat(lutarr); - - CV_Assert( dst.size() == src.size() && dst.type() == CV_MAKETYPE(lut.depth(), src.channels()) ); - cv::LUT( src, lut, dst ); -} - - -CV_IMPL void cvNormalize( const CvArr* srcarr, CvArr* dstarr, - double a, double b, int norm_type, const CvArr* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - CV_Assert( dst.size() == src.size() && src.channels() == dst.channels() ); - cv::normalize( src, dst, a, b, norm_type, dst.type(), mask ); -} - -#endif // OPENCV_EXCLUDE_C_API diff --git a/modules/core/src/copy.cpp b/modules/core/src/copy.cpp index ffb61117c4..327f5c9130 100644 --- a/modules/core/src/copy.cpp +++ b/modules/core/src/copy.cpp @@ -49,7 +49,6 @@ #include "precomp.hpp" #include "opencl_kernels_core.hpp" - namespace cv { @@ -1129,115 +1128,4 @@ void cv::copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, top, left, (int)src.elemSize(), (uchar*)buf.data() ); } } - - -#ifndef OPENCV_EXCLUDE_C_API - -/* dst = src */ -CV_IMPL void -cvCopy( const void* srcarr, void* dstarr, const void* maskarr ) -{ - if( CV_IS_SPARSE_MAT(srcarr) && CV_IS_SPARSE_MAT(dstarr)) - { - CV_Assert( maskarr == 0 ); - CvSparseMat* src1 = (CvSparseMat*)srcarr; - CvSparseMat* dst1 = (CvSparseMat*)dstarr; - CvSparseMatIterator iterator; - CvSparseNode* node; - - dst1->dims = src1->dims; - memcpy( dst1->size, src1->size, src1->dims*sizeof(src1->size[0])); - dst1->valoffset = src1->valoffset; - dst1->idxoffset = src1->idxoffset; - cvClearSet( dst1->heap ); - - if( src1->heap->active_count >= dst1->hashsize*CV_SPARSE_HASH_RATIO ) - { - cvFree( &dst1->hashtable ); - dst1->hashsize = src1->hashsize; - dst1->hashtable = - (void**)cvAlloc( dst1->hashsize*sizeof(dst1->hashtable[0])); - } - - memset( dst1->hashtable, 0, dst1->hashsize*sizeof(dst1->hashtable[0])); - - for( node = cvInitSparseMatIterator( src1, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap ); - int tabidx = node->hashval & (dst1->hashsize - 1); - memcpy( node_copy, node, dst1->heap->elem_size ); - node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx]; - dst1->hashtable[tabidx] = node_copy; - } - return; - } - cv::Mat src = cv::cvarrToMat(srcarr, false, true, 1), dst = cv::cvarrToMat(dstarr, false, true, 1); - CV_Assert( src.depth() == dst.depth() && src.size == dst.size ); - - int coi1 = 0, coi2 = 0; - if( CV_IS_IMAGE(srcarr) ) - coi1 = cvGetImageCOI((const IplImage*)srcarr); - if( CV_IS_IMAGE(dstarr) ) - coi2 = cvGetImageCOI((const IplImage*)dstarr); - - if( coi1 || coi2 ) - { - CV_Assert( (coi1 != 0 || src.channels() == 1) && - (coi2 != 0 || dst.channels() == 1) ); - - int pair[] = { std::max(coi1-1, 0), std::max(coi2-1, 0) }; - cv::mixChannels( &src, 1, &dst, 1, pair, 1 ); - return; - } - else - CV_Assert( src.channels() == dst.channels() ); - - if( !maskarr ) - src.copyTo(dst); - else - src.copyTo(dst, cv::cvarrToMat(maskarr)); -} - -CV_IMPL void -cvSet( void* arr, CvScalar value, const void* maskarr ) -{ - cv::Mat m = cv::cvarrToMat(arr); - if( !maskarr ) - m = value; - else - m.setTo(cv::Scalar(value), cv::cvarrToMat(maskarr)); -} - -CV_IMPL void -cvSetZero( CvArr* arr ) -{ - if( CV_IS_SPARSE_MAT(arr) ) - { - CvSparseMat* mat1 = (CvSparseMat*)arr; - cvClearSet( mat1->heap ); - if( mat1->hashtable ) - memset( mat1->hashtable, 0, mat1->hashsize*sizeof(mat1->hashtable[0])); - return; - } - cv::Mat m = cv::cvarrToMat(arr); - m = cv::Scalar(0); -} - -CV_IMPL void -cvFlip( const CvArr* srcarr, CvArr* dstarr, int flip_mode ) -{ - cv::Mat src = cv::cvarrToMat(srcarr); - cv::Mat dst; - - if (!dstarr) - dst = src; - else - dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.type() == dst.type() && src.size() == dst.size() ); - cv::flip( src, dst, flip_mode ); -} - -#endif // OPENCV_EXCLUDE_C_API /* End of file. */ diff --git a/modules/core/src/datastructs.cpp b/modules/core/src/datastructs.cpp deleted file mode 100644 index 17da7119a3..0000000000 --- a/modules/core/src/datastructs.cpp +++ /dev/null @@ -1,3589 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ -#include "precomp.hpp" - -#ifndef OPENCV_EXCLUDE_C_API - -/* default alignment for dynamic data strucutures, resided in storages. */ -#define CV_STRUCT_ALIGN ((int)sizeof(double)) - -/* default storage block size */ -#define CV_STORAGE_BLOCK_SIZE ((1<<16) - 128) - -#define ICV_FREE_PTR(storage) \ - ((schar*)(storage)->top + (storage)->block_size - (storage)->free_space) - -#define ICV_ALIGNED_SEQ_BLOCK_SIZE \ - (int)cvAlign(sizeof(CvSeqBlock), CV_STRUCT_ALIGN) - -CV_INLINE int -cvAlignLeft( int size, int align ) -{ - return size & -align; -} - -#define CV_GET_LAST_ELEM( seq, block ) \ - ((block)->data + ((block)->count - 1)*((seq)->elem_size)) - -#define CV_SWAP_ELEMS(a,b,elem_size) \ -{ \ - int k; \ - for( k = 0; k < elem_size; k++ ) \ - { \ - char t0 = (a)[k]; \ - char t1 = (b)[k]; \ - (a)[k] = t1; \ - (b)[k] = t0; \ - } \ -} - -#define ICV_SHIFT_TAB_MAX 32 -static const schar icvPower2ShiftTab[] = -{ - 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5 -}; - -/****************************************************************************************\ -* Functions for manipulating memory storage - list of memory blocks * -\****************************************************************************************/ - -/* Initialize allocated storage: */ -static void -icvInitMemStorage( CvMemStorage* storage, int block_size ) -{ - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( block_size <= 0 ) - block_size = CV_STORAGE_BLOCK_SIZE; - - block_size = cvAlign( block_size, CV_STRUCT_ALIGN ); - CV_Assert( sizeof(CvMemBlock) % CV_STRUCT_ALIGN == 0 ); - - memset( storage, 0, sizeof( *storage )); - storage->signature = CV_STORAGE_MAGIC_VAL; - storage->block_size = block_size; -} - - -/* Create root memory storage: */ -CV_IMPL CvMemStorage* -cvCreateMemStorage( int block_size ) -{ - CvMemStorage* storage = (CvMemStorage *)cvAlloc( sizeof( CvMemStorage )); - icvInitMemStorage( storage, block_size ); - return storage; -} - - -/* Create child memory storage: */ -CV_IMPL CvMemStorage * -cvCreateChildMemStorage( CvMemStorage * parent ) -{ - if( !parent ) - CV_Error( cv::Error::StsNullPtr, "" ); - - CvMemStorage* storage = cvCreateMemStorage(parent->block_size); - storage->parent = parent; - - return storage; -} - - -/* Release all blocks of the storage (or return them to parent, if any): */ -static void -icvDestroyMemStorage( CvMemStorage* storage ) -{ - CvMemBlock *block; - CvMemBlock *dst_top = 0; - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( storage->parent ) - dst_top = storage->parent->top; - - for( block = storage->bottom; block != 0; ) - { - CvMemBlock *temp = block; - - block = block->next; - if( storage->parent ) - { - if( dst_top ) - { - temp->prev = dst_top; - temp->next = dst_top->next; - if( temp->next ) - temp->next->prev = temp; - dst_top = dst_top->next = temp; - } - else - { - dst_top = storage->parent->bottom = storage->parent->top = temp; - temp->prev = temp->next = 0; - storage->free_space = storage->block_size - sizeof( *temp ); - } - } - else - { - cvFree( &temp ); - } - } - - storage->top = storage->bottom = 0; - storage->free_space = 0; -} - - -/* Release memory storage: */ -CV_IMPL void -cvReleaseMemStorage( CvMemStorage** storage ) -{ - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - CvMemStorage* st = *storage; - *storage = 0; - if( st ) - { - icvDestroyMemStorage( st ); - cvFree( &st ); - } -} - - -/* Clears memory storage (return blocks to the parent, if any): */ -CV_IMPL void -cvClearMemStorage( CvMemStorage * storage ) -{ - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( storage->parent ) - icvDestroyMemStorage( storage ); - else - { - storage->top = storage->bottom; - storage->free_space = storage->bottom ? storage->block_size - sizeof(CvMemBlock) : 0; - } -} - - -/* Moves stack pointer to next block. - If no blocks, allocate new one and link it to the storage: */ -static void -icvGoNextMemBlock( CvMemStorage * storage ) -{ - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !storage->top || !storage->top->next ) - { - CvMemBlock *block; - - if( !(storage->parent) ) - { - block = (CvMemBlock *)cvAlloc( storage->block_size ); - } - else - { - CvMemStorage *parent = storage->parent; - CvMemStoragePos parent_pos; - - cvSaveMemStoragePos( parent, &parent_pos ); - icvGoNextMemBlock( parent ); - - block = parent->top; - cvRestoreMemStoragePos( parent, &parent_pos ); - - if( block == parent->top ) /* the single allocated block */ - { - CV_Assert( parent->bottom == block ); - parent->top = parent->bottom = 0; - parent->free_space = 0; - } - else - { - /* cut the block from the parent's list of blocks */ - parent->top->next = block->next; - if( block->next ) - block->next->prev = parent->top; - } - } - - /* link block */ - block->next = 0; - block->prev = storage->top; - - if( storage->top ) - storage->top->next = block; - else - storage->top = storage->bottom = block; - } - - if( storage->top->next ) - storage->top = storage->top->next; - storage->free_space = storage->block_size - sizeof(CvMemBlock); - CV_Assert( storage->free_space % CV_STRUCT_ALIGN == 0 ); -} - - -/* Remember memory storage position: */ -CV_IMPL void -cvSaveMemStoragePos( const CvMemStorage * storage, CvMemStoragePos * pos ) -{ - if( !storage || !pos ) - CV_Error( cv::Error::StsNullPtr, "" ); - - pos->top = storage->top; - pos->free_space = storage->free_space; -} - - -/* Restore memory storage position: */ -CV_IMPL void -cvRestoreMemStoragePos( CvMemStorage * storage, CvMemStoragePos * pos ) -{ - if( !storage || !pos ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( pos->free_space > storage->block_size ) - CV_Error( cv::Error::StsBadSize, "" ); - - /* - // this breaks icvGoNextMemBlock, so comment it off for now - if( storage->parent && (!pos->top || pos->top->next) ) - { - CvMemBlock* save_bottom; - if( !pos->top ) - save_bottom = 0; - else - { - save_bottom = storage->bottom; - storage->bottom = pos->top->next; - pos->top->next = 0; - storage->bottom->prev = 0; - } - icvDestroyMemStorage( storage ); - storage->bottom = save_bottom; - }*/ - - storage->top = pos->top; - storage->free_space = pos->free_space; - - if( !storage->top ) - { - storage->top = storage->bottom; - storage->free_space = storage->top ? storage->block_size - sizeof(CvMemBlock) : 0; - } -} - - -/* Allocate continuous buffer of the specified size in the storage: */ -CV_IMPL void* -cvMemStorageAlloc( CvMemStorage* storage, size_t size ) -{ - schar *ptr = 0; - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" ); - - if( size > INT_MAX ) - CV_Error( cv::Error::StsOutOfRange, "Too large memory block is requested" ); - - CV_Assert( storage->free_space % CV_STRUCT_ALIGN == 0 ); - - if( (size_t)storage->free_space < size ) - { - size_t max_free_space = cvAlignLeft(storage->block_size - sizeof(CvMemBlock), CV_STRUCT_ALIGN); - if( max_free_space < size ) - CV_Error( cv::Error::StsOutOfRange, "requested size is negative or too big" ); - - icvGoNextMemBlock( storage ); - } - - ptr = ICV_FREE_PTR(storage); - CV_Assert( (size_t)ptr % CV_STRUCT_ALIGN == 0 ); - storage->free_space = cvAlignLeft(storage->free_space - (int)size, CV_STRUCT_ALIGN ); - - return ptr; -} - - -/*CV_IMPL CvString -cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len ) -{ - CvString str; - memset(&str, 0, sizeof(CvString)); - - str.len = len >= 0 ? len : (int)strlen(ptr); - str.ptr = (char*)cvMemStorageAlloc( storage, str.len + 1 ); - memcpy( str.ptr, ptr, str.len ); - str.ptr[str.len] = '\0'; - - return str; -}*/ - - -/****************************************************************************************\ -* Sequence implementation * -\****************************************************************************************/ - -/* Create empty sequence: */ -CV_IMPL CvSeq * -cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage* storage ) -{ - CvSeq *seq = 0; - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( header_size < sizeof( CvSeq ) || elem_size <= 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - /* allocate sequence header */ - seq = (CvSeq*)cvMemStorageAlloc( storage, header_size ); - memset( seq, 0, header_size ); - - seq->header_size = (int)header_size; - seq->flags = (seq_flags & ~CV_MAGIC_MASK) | CV_SEQ_MAGIC_VAL; - { - int elemtype = CV_MAT_TYPE(seq_flags); - int typesize = CV_ELEM_SIZE(elemtype); - - if( elemtype != CV_SEQ_ELTYPE_GENERIC && elemtype != CV_SEQ_ELTYPE_PTR && - typesize != 0 && typesize != (int)elem_size ) - CV_Error( cv::Error::StsBadSize, - "Specified element size doesn't match to the size of the specified element type " - "(try to use 0 for element type)" ); - } - seq->elem_size = (int)elem_size; - seq->storage = storage; - - cvSetSeqBlockSize( seq, (int)((1 << 10)/elem_size) ); - - return seq; -} - - -/* adjusts field of sequence. It determines how much the sequence - grows if there are no free space inside the sequence buffers */ -CV_IMPL void -cvSetSeqBlockSize( CvSeq *seq, int delta_elements ) -{ - int elem_size; - int useful_block_size; - - if( !seq || !seq->storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( delta_elements < 0 ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - useful_block_size = cvAlignLeft(seq->storage->block_size - sizeof(CvMemBlock) - - sizeof(CvSeqBlock), CV_STRUCT_ALIGN); - elem_size = seq->elem_size; - - if( delta_elements == 0 ) - { - delta_elements = (1 << 10) / elem_size; - delta_elements = MAX( delta_elements, 1 ); - } - if( delta_elements * elem_size > useful_block_size ) - { - delta_elements = useful_block_size / elem_size; - if( delta_elements == 0 ) - CV_Error( cv::Error::StsOutOfRange, "Storage block size is too small " - "to fit the sequence elements" ); - } - - seq->delta_elems = delta_elements; -} - - -/* Find a sequence element by its index: */ -CV_IMPL schar* -cvGetSeqElem( const CvSeq *seq, int index ) -{ - CvSeqBlock *block; - int count, total = seq->total; - - if( (unsigned)index >= (unsigned)total ) - { - index += index < 0 ? total : 0; - index -= index >= total ? total : 0; - if( (unsigned)index >= (unsigned)total ) - return 0; - } - - block = seq->first; - if( index + index <= total ) - { - while( index >= (count = block->count) ) - { - block = block->next; - index -= count; - } - } - else - { - do - { - block = block->prev; - total -= block->count; - } - while( index < total ); - index -= total; - } - - return block->data + index * seq->elem_size; -} - - -/* Calculate index of a sequence element: */ -CV_IMPL int -cvSeqElemIdx( const CvSeq* seq, const void* _element, CvSeqBlock** _block ) -{ - const schar *element = (const schar *)_element; - int elem_size; - int id = -1; - CvSeqBlock *first_block; - CvSeqBlock *block; - - if( !seq || !element ) - CV_Error( cv::Error::StsNullPtr, "" ); - - block = first_block = seq->first; - elem_size = seq->elem_size; - - for( ;; ) - { - if( (unsigned)(element - block->data) < (unsigned) (block->count * elem_size) ) - { - if( _block ) - *_block = block; - if( elem_size <= ICV_SHIFT_TAB_MAX && (id = icvPower2ShiftTab[elem_size - 1]) >= 0 ) - id = (int)((size_t)(element - block->data) >> id); - else - id = (int)((size_t)(element - block->data) / elem_size); - id += block->start_index - seq->first->start_index; - break; - } - block = block->next; - if( block == first_block ) - break; - } - - return id; -} - - -CV_IMPL int -cvSliceLength( CvSlice slice, const CvSeq* seq ) -{ - int total = seq->total; - int length = slice.end_index - slice.start_index; - - if( length != 0 ) - { - if( slice.start_index < 0 ) - slice.start_index += total; - if( slice.end_index <= 0 ) - slice.end_index += total; - - length = slice.end_index - slice.start_index; - } - - while( length < 0 ) - length += total; - if( length > total ) - length = total; - - return length; -} - - -/* Copy all sequence elements into single continuous array: */ -CV_IMPL void* -cvCvtSeqToArray( const CvSeq *seq, void *array, CvSlice slice ) -{ - int elem_size, total; - CvSeqReader reader; - char *dst = (char*)array; - - if( !seq || !array ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = seq->elem_size; - total = cvSliceLength( slice, seq )*elem_size; - - if( total == 0 ) - return 0; - - cvStartReadSeq( seq, &reader, 0 ); - cvSetSeqReaderPos( &reader, slice.start_index, 0 ); - - do - { - int count = (int)(reader.block_max - reader.ptr); - if( count > total ) - count = total; - - memcpy( dst, reader.ptr, count ); - dst += count; - reader.block = reader.block->next; - reader.ptr = reader.block->data; - reader.block_max = reader.ptr + reader.block->count*elem_size; - total -= count; - } - while( total > 0 ); - - return array; -} - - -/* Construct a sequence from an array without copying any data. - NB: The resultant sequence cannot grow beyond its initial size: */ -CV_IMPL CvSeq* -cvMakeSeqHeaderForArray( int seq_flags, int header_size, int elem_size, - void *array, int total, CvSeq *seq, CvSeqBlock * block ) -{ - CvSeq* result = 0; - - if( elem_size <= 0 || header_size < (int)sizeof( CvSeq ) || total < 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - if( !seq || ((!array || !block) && total > 0) ) - CV_Error( cv::Error::StsNullPtr, "" ); - - memset( seq, 0, header_size ); - - seq->header_size = header_size; - seq->flags = (seq_flags & ~CV_MAGIC_MASK) | CV_SEQ_MAGIC_VAL; - { - int elemtype = CV_MAT_TYPE(seq_flags); - int typesize = CV_ELEM_SIZE(elemtype); - - if( elemtype != CV_SEQ_ELTYPE_GENERIC && - typesize != 0 && typesize != elem_size ) - CV_Error( cv::Error::StsBadSize, - "Element size doesn't match to the size of predefined element type " - "(try to use 0 for sequence element type)" ); - } - seq->elem_size = elem_size; - seq->total = total; - seq->block_max = seq->ptr = (schar *) array + total * elem_size; - - if( total > 0 ) - { - seq->first = block; - block->prev = block->next = block; - block->start_index = 0; - block->count = total; - block->data = (schar *) array; - } - - result = seq; - - return result; -} - - -/* The function allocates space for at least one more sequence element. - If there are free sequence blocks (seq->free_blocks != 0) - they are reused, otherwise the space is allocated in the storage: */ -static void -icvGrowSeq( CvSeq *seq, int in_front_of ) -{ - CvSeqBlock *block; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - block = seq->free_blocks; - - if( !block ) - { - int elem_size = seq->elem_size; - int delta_elems = seq->delta_elems; - CvMemStorage *storage = seq->storage; - - if( seq->total >= delta_elems*4 ) - cvSetSeqBlockSize( seq, delta_elems*2 ); - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "The sequence has NULL storage pointer" ); - - /* If there is a free space just after last allocated block - and it is big enough then enlarge the last block. - This can happen only if the new block is added to the end of sequence: */ - if( (size_t)(ICV_FREE_PTR(storage) - seq->block_max) < CV_STRUCT_ALIGN && - storage->free_space >= seq->elem_size && !in_front_of ) - { - int delta = storage->free_space / elem_size; - - delta = MIN( delta, delta_elems ) * elem_size; - seq->block_max += delta; - storage->free_space = cvAlignLeft((int)(((schar*)storage->top + storage->block_size) - - seq->block_max), CV_STRUCT_ALIGN ); - return; - } - else - { - int delta = elem_size * delta_elems + ICV_ALIGNED_SEQ_BLOCK_SIZE; - - /* Try to allocate elements: */ - if( storage->free_space < delta ) - { - int small_block_size = MAX(1, delta_elems/3)*elem_size + - ICV_ALIGNED_SEQ_BLOCK_SIZE; - /* try to allocate smaller part */ - if( storage->free_space >= small_block_size + CV_STRUCT_ALIGN ) - { - delta = (storage->free_space - ICV_ALIGNED_SEQ_BLOCK_SIZE)/seq->elem_size; - delta = delta*seq->elem_size + ICV_ALIGNED_SEQ_BLOCK_SIZE; - } - else - { - icvGoNextMemBlock( storage ); - CV_Assert( storage->free_space >= delta ); - } - } - - block = (CvSeqBlock*)cvMemStorageAlloc( storage, delta ); - block->data = (schar*)cvAlignPtr( block + 1, CV_STRUCT_ALIGN ); - block->count = delta - ICV_ALIGNED_SEQ_BLOCK_SIZE; - block->prev = block->next = 0; - } - } - else - { - seq->free_blocks = block->next; - } - - if( !(seq->first) ) - { - seq->first = block; - block->prev = block->next = block; - } - else - { - block->prev = seq->first->prev; - block->next = seq->first; - block->prev->next = block->next->prev = block; - } - - /* For free blocks the field means - * total number of bytes in the block. - * - * For used blocks it means current number - * of sequence elements in the block: - */ - CV_Assert( block->count % seq->elem_size == 0 && block->count > 0 ); - - if( !in_front_of ) - { - seq->ptr = block->data; - seq->block_max = block->data + block->count; - block->start_index = block == block->prev ? 0 : - block->prev->start_index + block->prev->count; - } - else - { - int delta = block->count / seq->elem_size; - block->data += block->count; - - if( block != block->prev ) - { - CV_Assert( seq->first->start_index == 0 ); - seq->first = block; - } - else - { - seq->block_max = seq->ptr = block->data; - } - - block->start_index = 0; - - for( ;; ) - { - block->start_index += delta; - block = block->next; - if( block == seq->first ) - break; - } - } - - block->count = 0; -} - -/* Recycle a sequence block: */ -static void -icvFreeSeqBlock( CvSeq *seq, int in_front_of ) -{ - CvSeqBlock *block = seq->first; - - CV_Assert( (in_front_of ? block : block->prev)->count == 0 ); - - if( block == block->prev ) /* single block case */ - { - block->count = (int)(seq->block_max - block->data) + block->start_index * seq->elem_size; - block->data = seq->block_max - block->count; - seq->first = 0; - seq->ptr = seq->block_max = 0; - seq->total = 0; - } - else - { - if( !in_front_of ) - { - block = block->prev; - CV_Assert( seq->ptr == block->data ); - - block->count = (int)(seq->block_max - seq->ptr); - seq->block_max = seq->ptr = block->prev->data + - block->prev->count * seq->elem_size; - } - else - { - int delta = block->start_index; - - block->count = delta * seq->elem_size; - block->data -= block->count; - - /* Update start indices of sequence blocks: */ - for( ;; ) - { - block->start_index -= delta; - block = block->next; - if( block == seq->first ) - break; - } - - seq->first = block->next; - } - - block->prev->next = block->next; - block->next->prev = block->prev; - } - - CV_Assert( block->count > 0 && block->count % seq->elem_size == 0 ); - block->next = seq->free_blocks; - seq->free_blocks = block; -} - - -/****************************************************************************************\ -* Sequence Writer implementation * -\****************************************************************************************/ - -/* Initialize sequence writer: */ -CV_IMPL void -cvStartAppendToSeq( CvSeq *seq, CvSeqWriter * writer ) -{ - if( !seq || !writer ) - CV_Error( cv::Error::StsNullPtr, "" ); - - memset( writer, 0, sizeof( *writer )); - writer->header_size = sizeof( CvSeqWriter ); - - writer->seq = seq; - writer->block = seq->first ? seq->first->prev : 0; - writer->ptr = seq->ptr; - writer->block_max = seq->block_max; -} - - -/* Initialize sequence writer: */ -CV_IMPL void -cvStartWriteSeq( int seq_flags, int header_size, - int elem_size, CvMemStorage * storage, CvSeqWriter * writer ) -{ - if( !storage || !writer ) - CV_Error( cv::Error::StsNullPtr, "" ); - - CvSeq* seq = cvCreateSeq( seq_flags, header_size, elem_size, storage ); - cvStartAppendToSeq( seq, writer ); -} - - -/* Update sequence header: */ -CV_IMPL void -cvFlushSeqWriter( CvSeqWriter * writer ) -{ - if( !writer ) - CV_Error( cv::Error::StsNullPtr, "" ); - - CvSeq* seq = writer->seq; - seq->ptr = writer->ptr; - - if( writer->block ) - { - int total = 0; - CvSeqBlock *first_block = writer->seq->first; - CvSeqBlock *block = first_block; - - writer->block->count = (int)((writer->ptr - writer->block->data) / seq->elem_size); - CV_Assert( writer->block->count > 0 ); - - do - { - total += block->count; - block = block->next; - } - while( block != first_block ); - - writer->seq->total = total; - } -} - - -/* Calls icvFlushSeqWriter and finishes writing process: */ -CV_IMPL CvSeq * -cvEndWriteSeq( CvSeqWriter * writer ) -{ - if( !writer ) - CV_Error( cv::Error::StsNullPtr, "" ); - - cvFlushSeqWriter( writer ); - CvSeq* seq = writer->seq; - - /* Truncate the last block: */ - if( writer->block && writer->seq->storage ) - { - CvMemStorage *storage = seq->storage; - schar *storage_block_max = (schar *) storage->top + storage->block_size; - - CV_Assert( writer->block->count > 0 ); - - if( (unsigned)((storage_block_max - storage->free_space) - - seq->block_max) < CV_STRUCT_ALIGN ) - { - storage->free_space = cvAlignLeft((int)(storage_block_max - seq->ptr), CV_STRUCT_ALIGN); - seq->block_max = seq->ptr; - } - } - - writer->ptr = 0; - return seq; -} - - -/* Create new sequence block: */ -CV_IMPL void -cvCreateSeqBlock( CvSeqWriter * writer ) -{ - if( !writer || !writer->seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - CvSeq* seq = writer->seq; - - cvFlushSeqWriter( writer ); - - icvGrowSeq( seq, 0 ); - - writer->block = seq->first->prev; - writer->ptr = seq->ptr; - writer->block_max = seq->block_max; -} - - -/****************************************************************************************\ -* Sequence Reader implementation * -\****************************************************************************************/ - -/* Initialize sequence reader: */ -CV_IMPL void -cvStartReadSeq( const CvSeq *seq, CvSeqReader * reader, int reverse ) -{ - CvSeqBlock *first_block; - CvSeqBlock *last_block; - - if( reader ) - { - reader->seq = 0; - reader->block = 0; - reader->ptr = reader->block_max = reader->block_min = 0; - } - - if( !seq || !reader ) - CV_Error( cv::Error::StsNullPtr, "" ); - - reader->header_size = sizeof( CvSeqReader ); - reader->seq = (CvSeq*)seq; - - first_block = seq->first; - - if( first_block ) - { - last_block = first_block->prev; - reader->ptr = first_block->data; - reader->prev_elem = CV_GET_LAST_ELEM( seq, last_block ); - reader->delta_index = seq->first->start_index; - - if( reverse ) - { - schar *temp = reader->ptr; - - reader->ptr = reader->prev_elem; - reader->prev_elem = temp; - - reader->block = last_block; - } - else - { - reader->block = first_block; - } - - reader->block_min = reader->block->data; - reader->block_max = reader->block_min + reader->block->count * seq->elem_size; - } - else - { - reader->delta_index = 0; - reader->block = 0; - - reader->ptr = reader->prev_elem = reader->block_min = reader->block_max = 0; - } -} - - -/* Change the current reading block - * to the previous or to the next: - */ -CV_IMPL void -cvChangeSeqBlock( void* _reader, int direction ) -{ - CvSeqReader* reader = (CvSeqReader*)_reader; - - if( !reader ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( direction > 0 ) - { - reader->block = reader->block->next; - reader->ptr = reader->block->data; - } - else - { - reader->block = reader->block->prev; - reader->ptr = CV_GET_LAST_ELEM( reader->seq, reader->block ); - } - reader->block_min = reader->block->data; - reader->block_max = reader->block_min + reader->block->count * reader->seq->elem_size; -} - - -/* Return the current reader position: */ -CV_IMPL int -cvGetSeqReaderPos( CvSeqReader* reader ) -{ - int elem_size; - int index = -1; - - if( !reader || !reader->ptr ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = reader->seq->elem_size; - if( elem_size <= ICV_SHIFT_TAB_MAX && (index = icvPower2ShiftTab[elem_size - 1]) >= 0 ) - index = (int)((reader->ptr - reader->block_min) >> index); - else - index = (int)((reader->ptr - reader->block_min) / elem_size); - - index += reader->block->start_index - reader->delta_index; - - return index; -} - - -/* Set reader position to given position, - * either absolute or relative to the - * current one: - */ -CV_IMPL void -cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative ) -{ - CvSeqBlock *block; - int elem_size, count, total; - - if( !reader || !reader->seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - total = reader->seq->total; - elem_size = reader->seq->elem_size; - - if( !is_relative ) - { - if( index < 0 ) - { - if( index < -total ) - CV_Error( cv::Error::StsOutOfRange, "" ); - index += total; - } - else if( index >= total ) - { - index -= total; - if( index >= total ) - CV_Error( cv::Error::StsOutOfRange, "" ); - } - - block = reader->seq->first; - if( index >= (count = block->count) ) - { - if( index + index <= total ) - { - do - { - block = block->next; - index -= count; - } - while( index >= (count = block->count) ); - } - else - { - do - { - block = block->prev; - total -= block->count; - } - while( index < total ); - index -= total; - } - } - reader->ptr = block->data + index * elem_size; - if( reader->block != block ) - { - reader->block = block; - reader->block_min = block->data; - reader->block_max = block->data + block->count * elem_size; - } - } - else - { - schar* ptr = reader->ptr; - index *= elem_size; - block = reader->block; - - if( index > 0 ) - { - while( ptr + index >= reader->block_max ) - { - int delta = (int)(reader->block_max - ptr); - index -= delta; - reader->block = block = block->next; - reader->block_min = ptr = block->data; - reader->block_max = block->data + block->count*elem_size; - } - reader->ptr = ptr + index; - } - else - { - while( ptr + index < reader->block_min ) - { - int delta = (int)(ptr - reader->block_min); - index += delta; - reader->block = block = block->prev; - reader->block_min = block->data; - reader->block_max = ptr = block->data + block->count*elem_size; - } - reader->ptr = ptr + index; - } - } -} - - -/* Push element onto the sequence: */ -CV_IMPL schar* -cvSeqPush( CvSeq *seq, const void *element ) -{ - schar *ptr = 0; - size_t elem_size; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = seq->elem_size; - ptr = seq->ptr; - - if( ptr >= seq->block_max ) - { - icvGrowSeq( seq, 0 ); - - ptr = seq->ptr; - CV_Assert( ptr + elem_size <= seq->block_max /*&& ptr == seq->block_min */ ); - } - - if( element ) - memcpy( ptr, element, elem_size ); - seq->first->prev->count++; - seq->total++; - seq->ptr = ptr + elem_size; - - return ptr; -} - - -/* Pop last element off of the sequence: */ -CV_IMPL void -cvSeqPop( CvSeq *seq, void *element ) -{ - schar *ptr; - int elem_size; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( seq->total <= 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - elem_size = seq->elem_size; - seq->ptr = ptr = seq->ptr - elem_size; - - if( element ) - memcpy( element, ptr, elem_size ); - seq->ptr = ptr; - seq->total--; - - if( --(seq->first->prev->count) == 0 ) - { - icvFreeSeqBlock( seq, 0 ); - CV_Assert( seq->ptr == seq->block_max ); - } -} - - -/* Push element onto the front of the sequence: */ -CV_IMPL schar* -cvSeqPushFront( CvSeq *seq, const void *element ) -{ - schar* ptr = 0; - int elem_size; - CvSeqBlock *block; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = seq->elem_size; - block = seq->first; - - if( !block || block->start_index == 0 ) - { - icvGrowSeq( seq, 1 ); - - block = seq->first; - CV_Assert( block->start_index > 0 ); - } - - ptr = block->data -= elem_size; - - if( element ) - memcpy( ptr, element, elem_size ); - block->count++; - block->start_index--; - seq->total++; - - return ptr; -} - - -/* Shift out first element of the sequence: */ -CV_IMPL void -cvSeqPopFront( CvSeq *seq, void *element ) -{ - int elem_size; - CvSeqBlock *block; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( seq->total <= 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - elem_size = seq->elem_size; - block = seq->first; - - if( element ) - memcpy( element, block->data, elem_size ); - block->data += elem_size; - block->start_index++; - seq->total--; - - if( --(block->count) == 0 ) - icvFreeSeqBlock( seq, 1 ); -} - -/* Insert new element in middle of sequence: */ -CV_IMPL schar* -cvSeqInsert( CvSeq *seq, int before_index, const void *element ) -{ - int elem_size; - int block_size; - CvSeqBlock *block; - int delta_index; - int total; - schar* ret_ptr = 0; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - total = seq->total; - before_index += before_index < 0 ? total : 0; - before_index -= before_index > total ? total : 0; - - if( (unsigned)before_index > (unsigned)total ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - if( before_index == total ) - { - ret_ptr = cvSeqPush( seq, element ); - } - else if( before_index == 0 ) - { - ret_ptr = cvSeqPushFront( seq, element ); - } - else - { - elem_size = seq->elem_size; - - if( before_index >= total >> 1 ) - { - schar *ptr = seq->ptr + elem_size; - - if( ptr > seq->block_max ) - { - icvGrowSeq( seq, 0 ); - - ptr = seq->ptr + elem_size; - CV_Assert( ptr <= seq->block_max ); - } - - delta_index = seq->first->start_index; - block = seq->first->prev; - block->count++; - block_size = (int)(ptr - block->data); - - while( before_index < block->start_index - delta_index ) - { - CvSeqBlock *prev_block = block->prev; - - memmove( block->data + elem_size, block->data, block_size - elem_size ); - block_size = prev_block->count * elem_size; - memcpy( block->data, prev_block->data + block_size - elem_size, elem_size ); - block = prev_block; - - /* Check that we don't fall into an infinite loop: */ - CV_Assert( block != seq->first->prev ); - } - - before_index = (before_index - block->start_index + delta_index) * elem_size; - memmove( block->data + before_index + elem_size, block->data + before_index, - block_size - before_index - elem_size ); - - ret_ptr = block->data + before_index; - - if( element ) - memcpy( ret_ptr, element, elem_size ); - seq->ptr = ptr; - } - else - { - block = seq->first; - - if( block->start_index == 0 ) - { - icvGrowSeq( seq, 1 ); - - block = seq->first; - } - - delta_index = block->start_index; - block->count++; - block->start_index--; - block->data -= elem_size; - - while( before_index > block->start_index - delta_index + block->count ) - { - CvSeqBlock *next_block = block->next; - - block_size = block->count * elem_size; - memmove( block->data, block->data + elem_size, block_size - elem_size ); - memcpy( block->data + block_size - elem_size, next_block->data, elem_size ); - block = next_block; - - /* Check that we don't fall into an infinite loop: */ - CV_Assert( block != seq->first ); - } - - before_index = (before_index - block->start_index + delta_index) * elem_size; - memmove( block->data, block->data + elem_size, before_index - elem_size ); - - ret_ptr = block->data + before_index - elem_size; - - if( element ) - memcpy( ret_ptr, element, elem_size ); - } - - seq->total = total + 1; - } - - return ret_ptr; -} - - -/* Removes element from sequence: */ -CV_IMPL void -cvSeqRemove( CvSeq *seq, int index ) -{ - schar *ptr; - int elem_size; - int block_size; - CvSeqBlock *block; - int delta_index; - int total, front = 0; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - total = seq->total; - - index += index < 0 ? total : 0; - index -= index >= total ? total : 0; - - if( (unsigned) index >= (unsigned) total ) - CV_Error( cv::Error::StsOutOfRange, "Invalid index" ); - - if( index == total - 1 ) - { - cvSeqPop( seq, 0 ); - } - else if( index == 0 ) - { - cvSeqPopFront( seq, 0 ); - } - else - { - block = seq->first; - elem_size = seq->elem_size; - delta_index = block->start_index; - while( block->start_index - delta_index + block->count <= index ) - block = block->next; - - ptr = block->data + (index - block->start_index + delta_index) * elem_size; - - front = index < total >> 1; - if( !front ) - { - block_size = block->count * elem_size - (int)(ptr - block->data); - - while( block != seq->first->prev ) /* while not the last block */ - { - CvSeqBlock *next_block = block->next; - - memmove( ptr, ptr + elem_size, block_size - elem_size ); - memcpy( ptr + block_size - elem_size, next_block->data, elem_size ); - block = next_block; - ptr = block->data; - block_size = block->count * elem_size; - } - - memmove( ptr, ptr + elem_size, block_size - elem_size ); - seq->ptr -= elem_size; - } - else - { - ptr += elem_size; - block_size = (int)(ptr - block->data); - - while( block != seq->first ) - { - CvSeqBlock *prev_block = block->prev; - - memmove( block->data + elem_size, block->data, block_size - elem_size ); - block_size = prev_block->count * elem_size; - memcpy( block->data, prev_block->data + block_size - elem_size, elem_size ); - block = prev_block; - } - - memmove( block->data + elem_size, block->data, block_size - elem_size ); - block->data += elem_size; - block->start_index++; - } - - seq->total = total - 1; - if( --block->count == 0 ) - icvFreeSeqBlock( seq, front ); - } -} - - -/* Add several elements to the beginning or end of a sequence: */ -CV_IMPL void -cvSeqPushMulti( CvSeq *seq, const void *_elements, int count, int front ) -{ - char *elements = (char *) _elements; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "NULL sequence pointer" ); - if( count < 0 ) - CV_Error( cv::Error::StsBadSize, "number of removed elements is negative" ); - - int elem_size = seq->elem_size; - - if( !front ) - { - while( count > 0 ) - { - int delta = (int)((seq->block_max - seq->ptr) / elem_size); - - delta = MIN( delta, count ); - if( delta > 0 ) - { - seq->first->prev->count += delta; - seq->total += delta; - count -= delta; - delta *= elem_size; - if( elements ) - { - memcpy( seq->ptr, elements, delta ); - elements += delta; - } - seq->ptr += delta; - } - - if( count > 0 ) - icvGrowSeq( seq, 0 ); - } - } - else - { - CvSeqBlock* block = seq->first; - - while( count > 0 ) - { - int delta; - - if( !block || block->start_index == 0 ) - { - icvGrowSeq( seq, 1 ); - - block = seq->first; - CV_Assert( block->start_index > 0 ); - } - - delta = MIN( block->start_index, count ); - count -= delta; - block->start_index -= delta; - block->count += delta; - seq->total += delta; - delta *= elem_size; - block->data -= delta; - - if( elements ) - memcpy( block->data, elements + count*elem_size, delta ); - } - } -} - - -/* Remove several elements from the end of sequence: */ -CV_IMPL void -cvSeqPopMulti( CvSeq *seq, void *_elements, int count, int front ) -{ - char *elements = (char *) _elements; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "NULL sequence pointer" ); - if( count < 0 ) - CV_Error( cv::Error::StsBadSize, "number of removed elements is negative" ); - - count = MIN( count, seq->total ); - - if( !front ) - { - if( elements ) - elements += count * seq->elem_size; - - while( count > 0 ) - { - int delta = seq->first->prev->count; - - delta = MIN( delta, count ); - CV_Assert( delta > 0 ); - - seq->first->prev->count -= delta; - seq->total -= delta; - count -= delta; - delta *= seq->elem_size; - seq->ptr -= delta; - - if( elements ) - { - elements -= delta; - memcpy( elements, seq->ptr, delta ); - } - - if( seq->first->prev->count == 0 ) - icvFreeSeqBlock( seq, 0 ); - } - } - else - { - while( count > 0 ) - { - int delta = seq->first->count; - - delta = MIN( delta, count ); - CV_Assert( delta > 0 ); - - seq->first->count -= delta; - seq->total -= delta; - count -= delta; - seq->first->start_index += delta; - delta *= seq->elem_size; - - if( elements ) - { - memcpy( elements, seq->first->data, delta ); - elements += delta; - } - - seq->first->data += delta; - if( seq->first->count == 0 ) - icvFreeSeqBlock( seq, 1 ); - } - } -} - - -/* Remove all elements from a sequence: */ -CV_IMPL void -cvClearSeq( CvSeq *seq ) -{ - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - cvSeqPopMulti( seq, 0, seq->total ); -} - - -CV_IMPL CvSeq* -cvSeqSlice( const CvSeq* seq, CvSlice slice, CvMemStorage* storage, int copy_data ) -{ - CvSeq* subseq = 0; - int elem_size, count, length; - CvSeqReader reader; - CvSeqBlock *block, *first_block = 0, *last_block = 0; - - if( !CV_IS_SEQ(seq) ) - CV_Error( cv::Error::StsBadArg, "Invalid sequence header" ); - - if( !storage ) - { - storage = seq->storage; - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" ); - } - - elem_size = seq->elem_size; - length = cvSliceLength( slice, seq ); - if( slice.start_index < 0 ) - slice.start_index += seq->total; - else if( slice.start_index >= seq->total ) - slice.start_index -= seq->total; - if( (unsigned)length > (unsigned)seq->total || - ((unsigned)slice.start_index >= (unsigned)seq->total && length != 0) ) - CV_Error( cv::Error::StsOutOfRange, "Bad sequence slice" ); - - subseq = cvCreateSeq( seq->flags, seq->header_size, elem_size, storage ); - - if( length > 0 ) - { - cvStartReadSeq( seq, &reader, 0 ); - cvSetSeqReaderPos( &reader, slice.start_index, 0 ); - count = (int)((reader.block_max - reader.ptr)/elem_size); - - do - { - int bl = MIN( count, length ); - - if( !copy_data ) - { - block = (CvSeqBlock*)cvMemStorageAlloc( storage, sizeof(*block) ); - if( !first_block ) - { - first_block = subseq->first = block->prev = block->next = block; - block->start_index = 0; - } - else - { - block->prev = last_block; - block->next = first_block; - last_block->next = first_block->prev = block; - block->start_index = last_block->start_index + last_block->count; - } - last_block = block; - block->data = reader.ptr; - block->count = bl; - subseq->total += bl; - } - else - cvSeqPushMulti( subseq, reader.ptr, bl, 0 ); - length -= bl; - reader.block = reader.block->next; - reader.ptr = reader.block->data; - count = reader.block->count; - } - while( length > 0 ); - } - - return subseq; -} - - -// Remove slice from the middle of the sequence. -// !!! TODO !!! Implement more efficient algorithm -CV_IMPL void -cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ) -{ - int total, length; - - if( !CV_IS_SEQ(seq) ) - CV_Error( cv::Error::StsBadArg, "Invalid sequence header" ); - - length = cvSliceLength( slice, seq ); - total = seq->total; - - if( slice.start_index < 0 ) - slice.start_index += total; - else if( slice.start_index >= total ) - slice.start_index -= total; - - if( (unsigned)slice.start_index >= (unsigned)total ) - CV_Error( cv::Error::StsOutOfRange, "start slice index is out of range" ); - - slice.end_index = slice.start_index + length; - - if ( slice.start_index == slice.end_index ) - return; - - if( slice.end_index < total ) - { - CvSeqReader reader_to, reader_from; - int elem_size = seq->elem_size; - - cvStartReadSeq( seq, &reader_to ); - cvStartReadSeq( seq, &reader_from ); - - if( slice.start_index > total - slice.end_index ) - { - int i, count = seq->total - slice.end_index; - cvSetSeqReaderPos( &reader_to, slice.start_index ); - cvSetSeqReaderPos( &reader_from, slice.end_index ); - - for( i = 0; i < count; i++ ) - { - memcpy( reader_to.ptr, reader_from.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, reader_to ); - CV_NEXT_SEQ_ELEM( elem_size, reader_from ); - } - - cvSeqPopMulti( seq, 0, slice.end_index - slice.start_index ); - } - else - { - int i, count = slice.start_index; - cvSetSeqReaderPos( &reader_to, slice.end_index ); - cvSetSeqReaderPos( &reader_from, slice.start_index ); - - for( i = 0; i < count; i++ ) - { - CV_PREV_SEQ_ELEM( elem_size, reader_to ); - CV_PREV_SEQ_ELEM( elem_size, reader_from ); - - memcpy( reader_to.ptr, reader_from.ptr, elem_size ); - } - - cvSeqPopMulti( seq, 0, slice.end_index - slice.start_index, 1 ); - } - } - else - { - cvSeqPopMulti( seq, 0, total - slice.start_index ); - cvSeqPopMulti( seq, 0, slice.end_index - total, 1 ); - } -} - - -// Insert a sequence into the middle of another sequence: -// !!! TODO !!! Implement more efficient algorithm -CV_IMPL void -cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr ) -{ - CvSeqReader reader_to, reader_from; - int i, elem_size, total, from_total; - CvSeq from_header, *from = (CvSeq*)from_arr; - CvSeqBlock block; - - if( !CV_IS_SEQ(seq) ) - CV_Error( cv::Error::StsBadArg, "Invalid destination sequence header" ); - - if( !CV_IS_SEQ(from)) - { - CvMat* mat = (CvMat*)from; - if( !CV_IS_MAT(mat)) - CV_Error( cv::Error::StsBadArg, "Source is not a sequence nor matrix" ); - - if( !CV_IS_MAT_CONT(mat->type) || (mat->rows != 1 && mat->cols != 1) ) - CV_Error( cv::Error::StsBadArg, "The source array must be 1d continuous vector" ); - - from = cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC, sizeof(from_header), - CV_ELEM_SIZE(mat->type), - mat->data.ptr, mat->cols + mat->rows - 1, - &from_header, &block ); - } - - if( seq->elem_size != from->elem_size ) - CV_Error( cv::Error::StsUnmatchedSizes, - "Source and destination sequence element sizes are different." ); - - from_total = from->total; - - if( from_total == 0 ) - return; - - total = seq->total; - index += index < 0 ? total : 0; - index -= index > total ? total : 0; - - if( (unsigned)index > (unsigned)total ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - elem_size = seq->elem_size; - - if( index < (total >> 1) ) - { - cvSeqPushMulti( seq, 0, from_total, 1 ); - - cvStartReadSeq( seq, &reader_to ); - cvStartReadSeq( seq, &reader_from ); - cvSetSeqReaderPos( &reader_from, from_total ); - - for( i = 0; i < index; i++ ) - { - memcpy( reader_to.ptr, reader_from.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, reader_to ); - CV_NEXT_SEQ_ELEM( elem_size, reader_from ); - } - } - else - { - cvSeqPushMulti( seq, 0, from_total ); - - cvStartReadSeq( seq, &reader_to ); - cvStartReadSeq( seq, &reader_from ); - cvSetSeqReaderPos( &reader_from, total ); - cvSetSeqReaderPos( &reader_to, seq->total ); - - for( i = 0; i < total - index; i++ ) - { - CV_PREV_SEQ_ELEM( elem_size, reader_to ); - CV_PREV_SEQ_ELEM( elem_size, reader_from ); - memcpy( reader_to.ptr, reader_from.ptr, elem_size ); - } - } - - cvStartReadSeq( from, &reader_from ); - cvSetSeqReaderPos( &reader_to, index ); - - for( i = 0; i < from_total; i++ ) - { - memcpy( reader_to.ptr, reader_from.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, reader_to ); - CV_NEXT_SEQ_ELEM( elem_size, reader_from ); - } -} - -// Sort the sequence using user-specified comparison function. -// The semantics is similar to qsort() function. -// The code is based on BSD system qsort(): -// * Copyright (c) 1992, 1993 -// * The Regents of the University of California. All rights reserved. -// * -// * Redistribution and use in source and binary forms, with or without -// * modification, are permitted provided that the following conditions -// * are met: -// * 1. Redistributions of source code must retain the above copyright -// * notice, this list of conditions and the following disclaimer. -// * 2. Redistributions in binary form must reproduce the above copyright -// * notice, this list of conditions and the following disclaimer in the -// * documentation and/or other materials provided with the distribution. -// * 3. All advertising materials mentioning features or use of this software -// * must display the following acknowledgement: -// * This product includes software developed by the University of -// * California, Berkeley and its contributors. -// * 4. Neither the name of the University nor the names of its contributors -// * may be used to endorse or promote products derived from this software -// * without specific prior written permission. -// * -// * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -// * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -// * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// * SUCH DAMAGE. - -typedef struct CvSeqReaderPos -{ - CvSeqBlock* block; - schar* ptr; - schar* block_min; - schar* block_max; -} -CvSeqReaderPos; - -#define CV_SAVE_READER_POS( reader, pos ) \ -{ \ - (pos).block = (reader).block; \ - (pos).ptr = (reader).ptr; \ - (pos).block_min = (reader).block_min; \ - (pos).block_max = (reader).block_max; \ -} - -#define CV_RESTORE_READER_POS( reader, pos )\ -{ \ - (reader).block = (pos).block; \ - (reader).ptr = (pos).ptr; \ - (reader).block_min = (pos).block_min; \ - (reader).block_max = (pos).block_max; \ -} - -inline schar* -icvMed3( schar* a, schar* b, schar* c, CvCmpFunc cmp_func, void* aux ) -{ - return cmp_func(a, b, aux) < 0 ? - (cmp_func(b, c, aux) < 0 ? b : cmp_func(a, c, aux) < 0 ? c : a) - :(cmp_func(b, c, aux) > 0 ? b : cmp_func(a, c, aux) < 0 ? a : c); -} - -CV_IMPL void -cvSeqSort( CvSeq* seq, CvCmpFunc cmp_func, void* aux ) -{ - int elem_size; - int isort_thresh = 7; - CvSeqReader left, right; - int sp = 0; - - struct - { - CvSeqReaderPos lb; - CvSeqReaderPos ub; - } - stack[48]; - - if( !CV_IS_SEQ(seq) ) - CV_Error( !seq ? cv::Error::StsNullPtr : cv::Error::StsBadArg, "Bad input sequence" ); - - if( !cmp_func ) - CV_Error( cv::Error::StsNullPtr, "Null compare function" ); - - if( seq->total <= 1 ) - return; - - elem_size = seq->elem_size; - isort_thresh *= elem_size; - - cvStartReadSeq( seq, &left, 0 ); - right = left; - CV_SAVE_READER_POS( left, stack[0].lb ); - CV_PREV_SEQ_ELEM( elem_size, right ); - CV_SAVE_READER_POS( right, stack[0].ub ); - - while( sp >= 0 ) - { - CV_RESTORE_READER_POS( left, stack[sp].lb ); - CV_RESTORE_READER_POS( right, stack[sp].ub ); - sp--; - - for(;;) - { - int i, n, m; - CvSeqReader ptr, ptr2; - - if( left.block == right.block ) - n = (int)(right.ptr - left.ptr) + elem_size; - else - { - n = cvGetSeqReaderPos( &right ); - n = (n - cvGetSeqReaderPos( &left ) + 1)*elem_size; - } - - if( n <= isort_thresh ) - { - insert_sort: - ptr = ptr2 = left; - CV_NEXT_SEQ_ELEM( elem_size, ptr ); - CV_NEXT_SEQ_ELEM( elem_size, right ); - while( ptr.ptr != right.ptr ) - { - ptr2.ptr = ptr.ptr; - if( ptr2.block != ptr.block ) - { - ptr2.block = ptr.block; - ptr2.block_min = ptr.block_min; - ptr2.block_max = ptr.block_max; - } - while( ptr2.ptr != left.ptr ) - { - schar* cur = ptr2.ptr; - CV_PREV_SEQ_ELEM( elem_size, ptr2 ); - if( cmp_func( ptr2.ptr, cur, aux ) <= 0 ) - break; - CV_SWAP_ELEMS( ptr2.ptr, cur, elem_size ); - } - CV_NEXT_SEQ_ELEM( elem_size, ptr ); - } - break; - } - else - { - CvSeqReader left0, left1, right0, right1; - CvSeqReader tmp0, tmp1; - schar *m1, *m2, *m3, *pivot; - int swap_cnt = 0; - int l, l0, l1, r, r0, r1; - - left0 = tmp0 = left; - right0 = right1 = right; - n /= elem_size; - - if( n > 40 ) - { - int d = n / 8; - schar *p1, *p2, *p3; - p1 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p2 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p3 = tmp0.ptr; - m1 = icvMed3( p1, p2, p3, cmp_func, aux ); - cvSetSeqReaderPos( &tmp0, (n/2) - d*3, 1 ); - p1 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p2 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p3 = tmp0.ptr; - m2 = icvMed3( p1, p2, p3, cmp_func, aux ); - cvSetSeqReaderPos( &tmp0, n - 1 - d*3 - n/2, 1 ); - p1 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p2 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, d, 1 ); - p3 = tmp0.ptr; - m3 = icvMed3( p1, p2, p3, cmp_func, aux ); - } - else - { - m1 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, n/2, 1 ); - m2 = tmp0.ptr; - cvSetSeqReaderPos( &tmp0, n - 1 - n/2, 1 ); - m3 = tmp0.ptr; - } - - pivot = icvMed3( m1, m2, m3, cmp_func, aux ); - left = left0; - if( pivot != left.ptr ) - { - CV_SWAP_ELEMS( pivot, left.ptr, elem_size ); - pivot = left.ptr; - } - CV_NEXT_SEQ_ELEM( elem_size, left ); - left1 = left; - - for(;;) - { - while( left.ptr != right.ptr && (r = cmp_func(left.ptr, pivot, aux)) <= 0 ) - { - if( r == 0 ) - { - if( left1.ptr != left.ptr ) - CV_SWAP_ELEMS( left1.ptr, left.ptr, elem_size ); - swap_cnt = 1; - CV_NEXT_SEQ_ELEM( elem_size, left1 ); - } - CV_NEXT_SEQ_ELEM( elem_size, left ); - } - - while( left.ptr != right.ptr && (r = cmp_func(right.ptr,pivot, aux)) >= 0 ) - { - if( r == 0 ) - { - if( right1.ptr != right.ptr ) - CV_SWAP_ELEMS( right1.ptr, right.ptr, elem_size ); - swap_cnt = 1; - CV_PREV_SEQ_ELEM( elem_size, right1 ); - } - CV_PREV_SEQ_ELEM( elem_size, right ); - } - - if( left.ptr == right.ptr ) - { - r = cmp_func(left.ptr, pivot, aux); - if( r == 0 ) - { - if( left1.ptr != left.ptr ) - CV_SWAP_ELEMS( left1.ptr, left.ptr, elem_size ); - swap_cnt = 1; - CV_NEXT_SEQ_ELEM( elem_size, left1 ); - } - if( r <= 0 ) - { - CV_NEXT_SEQ_ELEM( elem_size, left ); - } - else - { - CV_PREV_SEQ_ELEM( elem_size, right ); - } - break; - } - - CV_SWAP_ELEMS( left.ptr, right.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, left ); - r = left.ptr == right.ptr; - CV_PREV_SEQ_ELEM( elem_size, right ); - swap_cnt = 1; - if( r ) - break; - } - - if( swap_cnt == 0 ) - { - left = left0, right = right0; - goto insert_sort; - } - - l = cvGetSeqReaderPos( &left ); - if( l == 0 ) - l = seq->total; - l0 = cvGetSeqReaderPos( &left0 ); - l1 = cvGetSeqReaderPos( &left1 ); - if( l1 == 0 ) - l1 = seq->total; - - n = MIN( l - l1, l1 - l0 ); - if( n > 0 ) - { - tmp0 = left0; - tmp1 = left; - cvSetSeqReaderPos( &tmp1, 0-n, 1 ); - for( i = 0; i < n; i++ ) - { - CV_SWAP_ELEMS( tmp0.ptr, tmp1.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, tmp0 ); - CV_NEXT_SEQ_ELEM( elem_size, tmp1 ); - } - } - - r = cvGetSeqReaderPos( &right ); - r0 = cvGetSeqReaderPos( &right0 ); - r1 = cvGetSeqReaderPos( &right1 ); - m = MIN( r0 - r1, r1 - r ); - if( m > 0 ) - { - tmp0 = left; - tmp1 = right0; - cvSetSeqReaderPos( &tmp1, 1-m, 1 ); - for( i = 0; i < m; i++ ) - { - CV_SWAP_ELEMS( tmp0.ptr, tmp1.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, tmp0 ); - CV_NEXT_SEQ_ELEM( elem_size, tmp1 ); - } - } - - n = l - l1; - m = r1 - r; - if( n > 1 ) - { - if( m > 1 ) - { - if( n > m ) - { - sp++; - CV_SAVE_READER_POS( left0, stack[sp].lb ); - cvSetSeqReaderPos( &left0, n - 1, 1 ); - CV_SAVE_READER_POS( left0, stack[sp].ub ); - left = right = right0; - cvSetSeqReaderPos( &left, 1 - m, 1 ); - } - else - { - sp++; - CV_SAVE_READER_POS( right0, stack[sp].ub ); - cvSetSeqReaderPos( &right0, 1 - m, 1 ); - CV_SAVE_READER_POS( right0, stack[sp].lb ); - left = right = left0; - cvSetSeqReaderPos( &right, n - 1, 1 ); - } - } - else - { - left = right = left0; - cvSetSeqReaderPos( &right, n - 1, 1 ); - } - } - else if( m > 1 ) - { - left = right = right0; - cvSetSeqReaderPos( &left, 1 - m, 1 ); - } - else - break; - } - } - } -} - - -CV_IMPL schar* -cvSeqSearch( CvSeq* seq, const void* _elem, CvCmpFunc cmp_func, - int is_sorted, int* _idx, void* userdata ) -{ - schar* result = 0; - const schar* elem = (const schar*)_elem; - int idx = -1; - int i, j; - - if( _idx ) - *_idx = idx; - - if( !CV_IS_SEQ(seq) ) - CV_Error( !seq ? cv::Error::StsNullPtr : cv::Error::StsBadArg, "Bad input sequence" ); - - if( !elem ) - CV_Error( cv::Error::StsNullPtr, "Null element pointer" ); - - int elem_size = seq->elem_size; - int total = seq->total; - - if( total == 0 ) - return 0; - - if( !is_sorted ) - { - CvSeqReader reader; - cvStartReadSeq( seq, &reader, 0 ); - - if( cmp_func ) - { - for( i = 0; i < total; i++ ) - { - if( cmp_func( elem, reader.ptr, userdata ) == 0 ) - break; - CV_NEXT_SEQ_ELEM( elem_size, reader ); - } - } - else if( (elem_size & (sizeof(int)-1)) == 0 ) - { - for( i = 0; i < total; i++ ) - { - for( j = 0; j < elem_size; j += sizeof(int) ) - { - if( *(const int*)(reader.ptr + j) != *(const int*)(elem + j) ) - break; - } - if( j == elem_size ) - break; - CV_NEXT_SEQ_ELEM( elem_size, reader ); - } - } - else - { - for( i = 0; i < total; i++ ) - { - for( j = 0; j < elem_size; j++ ) - { - if( reader.ptr[j] != elem[j] ) - break; - } - if( j == elem_size ) - break; - CV_NEXT_SEQ_ELEM( elem_size, reader ); - } - } - - idx = i; - if( i < total ) - result = reader.ptr; - } - else - { - if( !cmp_func ) - CV_Error( cv::Error::StsNullPtr, "Null compare function" ); - - i = 0, j = total; - - while( j > i ) - { - int k = (i+j)>>1, code; - schar* ptr = cvGetSeqElem( seq, k ); - code = cmp_func( elem, ptr, userdata ); - if( !code ) - { - result = ptr; - idx = k; - if( _idx ) - *_idx = idx; - return result; - } - if( code < 0 ) - j = k; - else - i = k+1; - } - idx = j; - } - - if( _idx ) - *_idx = idx; - - return result; -} - - -CV_IMPL void -cvSeqInvert( CvSeq* seq ) -{ - CvSeqReader left_reader, right_reader; - int elem_size; - int i, count; - - cvStartReadSeq( seq, &left_reader, 0 ); - cvStartReadSeq( seq, &right_reader, 1 ); - elem_size = seq->elem_size; - count = seq->total >> 1; - - for( i = 0; i < count; i++ ) - { - CV_SWAP_ELEMS( left_reader.ptr, right_reader.ptr, elem_size ); - CV_NEXT_SEQ_ELEM( elem_size, left_reader ); - CV_PREV_SEQ_ELEM( elem_size, right_reader ); - } -} - - -typedef struct CvPTreeNode -{ - struct CvPTreeNode* parent; - schar* element; - int rank; -} -CvPTreeNode; - - -// This function splits the input sequence or set into one or more equivalence classes. -// is_equal(a,b,...) returns non-zero if the two sequence elements -// belong to the same class. The function returns sequence of integers - -// 0-based class indexes for each element. -// -// The algorithm is described in "Introduction to Algorithms" -// by Cormen, Leiserson and Rivest, chapter "Data structures for disjoint sets" -CV_IMPL int -cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, CvSeq** labels, - CvCmpFunc is_equal, void* userdata ) -{ - CvSeq* result = 0; - CvMemStorage* temp_storage = 0; - int class_idx = 0; - - CvSeqWriter writer; - CvSeqReader reader, reader0; - CvSeq* nodes; - int i, j; - int is_set; - - if( !labels ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !seq || !is_equal ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !storage ) - storage = seq->storage; - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - - is_set = CV_IS_SET(seq); - - temp_storage = cvCreateChildMemStorage( storage ); - - nodes = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPTreeNode), temp_storage ); - - cvStartReadSeq( seq, &reader ); - memset( &writer, 0, sizeof(writer)); - cvStartAppendToSeq( nodes, &writer ); - - // Initial O(N) pass. Make a forest of single-vertex trees. - for( i = 0; i < seq->total; i++ ) - { - CvPTreeNode node = { 0, 0, 0 }; - if( !is_set || CV_IS_SET_ELEM( reader.ptr )) - node.element = reader.ptr; - CV_WRITE_SEQ_ELEM( node, writer ); - CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); - } - - cvEndWriteSeq( &writer ); - - // Because in the next loop we will iterate - // through all the sequence nodes each time, - // we do not need to initialize reader every time: - cvStartReadSeq( nodes, &reader ); - cvStartReadSeq( nodes, &reader0 ); - - // The main O(N^2) pass. Merge connected components. - for( i = 0; i < nodes->total; i++ ) - { - CvPTreeNode* node = (CvPTreeNode*)(reader0.ptr); - CvPTreeNode* root = node; - CV_NEXT_SEQ_ELEM( nodes->elem_size, reader0 ); - - if( !node->element ) - continue; - - // find root - while( root->parent ) - root = root->parent; - - for( j = 0; j < nodes->total; j++ ) - { - CvPTreeNode* node2 = (CvPTreeNode*)reader.ptr; - - if( node2->element && node2 != node && - is_equal( node->element, node2->element, userdata )) - { - CvPTreeNode* root2 = node2; - - // unite both trees - while( root2->parent ) - root2 = root2->parent; - - if( root2 != root ) - { - if( root->rank > root2->rank ) - root2->parent = root; - else - { - root->parent = root2; - root2->rank += root->rank == root2->rank; - root = root2; - } - CV_Assert( root->parent == 0 ); - - // Compress path from node2 to the root: - while( node2->parent ) - { - CvPTreeNode* temp = node2; - node2 = node2->parent; - temp->parent = root; - } - - // Compress path from node to the root: - node2 = node; - while( node2->parent ) - { - CvPTreeNode* temp = node2; - node2 = node2->parent; - temp->parent = root; - } - } - } - - CV_NEXT_SEQ_ELEM( sizeof(*node), reader ); - } - } - - // Final O(N) pass (Enumerate classes) - // Reuse reader one more time - result = cvCreateSeq( 0, sizeof(CvSeq), sizeof(int), storage ); - cvStartAppendToSeq( result, &writer ); - - for( i = 0; i < nodes->total; i++ ) - { - CvPTreeNode* node = (CvPTreeNode*)reader.ptr; - int idx = -1; - - if( node->element ) - { - while( node->parent ) - node = node->parent; - if( node->rank >= 0 ) - node->rank = ~class_idx++; - idx = ~node->rank; - } - - CV_NEXT_SEQ_ELEM( sizeof(*node), reader ); - CV_WRITE_SEQ_ELEM( idx, writer ); - } - - cvEndWriteSeq( &writer ); - - if( labels ) - *labels = result; - - cvReleaseMemStorage( &temp_storage ); - return class_idx; -} - - -/****************************************************************************************\ -* Set implementation * -\****************************************************************************************/ - -/* Creates empty set: */ -CV_IMPL CvSet* -cvCreateSet( int set_flags, int header_size, int elem_size, CvMemStorage * storage ) -{ - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "" ); - if( header_size < (int)sizeof( CvSet ) || - elem_size < (int)sizeof(void*)*2 || - (elem_size & (sizeof(void*)-1)) != 0 ) - CV_Error( cv::Error::StsBadSize, "" ); - - CvSet* set = (CvSet*) cvCreateSeq( set_flags, header_size, elem_size, storage ); - set->flags = (set->flags & ~CV_MAGIC_MASK) | CV_SET_MAGIC_VAL; - - return set; -} - - -/* Add new element to the set: */ -CV_IMPL int -cvSetAdd( CvSet* set, CvSetElem* element, CvSetElem** inserted_element ) -{ - int id = -1; - CvSetElem *free_elem; - - if( !set ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !(set->free_elems) ) - { - int count = set->total; - int elem_size = set->elem_size; - schar *ptr; - icvGrowSeq( (CvSeq *) set, 0 ); - - set->free_elems = (CvSetElem*) (ptr = set->ptr); - for( ; ptr + elem_size <= set->block_max; ptr += elem_size, count++ ) - { - ((CvSetElem*)ptr)->flags = count | CV_SET_ELEM_FREE_FLAG; - ((CvSetElem*)ptr)->next_free = (CvSetElem*)(ptr + elem_size); - } - CV_Assert( count <= CV_SET_ELEM_IDX_MASK+1 ); - ((CvSetElem*)(ptr - elem_size))->next_free = 0; - set->first->prev->count += count - set->total; - set->total = count; - set->ptr = set->block_max; - } - - free_elem = set->free_elems; - set->free_elems = free_elem->next_free; - - id = free_elem->flags & CV_SET_ELEM_IDX_MASK; - if( element ) - memcpy( free_elem, element, set->elem_size ); - - free_elem->flags = id; - set->active_count++; - - if( inserted_element ) - *inserted_element = free_elem; - - return id; -} - - -/* Remove element from a set given element index: */ -CV_IMPL void -cvSetRemove( CvSet* set, int index ) -{ - CV_Assert(set != NULL); - CvSetElem* elem = cvGetSetElem( set, index ); - if( elem ) - cvSetRemoveByPtr( set, elem ); - else if( !set ) - CV_Error( cv::Error::StsNullPtr, "" ); -} - - -/* Remove all elements from a set: */ -CV_IMPL void -cvClearSet( CvSet* set ) -{ - cvClearSeq( (CvSeq*)set ); - set->free_elems = 0; - set->active_count = 0; -} - - -/****************************************************************************************\ -* Graph implementation * -\****************************************************************************************/ - -/* Create a new graph: */ -CV_IMPL CvGraph * -cvCreateGraph( int graph_type, int header_size, - int vtx_size, int edge_size, CvMemStorage * storage ) -{ - CvGraph *graph = 0; - CvSet *edges = 0; - CvSet *vertices = 0; - - if( header_size < (int) sizeof( CvGraph ) - || edge_size < (int) sizeof( CvGraphEdge ) - || vtx_size < (int) sizeof( CvGraphVtx ) - ){ - CV_Error( cv::Error::StsBadSize, "" ); - } - - vertices = cvCreateSet( graph_type, header_size, vtx_size, storage ); - edges = cvCreateSet( CV_SEQ_KIND_GENERIC | CV_SEQ_ELTYPE_GRAPH_EDGE, - sizeof( CvSet ), edge_size, storage ); - - graph = (CvGraph*)vertices; - graph->edges = edges; - - return graph; -} - - -/* Remove all vertices and edges from a graph: */ -CV_IMPL void -cvClearGraph( CvGraph * graph ) -{ - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - cvClearSet( graph->edges ); - cvClearSet( (CvSet*)graph ); -} - - -/* Add a vertex to a graph: */ -CV_IMPL int -cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* _vertex, CvGraphVtx** _inserted_vertex ) -{ - CvGraphVtx *vertex = 0; - int index = -1; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - vertex = (CvGraphVtx*)cvSetNew((CvSet*)graph); - if( vertex ) - { - if( _vertex ) - memcpy( vertex + 1, _vertex + 1, graph->elem_size - sizeof(CvGraphVtx) ); - vertex->first = 0; - index = vertex->flags; - } - - if( _inserted_vertex ) - *_inserted_vertex = vertex; - - return index; -} - - -/* Remove a vertex from the graph together with its incident edges: */ -CV_IMPL int -cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ) -{ - int count = -1; - - if( !graph || !vtx ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( !CV_IS_SET_ELEM(vtx)) - CV_Error( cv::Error::StsBadArg, "The vertex does not belong to the graph" ); - - count = graph->edges->active_count; - for( ;; ) - { - CvGraphEdge *edge = vtx->first; - if( !edge ) - break; - cvGraphRemoveEdgeByPtr( graph, edge->vtx[0], edge->vtx[1] ); - } - count -= graph->edges->active_count; - cvSetRemoveByPtr( (CvSet*)graph, vtx ); - - return count; -} - - -/* Remove a vertex from the graph together with its incident edges: */ -CV_IMPL int -cvGraphRemoveVtx( CvGraph* graph, int index ) -{ - int count = -1; - CvGraphVtx *vtx = 0; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - vtx = cvGetGraphVtx( graph, index ); - if( !vtx ) - CV_Error( cv::Error::StsBadArg, "The vertex is not found" ); - - count = graph->edges->active_count; - for( ;; ) - { - CvGraphEdge *edge = vtx->first; - count++; - - if( !edge ) - break; - cvGraphRemoveEdgeByPtr( graph, edge->vtx[0], edge->vtx[1] ); - } - count -= graph->edges->active_count; - cvSetRemoveByPtr( (CvSet*)graph, vtx ); - - return count; -} - - -/* Find a graph edge given pointers to the ending vertices: */ -CV_IMPL CvGraphEdge* -cvFindGraphEdgeByPtr( const CvGraph* graph, - const CvGraphVtx* start_vtx, - const CvGraphVtx* end_vtx ) -{ - int ofs = 0; - - if( !graph || !start_vtx || !end_vtx ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( start_vtx == end_vtx ) - return 0; - - if( !CV_IS_GRAPH_ORIENTED( graph ) && - (start_vtx->flags & CV_SET_ELEM_IDX_MASK) > (end_vtx->flags & CV_SET_ELEM_IDX_MASK) ) - { - const CvGraphVtx* t; - CV_SWAP( start_vtx, end_vtx, t ); - } - - CvGraphEdge* edge = start_vtx->first; - for( ; edge; edge = edge->next[ofs] ) - { - ofs = start_vtx == edge->vtx[1]; - CV_Assert( ofs == 1 || start_vtx == edge->vtx[0] ); - if( edge->vtx[1] == end_vtx ) - break; - } - - return edge; -} - - -/* Find an edge in the graph given indices of the ending vertices: */ -CV_IMPL CvGraphEdge * -cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ) -{ - CvGraphVtx *start_vtx; - CvGraphVtx *end_vtx; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "graph pointer is NULL" ); - - start_vtx = cvGetGraphVtx( graph, start_idx ); - end_vtx = cvGetGraphVtx( graph, end_idx ); - - return cvFindGraphEdgeByPtr( graph, start_vtx, end_vtx ); -} - - -/* Given two vertices, return the edge - * connecting them, creating it if it - * did not already exist: - */ -CV_IMPL int -cvGraphAddEdgeByPtr( CvGraph* graph, - CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, - const CvGraphEdge* _edge, - CvGraphEdge ** _inserted_edge ) -{ - CvGraphEdge *edge = 0; - int result = -1; - int delta; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "graph pointer is NULL" ); - - if( !CV_IS_GRAPH_ORIENTED( graph ) && - (start_vtx->flags & CV_SET_ELEM_IDX_MASK) > (end_vtx->flags & CV_SET_ELEM_IDX_MASK) ) - { - CvGraphVtx* t; - CV_SWAP( start_vtx, end_vtx, t ); - } - - edge = cvFindGraphEdgeByPtr( graph, start_vtx, end_vtx ); - if( edge ) - { - result = 0; - if( _inserted_edge ) - *_inserted_edge = edge; - return result; - } - - if( start_vtx == end_vtx ) - CV_Error( start_vtx ? cv::Error::StsBadArg : cv::Error::StsNullPtr, - "vertex pointers coincide (or set to NULL)" ); - - edge = (CvGraphEdge*)cvSetNew( (CvSet*)(graph->edges) ); - CV_Assert( edge->flags >= 0 ); - - edge->vtx[0] = start_vtx; - edge->vtx[1] = end_vtx; - edge->next[0] = start_vtx->first; - edge->next[1] = end_vtx->first; - start_vtx->first = end_vtx->first = edge; - - delta = graph->edges->elem_size - sizeof(*edge); - if( _edge ) - { - if( delta > 0 ) - memcpy( edge + 1, _edge + 1, delta ); - edge->weight = _edge->weight; - } - else - { - if( delta > 0 ) - memset( edge + 1, 0, delta ); - edge->weight = 1.f; - } - - result = 1; - - if( _inserted_edge ) - *_inserted_edge = edge; - - return result; -} - -/* Given two vertices, return the edge - * connecting them, creating it if it - * did not already exist: - */ -CV_IMPL int -cvGraphAddEdge( CvGraph* graph, - int start_idx, int end_idx, - const CvGraphEdge* _edge, - CvGraphEdge ** _inserted_edge ) -{ - CvGraphVtx *start_vtx; - CvGraphVtx *end_vtx; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - start_vtx = cvGetGraphVtx( graph, start_idx ); - end_vtx = cvGetGraphVtx( graph, end_idx ); - - return cvGraphAddEdgeByPtr( graph, start_vtx, end_vtx, _edge, _inserted_edge ); -} - - -/* Remove the graph edge connecting two given vertices: */ -CV_IMPL void -cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx ) -{ - int ofs, prev_ofs; - CvGraphEdge *edge, *next_edge, *prev_edge; - - if( !graph || !start_vtx || !end_vtx ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( start_vtx == end_vtx ) - return; - - if( !CV_IS_GRAPH_ORIENTED( graph ) && - (start_vtx->flags & CV_SET_ELEM_IDX_MASK) > (end_vtx->flags & CV_SET_ELEM_IDX_MASK) ) - { - CvGraphVtx* t; - CV_SWAP( start_vtx, end_vtx, t ); - } - - for( ofs = prev_ofs = 0, prev_edge = 0, edge = start_vtx->first; edge != 0; - prev_ofs = ofs, prev_edge = edge, edge = edge->next[ofs] ) - { - ofs = start_vtx == edge->vtx[1]; - CV_Assert( ofs == 1 || start_vtx == edge->vtx[0] ); - if( edge->vtx[1] == end_vtx ) - break; - } - - if( !edge ) - return; - - next_edge = edge->next[ofs]; - if( prev_edge ) - prev_edge->next[prev_ofs] = next_edge; - else - start_vtx->first = next_edge; - - for( ofs = prev_ofs = 0, prev_edge = 0, edge = end_vtx->first; edge != 0; - prev_ofs = ofs, prev_edge = edge, edge = edge->next[ofs] ) - { - ofs = end_vtx == edge->vtx[1]; - CV_Assert( ofs == 1 || end_vtx == edge->vtx[0] ); - if( edge->vtx[0] == start_vtx ) - break; - } - - CV_Assert( edge != 0 ); - - next_edge = edge->next[ofs]; - if( prev_edge ) - prev_edge->next[prev_ofs] = next_edge; - else - end_vtx->first = next_edge; - - cvSetRemoveByPtr( graph->edges, edge ); -} - - -/* Remove the graph edge connecting two given vertices: */ -CV_IMPL void -cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ) -{ - CvGraphVtx *start_vtx; - CvGraphVtx *end_vtx; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - start_vtx = cvGetGraphVtx( graph, start_idx ); - end_vtx = cvGetGraphVtx( graph, end_idx ); - - cvGraphRemoveEdgeByPtr( graph, start_vtx, end_vtx ); -} - - -/* Count number of edges incident to a given vertex: */ -CV_IMPL int -cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vertex ) -{ - CvGraphEdge *edge; - int count; - - if( !graph || !vertex ) - CV_Error( cv::Error::StsNullPtr, "" ); - - for( edge = vertex->first, count = 0; edge; ) - { - count++; - edge = CV_NEXT_GRAPH_EDGE( edge, vertex ); - } - - return count; -} - - -/* Count number of edges incident to a given vertex: */ -CV_IMPL int -cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ) -{ - CvGraphVtx *vertex; - CvGraphEdge *edge; - int count; - - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "" ); - - vertex = cvGetGraphVtx( graph, vtx_idx ); - if( !vertex ) - CV_Error( cv::Error::StsObjectNotFound, "" ); - - for( edge = vertex->first, count = 0; edge; ) - { - count++; - edge = CV_NEXT_GRAPH_EDGE( edge, vertex ); - } - - return count; -} - - -typedef struct CvGraphItem -{ - CvGraphVtx* vtx; - CvGraphEdge* edge; -} -CvGraphItem; - - -static void -icvSeqElemsClearFlags( CvSeq* seq, int offset, int clear_mask ) -{ - CvSeqReader reader; - int i, total, elem_size; - - if( !seq ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = seq->elem_size; - total = seq->total; - - if( (unsigned)offset > (unsigned)elem_size ) - CV_Error( cv::Error::StsBadArg, "" ); - - cvStartReadSeq( seq, &reader ); - - for( i = 0; i < total; i++ ) - { - int* flag_ptr = (int*)(reader.ptr + offset); - *flag_ptr &= ~clear_mask; - - CV_NEXT_SEQ_ELEM( elem_size, reader ); - } -} - - -static schar* -icvSeqFindNextElem( CvSeq* seq, int offset, int mask, - int value, int* start_index ) -{ - schar* elem_ptr = 0; - - CvSeqReader reader; - int total, elem_size, index; - - if( !seq || !start_index ) - CV_Error( cv::Error::StsNullPtr, "" ); - - elem_size = seq->elem_size; - total = seq->total; - index = *start_index; - - if( (unsigned)offset > (unsigned)elem_size ) - CV_Error( cv::Error::StsBadArg, "" ); - - if( total == 0 ) - return 0; - - if( (unsigned)index >= (unsigned)total ) - { - index %= total; - index += index < 0 ? total : 0; - } - - cvStartReadSeq( seq, &reader ); - - if( index != 0 ) - cvSetSeqReaderPos( &reader, index ); - - for( index = 0; index < total; index++ ) - { - int* flag_ptr = (int*)(reader.ptr + offset); - if( (*flag_ptr & mask) == value ) - break; - - CV_NEXT_SEQ_ELEM( elem_size, reader ); - } - - if( index < total ) - { - elem_ptr = reader.ptr; - *start_index = index; - } - - return elem_ptr; -} - -#define CV_FIELD_OFFSET( field, structtype ) ((int)(size_t)&((structtype*)0)->field) - -CV_IMPL CvGraphScanner* -cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx, int mask ) -{ - if( !graph ) - CV_Error( cv::Error::StsNullPtr, "Null graph pointer" ); - - CV_Assert( graph->storage != 0 ); - - CvGraphScanner* scanner = (CvGraphScanner*)cvAlloc( sizeof(*scanner) ); - memset( scanner, 0, sizeof(*scanner)); - - scanner->graph = graph; - scanner->mask = mask; - scanner->vtx = vtx; - scanner->index = vtx == 0 ? 0 : -1; - - CvMemStorage* child_storage = cvCreateChildMemStorage( graph->storage ); - - scanner->stack = cvCreateSeq( 0, sizeof(CvSet), - sizeof(CvGraphItem), child_storage ); - - icvSeqElemsClearFlags( (CvSeq*)graph, - CV_FIELD_OFFSET( flags, CvGraphVtx), - CV_GRAPH_ITEM_VISITED_FLAG| - CV_GRAPH_SEARCH_TREE_NODE_FLAG ); - - icvSeqElemsClearFlags( (CvSeq*)(graph->edges), - CV_FIELD_OFFSET( flags, CvGraphEdge), - CV_GRAPH_ITEM_VISITED_FLAG ); - - return scanner; -} - - -CV_IMPL void -cvReleaseGraphScanner( CvGraphScanner** scanner ) -{ - if( !scanner ) - CV_Error( cv::Error::StsNullPtr, "Null double pointer to graph scanner" ); - - if( *scanner ) - { - if( (*scanner)->stack ) - cvReleaseMemStorage( &((*scanner)->stack->storage)); - cvFree( scanner ); - } -} - - -CV_IMPL int -cvNextGraphItem( CvGraphScanner* scanner ) -{ - int code = -1; - CvGraphVtx* vtx; - CvGraphVtx* dst; - CvGraphEdge* edge; - CvGraphItem item; - - if( !scanner || !(scanner->stack)) - CV_Error( cv::Error::StsNullPtr, "Null graph scanner" ); - - dst = scanner->dst; - vtx = scanner->vtx; - edge = scanner->edge; - - for(;;) - { - for(;;) - { - if( dst && !CV_IS_GRAPH_VERTEX_VISITED(dst) ) - { - scanner->vtx = vtx = dst; - edge = vtx->first; - dst->flags |= CV_GRAPH_ITEM_VISITED_FLAG; - - if((scanner->mask & CV_GRAPH_VERTEX)) - { - scanner->vtx = vtx; - scanner->edge = vtx->first; - scanner->dst = 0; - code = CV_GRAPH_VERTEX; - return code; - } - } - - while( edge ) - { - dst = edge->vtx[vtx == edge->vtx[0]]; - - if( !CV_IS_GRAPH_EDGE_VISITED(edge) ) - { - // Check that the edge is outgoing: - if( !CV_IS_GRAPH_ORIENTED( scanner->graph ) || dst != edge->vtx[0] ) - { - edge->flags |= CV_GRAPH_ITEM_VISITED_FLAG; - - if( !CV_IS_GRAPH_VERTEX_VISITED(dst) ) - { - item.vtx = vtx; - item.edge = edge; - - vtx->flags |= CV_GRAPH_SEARCH_TREE_NODE_FLAG; - - cvSeqPush( scanner->stack, &item ); - - if( scanner->mask & CV_GRAPH_TREE_EDGE ) - { - code = CV_GRAPH_TREE_EDGE; - scanner->vtx = vtx; - scanner->dst = dst; - scanner->edge = edge; - return code; - } - break; - } - else - { - if( scanner->mask & (CV_GRAPH_BACK_EDGE| - CV_GRAPH_CROSS_EDGE| - CV_GRAPH_FORWARD_EDGE) ) - { - code = (dst->flags & CV_GRAPH_SEARCH_TREE_NODE_FLAG) ? - CV_GRAPH_BACK_EDGE : - (edge->flags & CV_GRAPH_FORWARD_EDGE_FLAG) ? - CV_GRAPH_FORWARD_EDGE : CV_GRAPH_CROSS_EDGE; - edge->flags &= ~CV_GRAPH_FORWARD_EDGE_FLAG; - if( scanner->mask & code ) - { - scanner->vtx = vtx; - scanner->dst = dst; - scanner->edge = edge; - return code; - } - } - } - } - else if( (dst->flags & (CV_GRAPH_ITEM_VISITED_FLAG| - CV_GRAPH_SEARCH_TREE_NODE_FLAG)) == - (CV_GRAPH_ITEM_VISITED_FLAG| - CV_GRAPH_SEARCH_TREE_NODE_FLAG)) - { - edge->flags |= CV_GRAPH_FORWARD_EDGE_FLAG; - } - } - - edge = CV_NEXT_GRAPH_EDGE( edge, vtx ); - } - - if( !edge ) /* need to backtrack */ - { - if( scanner->stack->total == 0 ) - { - if( scanner->index >= 0 ) - vtx = 0; - else - scanner->index = 0; - break; - } - cvSeqPop( scanner->stack, &item ); - vtx = item.vtx; - vtx->flags &= ~CV_GRAPH_SEARCH_TREE_NODE_FLAG; - edge = item.edge; - dst = 0; - - if( scanner->mask & CV_GRAPH_BACKTRACKING ) - { - scanner->vtx = vtx; - scanner->edge = edge; - scanner->dst = edge->vtx[vtx == edge->vtx[0]]; - code = CV_GRAPH_BACKTRACKING; - return code; - } - } - } - - if( !vtx ) - { - vtx = (CvGraphVtx*)icvSeqFindNextElem( (CvSeq*)(scanner->graph), - CV_FIELD_OFFSET( flags, CvGraphVtx ), CV_GRAPH_ITEM_VISITED_FLAG|INT_MIN, - 0, &(scanner->index) ); - - if( !vtx ) - { - code = CV_GRAPH_OVER; - break; - } - } - - dst = vtx; - if( scanner->mask & CV_GRAPH_NEW_TREE ) - { - scanner->dst = dst; - scanner->edge = 0; - scanner->vtx = 0; - code = CV_GRAPH_NEW_TREE; - break; - } - } - - return code; -} - - -CV_IMPL CvGraph* -cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ) -{ - int* flag_buffer = 0; - CvGraphVtx** ptr_buffer = 0; - CvGraph* result = 0; - - int i, k; - int vtx_size, edge_size; - CvSeqReader reader; - - if( !CV_IS_GRAPH(graph)) - CV_Error( cv::Error::StsBadArg, "Invalid graph pointer" ); - - if( !storage ) - storage = graph->storage; - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" ); - - vtx_size = graph->elem_size; - edge_size = graph->edges->elem_size; - - flag_buffer = (int*)cvAlloc( graph->total*sizeof(flag_buffer[0])); - ptr_buffer = (CvGraphVtx**)cvAlloc( graph->total*sizeof(ptr_buffer[0])); - result = cvCreateGraph( graph->flags, graph->header_size, - vtx_size, edge_size, storage ); - memcpy( result + sizeof(CvGraph), graph + sizeof(CvGraph), - graph->header_size - sizeof(CvGraph)); - - // Pass 1. Save flags, copy vertices: - cvStartReadSeq( (CvSeq*)graph, &reader ); - for( i = 0, k = 0; i < graph->total; i++ ) - { - if( CV_IS_SET_ELEM( reader.ptr )) - { - CvGraphVtx* vtx = (CvGraphVtx*)reader.ptr; - CvGraphVtx* dstvtx = 0; - cvGraphAddVtx( result, vtx, &dstvtx ); - flag_buffer[k] = dstvtx->flags = vtx->flags; - vtx->flags = k; - ptr_buffer[k++] = dstvtx; - } - CV_NEXT_SEQ_ELEM( vtx_size, reader ); - } - - // Pass 2. Copy edges: - cvStartReadSeq( (CvSeq*)graph->edges, &reader ); - for( i = 0; i < graph->edges->total; i++ ) - { - if( CV_IS_SET_ELEM( reader.ptr )) - { - CvGraphEdge* edge = (CvGraphEdge*)reader.ptr; - CvGraphEdge* dstedge = 0; - CvGraphVtx* new_org = ptr_buffer[edge->vtx[0]->flags]; - CvGraphVtx* new_dst = ptr_buffer[edge->vtx[1]->flags]; - cvGraphAddEdgeByPtr( result, new_org, new_dst, edge, &dstedge ); - dstedge->flags = edge->flags; - } - CV_NEXT_SEQ_ELEM( edge_size, reader ); - } - - // Pass 3. Restore flags: - cvStartReadSeq( (CvSeq*)graph, &reader ); - for( i = 0, k = 0; i < graph->edges->total; i++ ) - { - if( CV_IS_SET_ELEM( reader.ptr )) - { - CvGraphVtx* vtx = (CvGraphVtx*)reader.ptr; - vtx->flags = flag_buffer[k++]; - } - CV_NEXT_SEQ_ELEM( vtx_size, reader ); - } - - cvFree( &flag_buffer ); - cvFree( &ptr_buffer ); - - if( cvGetErrStatus() < 0 ) - result = 0; - - return result; -} - - -/****************************************************************************************\ -* Working with sequence tree * -\****************************************************************************************/ - -// Gather pointers to all the sequences, accessible from the , to the single sequence. -CV_IMPL CvSeq* -cvTreeToNodeSeq( const void* first, int header_size, CvMemStorage* storage ) -{ - CvSeq* allseq = 0; - CvTreeNodeIterator iterator; - - if( !storage ) - CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" ); - - allseq = cvCreateSeq( 0, header_size, sizeof(first), storage ); - - if( first ) - { - cvInitTreeNodeIterator( &iterator, first, INT_MAX ); - - for(;;) - { - void* node = cvNextTreeNode( &iterator ); - if( !node ) - break; - cvSeqPush( allseq, &node ); - } - } - - - - return allseq; -} - - -typedef struct CvTreeNode -{ - int flags; /* miscellaneous flags */ - int header_size; /* size of sequence header */ - struct CvTreeNode* h_prev; /* previous sequence */ - struct CvTreeNode* h_next; /* next sequence */ - struct CvTreeNode* v_prev; /* 2nd previous sequence */ - struct CvTreeNode* v_next; /* 2nd next sequence */ -} -CvTreeNode; - - - -// Insert contour into tree given certain parent sequence. -// If parent is equal to frame (the most external contour), -// then added contour will have null pointer to parent: -CV_IMPL void -cvInsertNodeIntoTree( void* _node, void* _parent, void* _frame ) -{ - CvTreeNode* node = (CvTreeNode*)_node; - CvTreeNode* parent = (CvTreeNode*)_parent; - - if( !node || !parent ) - CV_Error( cv::Error::StsNullPtr, "" ); - - node->v_prev = _parent != _frame ? parent : 0; - node->h_next = parent->v_next; - - CV_Assert( parent->v_next != node ); - - if( parent->v_next ) - parent->v_next->h_prev = node; - parent->v_next = node; -} - - -// Remove contour from tree, together with the contour's children: -CV_IMPL void -cvRemoveNodeFromTree( void* _node, void* _frame ) -{ - CvTreeNode* node = (CvTreeNode*)_node; - CvTreeNode* frame = (CvTreeNode*)_frame; - - if( !node ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( node == frame ) - CV_Error( cv::Error::StsBadArg, "frame node could not be deleted" ); - - if( node->h_next ) - node->h_next->h_prev = node->h_prev; - - if( node->h_prev ) - node->h_prev->h_next = node->h_next; - else - { - CvTreeNode* parent = node->v_prev; - if( !parent ) - parent = frame; - - if( parent ) - { - CV_Assert( parent->v_next == node ); - parent->v_next = node->h_next; - } - } -} - - -CV_IMPL void -cvInitTreeNodeIterator( CvTreeNodeIterator* treeIterator, - const void* first, int max_level ) -{ - if( !treeIterator || !first ) - CV_Error( cv::Error::StsNullPtr, "" ); - - if( max_level < 0 ) - CV_Error( cv::Error::StsOutOfRange, "" ); - - treeIterator->node = (void*)first; - treeIterator->level = 0; - treeIterator->max_level = max_level; -} - - -CV_IMPL void* -cvNextTreeNode( CvTreeNodeIterator* treeIterator ) -{ - CvTreeNode* prevNode = 0; - CvTreeNode* node; - int level; - - if( !treeIterator ) - CV_Error( cv::Error::StsNullPtr, "NULL iterator pointer" ); - - prevNode = node = (CvTreeNode*)treeIterator->node; - level = treeIterator->level; - - if( node ) - { - if( node->v_next && level+1 < treeIterator->max_level ) - { - node = node->v_next; - level++; - } - else - { - while( node->h_next == 0 ) - { - node = node->v_prev; - if( --level < 0 ) - { - node = 0; - break; - } - } - node = node && treeIterator->max_level != 0 ? node->h_next : 0; - } - } - - treeIterator->node = node; - treeIterator->level = level; - return prevNode; -} - - -CV_IMPL void* -cvPrevTreeNode( CvTreeNodeIterator* treeIterator ) -{ - CvTreeNode* prevNode = 0; - CvTreeNode* node; - int level; - - if( !treeIterator ) - CV_Error( cv::Error::StsNullPtr, "" ); - - prevNode = node = (CvTreeNode*)treeIterator->node; - level = treeIterator->level; - - if( node ) - { - if( !node->h_prev ) - { - node = node->v_prev; - if( --level < 0 ) - node = 0; - } - else - { - node = node->h_prev; - - while( node->v_next && level < treeIterator->max_level ) - { - node = node->v_next; - level++; - - while( node->h_next ) - node = node->h_next; - } - } - } - - treeIterator->node = node; - treeIterator->level = level; - return prevNode; -} - -namespace cv -{ - -//////////////////////////////////////////////////////////////////////////////// - -schar* seqPush( CvSeq* seq, const void* element ) -{ - return cvSeqPush(seq, element); -} - -schar* seqPushFront( CvSeq* seq, const void* element ) -{ - return cvSeqPushFront(seq, element); -} - -void seqPop( CvSeq* seq, void* element ) -{ - cvSeqPop(seq, element); -} - -void seqPopFront( CvSeq* seq, void* element ) -{ - cvSeqPopFront(seq, element); -} - -void seqRemove( CvSeq* seq, int index ) -{ - cvSeqRemove(seq, index); -} - -void clearSeq( CvSeq* seq ) -{ - cvClearSeq(seq); -} - -schar* getSeqElem( const CvSeq* seq, int index ) -{ - return cvGetSeqElem(seq, index); -} - -void seqRemoveSlice( CvSeq* seq, CvSlice slice ) -{ - return cvSeqRemoveSlice(seq, slice); -} - -void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ) -{ - cvSeqInsertSlice(seq, before_index, from_arr); -} - -} - -#endif // OPENCV_EXCLUDE_C_API -/* End of file. */ diff --git a/modules/core/src/dxt.cpp b/modules/core/src/dxt.cpp index 5ace6cbedc..b2f6dca8d9 100644 --- a/modules/core/src/dxt.cpp +++ b/modules/core/src/dxt.cpp @@ -4639,64 +4639,4 @@ int cv::getOptimalDFTSize( int size0 ) return optimalDFTSizeTab[b]; } - - -#ifndef OPENCV_EXCLUDE_C_API - -CV_IMPL void -cvDFT( const CvArr* srcarr, CvArr* dstarr, int flags, int nonzero_rows ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0; - int _flags = ((flags & CV_DXT_INVERSE) ? cv::DFT_INVERSE : 0) | - ((flags & CV_DXT_SCALE) ? cv::DFT_SCALE : 0) | - ((flags & CV_DXT_ROWS) ? cv::DFT_ROWS : 0); - - CV_Assert( src.size == dst.size ); - - if( src.type() != dst.type() ) - { - if( dst.channels() == 2 ) - _flags |= cv::DFT_COMPLEX_OUTPUT; - else - _flags |= cv::DFT_REAL_OUTPUT; - } - - cv::dft( src, dst, _flags, nonzero_rows ); - CV_Assert( dst.data == dst0.data ); // otherwise it means that the destination size or type was incorrect -} - - -CV_IMPL void -cvMulSpectrums( const CvArr* srcAarr, const CvArr* srcBarr, - CvArr* dstarr, int flags ) -{ - cv::Mat srcA = cv::cvarrToMat(srcAarr), - srcB = cv::cvarrToMat(srcBarr), - dst = cv::cvarrToMat(dstarr); - CV_Assert( srcA.size == dst.size && srcA.type() == dst.type() ); - - cv::mulSpectrums(srcA, srcB, dst, - (flags & CV_DXT_ROWS) ? cv::DFT_ROWS : 0, - (flags & CV_DXT_MUL_CONJ) != 0 ); -} - - -CV_IMPL void -cvDCT( const CvArr* srcarr, CvArr* dstarr, int flags ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.size == dst.size && src.type() == dst.type() ); - int _flags = ((flags & CV_DXT_INVERSE) ? cv::DCT_INVERSE : 0) | - ((flags & CV_DXT_ROWS) ? cv::DCT_ROWS : 0); - cv::dct( src, dst, _flags ); -} - - -CV_IMPL int -cvGetOptimalDFTSize( int size0 ) -{ - return cv::getOptimalDFTSize(size0); -} - -#endif // OPENCV_EXCLUDE_C_API /* End of file. */ diff --git a/modules/core/src/lapack.cpp b/modules/core/src/lapack.cpp index 37949f9d62..c3ee3c2a1b 100644 --- a/modules/core/src/lapack.cpp +++ b/modules/core/src/lapack.cpp @@ -1548,200 +1548,3 @@ void cv::SVBackSubst(InputArray w, InputArray u, InputArray vt, InputArray rhs, SVD::backSubst(w, u, vt, rhs, dst); } - - - -#ifndef OPENCV_EXCLUDE_C_API - -CV_IMPL double -cvDet( const CvArr* arr ) -{ - if( CV_IS_MAT(arr) && ((CvMat*)arr)->rows <= 3 ) - { - CvMat* mat = (CvMat*)arr; - int type = CV_MAT_TYPE(mat->type); - int rows = mat->rows; - uchar* m = mat->data.ptr; - int step = mat->step; - CV_Assert( rows == mat->cols ); - - #define Mf(y, x) ((float*)(m + y*step))[x] - #define Md(y, x) ((double*)(m + y*step))[x] - - if( type == CV_32F ) - { - if( rows == 2 ) - return det2(Mf); - if( rows == 3 ) - return det3(Mf); - } - else if( type == CV_64F ) - { - if( rows == 2 ) - return det2(Md); - if( rows == 3 ) - return det3(Md); - } - } - return cv::determinant(cv::cvarrToMat(arr)); -} - - -CV_IMPL double -cvInvert( const CvArr* srcarr, CvArr* dstarr, int method ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.type() == dst.type() && src.rows == dst.cols && src.cols == dst.rows ); - return cv::invert( src, dst, method == CV_CHOLESKY ? cv::DECOMP_CHOLESKY : - method == CV_SVD ? cv::DECOMP_SVD : - method == CV_SVD_SYM ? cv::DECOMP_EIG : cv::DECOMP_LU ); -} - - -CV_IMPL int -cvSolve( const CvArr* Aarr, const CvArr* barr, CvArr* xarr, int method ) -{ - cv::Mat A = cv::cvarrToMat(Aarr), b = cv::cvarrToMat(barr), x = cv::cvarrToMat(xarr); - - CV_Assert( A.type() == x.type() && A.cols == x.rows && x.cols == b.cols ); - bool is_normal = (method & CV_NORMAL) != 0; - method &= ~CV_NORMAL; - return cv::solve( A, b, x, (method == CV_CHOLESKY ? cv::DECOMP_CHOLESKY : - method == CV_SVD ? cv::DECOMP_SVD : - method == CV_SVD_SYM ? cv::DECOMP_EIG : - A.rows > A.cols ? cv::DECOMP_QR : cv::DECOMP_LU) + (is_normal ? cv::DECOMP_NORMAL : 0) ); -} - - -CV_IMPL void -cvEigenVV( CvArr* srcarr, CvArr* evectsarr, CvArr* evalsarr, double, - int, int ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), evals0 = cv::cvarrToMat(evalsarr), evals = evals0; - if( evectsarr ) - { - cv::Mat evects0 = cv::cvarrToMat(evectsarr), evects = evects0; - eigen(src, evals, evects); - if( evects0.data != evects.data ) - { - const uchar* p = evects0.ptr(); - evects.convertTo(evects0, evects0.type()); - CV_Assert( p == evects0.ptr() ); - } - } - else - eigen(src, evals); - if( evals0.data != evals.data ) - { - const uchar* p = evals0.ptr(); - if( evals0.size() == evals.size() ) - evals.convertTo(evals0, evals0.type()); - else if( evals0.type() == evals.type() ) - cv::transpose(evals, evals0); - else - cv::Mat(evals.t()).convertTo(evals0, evals0.type()); - CV_Assert( p == evals0.ptr() ); - } -} - - -CV_IMPL void -cvSVD( CvArr* aarr, CvArr* warr, CvArr* uarr, CvArr* varr, int flags ) -{ - cv::Mat a = cv::cvarrToMat(aarr), w = cv::cvarrToMat(warr), u, v; - int m = a.rows, n = a.cols, type = a.type(), mn = std::max(m, n), nm = std::min(m, n); - - CV_Assert( w.type() == type && - (w.size() == cv::Size(nm,1) || w.size() == cv::Size(1, nm) || - w.size() == cv::Size(nm, nm) || w.size() == cv::Size(n, m)) ); - - cv::SVD svd; - - if( w.size() == cv::Size(nm, 1) ) - svd.w = cv::Mat(nm, 1, type, w.ptr() ); - else if( w.isContinuous() ) - svd.w = w; - - if( uarr ) - { - u = cv::cvarrToMat(uarr); - CV_Assert( u.type() == type ); - svd.u = u; - } - - if( varr ) - { - v = cv::cvarrToMat(varr); - CV_Assert( v.type() == type ); - svd.vt = v; - } - - svd(a, ((flags & CV_SVD_MODIFY_A) ? cv::SVD::MODIFY_A : 0) | - ((!svd.u.data && !svd.vt.data) ? cv::SVD::NO_UV : 0) | - ((m != n && (svd.u.size() == cv::Size(mn, mn) || - svd.vt.size() == cv::Size(mn, mn))) ? cv::SVD::FULL_UV : 0)); - - if( !u.empty() ) - { - if( flags & CV_SVD_U_T ) - cv::transpose( svd.u, u ); - else if( u.data != svd.u.data ) - { - CV_Assert( u.size() == svd.u.size() ); - svd.u.copyTo(u); - } - } - - if( !v.empty() ) - { - if( !(flags & CV_SVD_V_T) ) - cv::transpose( svd.vt, v ); - else if( v.data != svd.vt.data ) - { - CV_Assert( v.size() == svd.vt.size() ); - svd.vt.copyTo(v); - } - } - - if( w.data != svd.w.data ) - { - if( w.size() == svd.w.size() ) - svd.w.copyTo(w); - else - { - w = cv::Scalar(0); - cv::Mat wd = w.diag(); - svd.w.copyTo(wd); - } - } -} - - -CV_IMPL void -cvSVBkSb( const CvArr* warr, const CvArr* uarr, - const CvArr* varr, const CvArr* rhsarr, - CvArr* dstarr, int flags ) -{ - cv::Mat w = cv::cvarrToMat(warr), u = cv::cvarrToMat(uarr), - v = cv::cvarrToMat(varr), rhs, - dst = cv::cvarrToMat(dstarr), dst0 = dst; - if( flags & CV_SVD_U_T ) - { - cv::Mat tmp; - transpose(u, tmp); - u = tmp; - } - if( !(flags & CV_SVD_V_T) ) - { - cv::Mat tmp; - transpose(v, tmp); - v = tmp; - } - if( rhsarr ) - rhs = cv::cvarrToMat(rhsarr); - - cv::SVD::backSubst(w, u, v, rhs, dst); - CV_Assert( dst.data == dst0.data ); -} -#endif // OPENCV_EXCLUDE_C_API diff --git a/modules/core/src/mathfuncs.cpp b/modules/core/src/mathfuncs.cpp index ec99a22a13..2c22dee5c4 100644 --- a/modules/core/src/mathfuncs.cpp +++ b/modules/core/src/mathfuncs.cpp @@ -1607,33 +1607,6 @@ bool checkRange(InputArray _src, bool quiet, Point* pt, double minVal, double ma } // namespace cv - -#ifndef OPENCV_EXCLUDE_C_API - -CV_IMPL void cvExp( const CvArr* srcarr, CvArr* dstarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.type() == dst.type() && src.size == dst.size ); - cv::exp( src, dst ); -} - -CV_IMPL void cvPow( const CvArr* srcarr, CvArr* dstarr, double power ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.type() == dst.type() && src.size == dst.size ); - cv::pow( src, power, dst ); -} - -CV_IMPL int cvCheckArr( const CvArr* arr, int flags, - double minVal, double maxVal ) -{ - if( (flags & CV_CHECK_RANGE) == 0 ) - minVal = -DBL_MAX, maxVal = DBL_MAX; - return cv::checkRange(cv::cvarrToMat(arr), (flags & CV_CHECK_QUIET) != 0, 0, minVal, maxVal ); -} - -#endif // OPENCV_EXCLUDE_C_API - /* Finds real roots of cubic, quadratic or linear equation. The original code has been taken from Ken Turkowski web page @@ -1927,21 +1900,6 @@ double cv::solvePoly( InputArray _coeffs0, OutputArray _roots0, int maxIters ) return maxDiff; } - -#ifndef OPENCV_EXCLUDE_C_API - -void cvSolvePoly(const CvMat* a, CvMat *r, int maxiter, int) -{ - cv::Mat _a = cv::cvarrToMat(a); - cv::Mat _r = cv::cvarrToMat(r); - cv::Mat _r0 = _r; - cv::solvePoly(_a, _r, maxiter); - CV_Assert( _r.data == _r0.data ); // check that the array of roots was not reallocated -} - -#endif // OPENCV_EXCLUDE_C_API - - // Common constants for dispatched code namespace cv { namespace details { diff --git a/modules/core/src/matmul.dispatch.cpp b/modules/core/src/matmul.dispatch.cpp index a2b34dbb0a..1dfd1dd7c0 100644 --- a/modules/core/src/matmul.dispatch.cpp +++ b/modules/core/src/matmul.dispatch.cpp @@ -696,7 +696,7 @@ void calcCovarMatrix( const Mat* data, int nsamples, Mat& covar, Mat& _mean, int Mat mean; ctype = std::max(std::max(CV_MAT_DEPTH(ctype >= 0 ? ctype : type), _mean.depth()), CV_32F); - if( (flags & CV_COVAR_USE_AVG) != 0 ) + if( (flags & cv::COVAR_USE_AVG) != 0 ) { CV_Assert( _mean.size() == size ); if( _mean.isContinuous() && _mean.type() == ctype ) @@ -722,8 +722,8 @@ void calcCovarMatrix( const Mat* data, int nsamples, Mat& covar, Mat& _mean, int } } - calcCovarMatrix( _data, covar, mean, (flags & ~(CV_COVAR_ROWS|CV_COVAR_COLS)) | CV_COVAR_ROWS, ctype ); - if( (flags & CV_COVAR_USE_AVG) == 0 ) + calcCovarMatrix( _data, covar, mean, (flags & ~(cv::COVAR_ROWS|cv::COVAR_COLS)) | cv::COVAR_ROWS, ctype ); + if( (flags & cv::COVAR_USE_AVG) == 0 ) _mean = mean.reshape(1, size.height); } @@ -754,7 +754,7 @@ void calcCovarMatrix( InputArray _src, OutputArray _covar, InputOutputArray _mea } Mat mean; - if( (flags & CV_COVAR_USE_AVG) != 0 ) + if( (flags & cv::COVAR_USE_AVG) != 0 ) { CV_Assert( _mean.size() == size ); @@ -770,9 +770,9 @@ void calcCovarMatrix( InputArray _src, OutputArray _covar, InputOutputArray _mea mean = _mean.getMat().reshape(1, 1); } - calcCovarMatrix( _data, _covar, mean, (flags & ~(CV_COVAR_ROWS|CV_COVAR_COLS)) | CV_COVAR_ROWS, ctype ); + calcCovarMatrix( _data, _covar, mean, (flags & ~(cv::COVAR_ROWS|cv::COVAR_COLS)) | cv::COVAR_ROWS, ctype ); - if( (flags & CV_COVAR_USE_AVG) == 0 ) + if( (flags & cv::COVAR_USE_AVG) == 0 ) { mean = mean.reshape(1, size.height); mean.copyTo(_mean); @@ -781,14 +781,14 @@ void calcCovarMatrix( InputArray _src, OutputArray _covar, InputOutputArray _mea } Mat data = _src.getMat(), mean; - CV_Assert( ((flags & CV_COVAR_ROWS) != 0) ^ ((flags & CV_COVAR_COLS) != 0) ); - bool takeRows = (flags & CV_COVAR_ROWS) != 0; + CV_Assert( ((flags & cv::COVAR_ROWS) != 0) ^ ((flags & cv::COVAR_COLS) != 0) ); + bool takeRows = (flags & cv::COVAR_ROWS) != 0; int type = data.type(); int nsamples = takeRows ? data.rows : data.cols; CV_Assert( nsamples > 0 ); Size size = takeRows ? Size(data.cols, 1) : Size(1, data.rows); - if( (flags & CV_COVAR_USE_AVG) != 0 ) + if( (flags & cv::COVAR_USE_AVG) != 0 ) { mean = _mean.getMat(); ctype = std::max(std::max(CV_MAT_DEPTH(ctype >= 0 ? ctype : type), mean.depth()), CV_32F); @@ -808,8 +808,8 @@ void calcCovarMatrix( InputArray _src, OutputArray _covar, InputOutputArray _mea mean = _mean.getMat(); } - mulTransposed( data, _covar, ((flags & CV_COVAR_NORMAL) == 0) ^ takeRows, - mean, (flags & CV_COVAR_SCALE) != 0 ? 1./nsamples : 1, ctype ); + mulTransposed( data, _covar, ((flags & cv::COVAR_NORMAL) == 0) ^ takeRows, + mean, (flags & cv::COVAR_SCALE) != 0 ? 1./nsamples : 1, ctype ); } @@ -1097,233 +1097,4 @@ double UMat::dot(InputArray m) const } } // namespace cv:: - - -#ifndef OPENCV_EXCLUDE_C_API -/****************************************************************************************\ -* Earlier API * -\****************************************************************************************/ - -CV_IMPL void cvGEMM( const CvArr* Aarr, const CvArr* Barr, double alpha, - const CvArr* Carr, double beta, CvArr* Darr, int flags ) -{ - cv::Mat A = cv::cvarrToMat(Aarr), B = cv::cvarrToMat(Barr); - cv::Mat C, D = cv::cvarrToMat(Darr); - - if( Carr ) - C = cv::cvarrToMat(Carr); - - CV_Assert_N( (D.rows == ((flags & CV_GEMM_A_T) == 0 ? A.rows : A.cols)), - (D.cols == ((flags & CV_GEMM_B_T) == 0 ? B.cols : B.rows)), - D.type() == A.type() ); - - gemm( A, B, alpha, C, beta, D, flags ); -} - - -CV_IMPL void -cvTransform( const CvArr* srcarr, CvArr* dstarr, - const CvMat* transmat, const CvMat* shiftvec ) -{ - cv::Mat m = cv::cvarrToMat(transmat), src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - if( shiftvec ) - { - cv::Mat v = cv::cvarrToMat(shiftvec).reshape(1,m.rows), - _m(m.rows, m.cols + 1, m.type()), m1 = _m.colRange(0,m.cols), v1 = _m.col(m.cols); - m.convertTo(m1, m1.type()); - v.convertTo(v1, v1.type()); - m = _m; - } - - CV_Assert_N( dst.depth() == src.depth(), dst.channels() == m.rows ); - cv::transform( src, dst, m ); -} - - -CV_IMPL void -cvPerspectiveTransform( const CvArr* srcarr, CvArr* dstarr, const CvMat* mat ) -{ - cv::Mat m = cv::cvarrToMat(mat), src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert_N( dst.type() == src.type(), dst.channels() == m.rows-1 ); - cv::perspectiveTransform( src, dst, m ); -} - - -CV_IMPL void cvScaleAdd( const CvArr* srcarr1, CvScalar scale, - const CvArr* srcarr2, CvArr* dstarr ) -{ - cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr); - - CV_Assert_N( src1.size == dst.size, src1.type() == dst.type() ); - cv::scaleAdd( src1, scale.val[0], cv::cvarrToMat(srcarr2), dst ); -} - - -CV_IMPL void -cvCalcCovarMatrix( const CvArr** vecarr, int count, - CvArr* covarr, CvArr* avgarr, int flags ) -{ - cv::Mat cov0 = cv::cvarrToMat(covarr), cov = cov0, mean0, mean; - CV_Assert_N( vecarr != 0, count >= 1 ); - - if( avgarr ) - mean = mean0 = cv::cvarrToMat(avgarr); - - if( (flags & CV_COVAR_COLS) != 0 || (flags & CV_COVAR_ROWS) != 0 ) - { - - cv::Mat data = cv::cvarrToMat(vecarr[0]); - cv::calcCovarMatrix( data, cov, mean, flags, cov.type() ); - } - else - { - std::vector data(count); - for( int i = 0; i < count; i++ ) - data[i] = cv::cvarrToMat(vecarr[i]); - cv::calcCovarMatrix( &data[0], count, cov, mean, flags, cov.type() ); - } - - if( mean.data != mean0.data && mean0.data ) - mean.convertTo(mean0, mean0.type()); - - if( cov.data != cov0.data ) - cov.convertTo(cov0, cov0.type()); -} - - -CV_IMPL double -cvMahalanobis( const CvArr* srcAarr, const CvArr* srcBarr, const CvArr* matarr ) -{ - return cv::Mahalanobis(cv::cvarrToMat(srcAarr), - cv::cvarrToMat(srcBarr), cv::cvarrToMat(matarr)); -} - -CV_IMPL void -cvMulTransposed( const CvArr* srcarr, CvArr* dstarr, - int order, const CvArr* deltaarr, double scale ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0, delta; - if( deltaarr ) - delta = cv::cvarrToMat(deltaarr); - cv::mulTransposed( src, dst, order != 0, delta, scale, dst.type()); - if( dst.data != dst0.data ) - dst.convertTo(dst0, dst0.type()); -} - -CV_IMPL double cvDotProduct( const CvArr* srcAarr, const CvArr* srcBarr ) -{ - return cv::cvarrToMat(srcAarr).dot(cv::cvarrToMat(srcBarr)); -} - - -CV_IMPL void -cvCalcPCA( const CvArr* data_arr, CvArr* avg_arr, CvArr* eigenvals, CvArr* eigenvects, int flags ) -{ - cv::Mat data = cv::cvarrToMat(data_arr), mean0 = cv::cvarrToMat(avg_arr); - cv::Mat evals0 = cv::cvarrToMat(eigenvals), evects0 = cv::cvarrToMat(eigenvects); - cv::Mat mean = mean0, evals = evals0, evects = evects0; - - cv::PCA pca; - pca.mean = mean; - pca.eigenvalues = evals; - pca.eigenvectors = evects; - - pca(data, (flags & cv::PCA::USE_AVG) ? mean : cv::Mat(), - flags, !evals.empty() ? evals.rows + evals.cols - 1 : 0); - - if( pca.mean.size() == mean.size() ) - pca.mean.convertTo( mean, mean.type() ); - else - { - cv::Mat temp; pca.mean.convertTo( temp, mean.type() ); - transpose( temp, mean ); - } - - evals = pca.eigenvalues; - evects = pca.eigenvectors; - int ecount0 = evals0.cols + evals0.rows - 1; - int ecount = evals.cols + evals.rows - 1; - - CV_Assert_N( (evals0.cols == 1 || evals0.rows == 1), - ecount0 <= ecount, - evects0.cols == evects.cols, - evects0.rows == ecount0 ); - - cv::Mat temp = evals0; - if( evals.rows == 1 ) - evals.colRange(0, ecount0).convertTo(temp, evals0.type()); - else - evals.rowRange(0, ecount0).convertTo(temp, evals0.type()); - if( temp.data != evals0.data ) - transpose(temp, evals0); - evects.rowRange(0, ecount0).convertTo( evects0, evects0.type() ); - - // otherwise some datatype's or size's were incorrect, so the output arrays have been reallocated - CV_Assert( mean0.data == mean.data ); -} - - -CV_IMPL void -cvProjectPCA( const CvArr* data_arr, const CvArr* avg_arr, - const CvArr* eigenvects, CvArr* result_arr ) -{ - cv::Mat data = cv::cvarrToMat(data_arr), mean = cv::cvarrToMat(avg_arr); - cv::Mat evects = cv::cvarrToMat(eigenvects), dst0 = cv::cvarrToMat(result_arr), dst = dst0; - - cv::PCA pca; - pca.mean = mean; - int n; - if( mean.rows == 1 ) - { - CV_Assert_N(dst.cols <= evects.rows, dst.rows == data.rows); - n = dst.cols; - } - else - { - CV_Assert_N(dst.rows <= evects.rows, dst.cols == data.cols); - n = dst.rows; - } - pca.eigenvectors = evects.rowRange(0, n); - - cv::Mat result = pca.project(data); - if( result.cols != dst.cols ) - result = result.reshape(1, 1); - result.convertTo(dst, dst.type()); - - CV_Assert(dst0.data == dst.data); -} - - -CV_IMPL void -cvBackProjectPCA( const CvArr* proj_arr, const CvArr* avg_arr, - const CvArr* eigenvects, CvArr* result_arr ) -{ - cv::Mat data = cv::cvarrToMat(proj_arr), mean = cv::cvarrToMat(avg_arr); - cv::Mat evects = cv::cvarrToMat(eigenvects), dst0 = cv::cvarrToMat(result_arr), dst = dst0; - - cv::PCA pca; - pca.mean = mean; - int n; - if( mean.rows == 1 ) - { - CV_Assert_N(data.cols <= evects.rows, dst.rows == data.rows); - n = data.cols; - } - else - { - CV_Assert_N(data.rows <= evects.rows, dst.cols == data.cols); - n = data.rows; - } - pca.eigenvectors = evects.rowRange(0, n); - - cv::Mat result = pca.backProject(data); - result.convertTo(dst, dst.type()); - - CV_Assert(dst0.data == dst.data); -} - -#endif // OPENCV_EXCLUDE_C_API - /* End of file. */ diff --git a/modules/core/src/matrix_c.cpp b/modules/core/src/matrix_c.cpp deleted file mode 100644 index 0054d0a534..0000000000 --- a/modules/core/src/matrix_c.cpp +++ /dev/null @@ -1,328 +0,0 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#include "precomp.hpp" -#include "opencv2/core/mat.hpp" -#include "opencv2/core/types_c.h" - -#ifndef OPENCV_EXCLUDE_C_API -// glue - -CvMatND cvMatND(const cv::Mat& m) -{ - CvMatND self; - cvInitMatNDHeader(&self, m.dims, m.size, m.type(), m.data ); - int i, d = m.dims; - for( i = 0; i < d; i++ ) - self.dim[i].step = (int)m.step[i]; - self.type |= m.flags & cv::Mat::CONTINUOUS_FLAG; - return self; -} - -_IplImage cvIplImage(const cv::Mat& m) -{ - _IplImage self; - CV_Assert( m.dims <= 2 ); - cvInitImageHeader(&self, cvSize(m.size()), cvIplDepth(m.flags), m.channels()); - cvSetData(&self, m.data, (int)m.step[0]); - return self; -} - -namespace cv { - -static Mat cvMatToMat(const CvMat* m, bool copyData) -{ - Mat thiz; - - if( !m ) - return thiz; - - if( !copyData ) - { - thiz.flags = Mat::MAGIC_VAL + (m->type & (CV_MAT_TYPE_MASK|CV_MAT_CONT_FLAG)); - thiz.dims = 2; - thiz.rows = m->rows; - thiz.cols = m->cols; - thiz.datastart = thiz.data = m->data.ptr; - size_t esz = CV_ELEM_SIZE(m->type), minstep = thiz.cols*esz, _step = m->step; - if( _step == 0 ) - _step = minstep; - thiz.datalimit = thiz.datastart + _step*thiz.rows; - thiz.dataend = thiz.datalimit - _step + minstep; - thiz.step[0] = _step; thiz.step[1] = esz; - } - else - { - thiz.datastart = thiz.dataend = thiz.data = 0; - Mat(m->rows, m->cols, m->type, m->data.ptr, m->step).copyTo(thiz); - } - - return thiz; -} - -static Mat cvMatNDToMat(const CvMatND* m, bool copyData) -{ - Mat thiz; - - if( !m ) - return thiz; - thiz.datastart = thiz.data = m->data.ptr; - thiz.flags |= CV_MAT_TYPE(m->type); - int _sizes[CV_MAX_DIM]; - size_t _steps[CV_MAX_DIM]; - - int d = m->dims; - for( int i = 0; i < d; i++ ) - { - _sizes[i] = m->dim[i].size; - _steps[i] = m->dim[i].step; - } - - setSize(thiz, d, _sizes, _steps); - finalizeHdr(thiz); - - if( copyData ) - { - Mat temp(thiz); - thiz.release(); - temp.copyTo(thiz); - } - - return thiz; -} - -static Mat iplImageToMat(const IplImage* img, bool copyData) -{ - Mat m; - - if( !img ) - return m; - - m.dims = 2; - CV_DbgAssert(CV_IS_IMAGE(img) && img->imageData != 0); - - int imgdepth = IPL2CV_DEPTH(img->depth); - size_t esz; - m.step[0] = img->widthStep; - - if(!img->roi) - { - CV_Assert(img->dataOrder == IPL_DATA_ORDER_PIXEL); - m.flags = Mat::MAGIC_VAL + CV_MAKETYPE(imgdepth, img->nChannels); - m.rows = img->height; - m.cols = img->width; - m.datastart = m.data = (uchar*)img->imageData; - esz = CV_ELEM_SIZE(m.flags); - } - else - { - CV_Assert(img->dataOrder == IPL_DATA_ORDER_PIXEL || img->roi->coi != 0); - bool selectedPlane = img->roi->coi && img->dataOrder == IPL_DATA_ORDER_PLANE; - m.flags = Mat::MAGIC_VAL + CV_MAKETYPE(imgdepth, selectedPlane ? 1 : img->nChannels); - m.rows = img->roi->height; - m.cols = img->roi->width; - esz = CV_ELEM_SIZE(m.flags); - m.datastart = m.data = (uchar*)img->imageData + - (selectedPlane ? (img->roi->coi - 1)*m.step*img->height : 0) + - img->roi->yOffset*m.step[0] + img->roi->xOffset*esz; - } - m.datalimit = m.datastart + m.step.p[0]*m.rows; - m.dataend = m.datastart + m.step.p[0]*(m.rows-1) + esz*m.cols; - m.step[1] = esz; - m.updateContinuityFlag(); - - if( copyData ) - { - Mat m2 = m; - m.release(); - if( !img->roi || !img->roi->coi || - img->dataOrder == IPL_DATA_ORDER_PLANE) - m2.copyTo(m); - else - { - int ch[] = {img->roi->coi - 1, 0}; - m.create(m2.rows, m2.cols, m2.type()); - mixChannels(&m2, 1, &m, 1, ch, 1); - } - } - - return m; -} - -Mat cvarrToMat(const CvArr* arr, bool copyData, - bool /*allowND*/, int coiMode, AutoBuffer* abuf ) -{ - if( !arr ) - return Mat(); - if( CV_IS_MAT_HDR_Z(arr) ) - return cvMatToMat((const CvMat*)arr, copyData); - if( CV_IS_MATND(arr) ) - return cvMatNDToMat((const CvMatND*)arr, copyData ); - if( CV_IS_IMAGE(arr) ) - { - const IplImage* iplimg = (const IplImage*)arr; - if( coiMode == 0 && iplimg->roi && iplimg->roi->coi > 0 ) - CV_Error(cv::Error::BadCOI, "COI is not supported by the function"); - return iplImageToMat(iplimg, copyData); - } - if( CV_IS_SEQ(arr) ) - { - CvSeq* seq = (CvSeq*)arr; - int total = seq->total, type = CV_MAT_TYPE(seq->flags), esz = seq->elem_size; - if( total == 0 ) - return Mat(); - CV_Assert(total > 0 && CV_ELEM_SIZE(seq->flags) == esz); - if(!copyData && seq->first->next == seq->first) - return Mat(total, 1, type, seq->first->data); - if( abuf ) - { - abuf->allocate(((size_t)total*esz + sizeof(double)-1)/sizeof(double)); - double* bufdata = abuf->data(); - cvCvtSeqToArray(seq, bufdata, CV_WHOLE_SEQ); - return Mat(total, 1, type, bufdata); - } - - Mat buf(total, 1, type); - cvCvtSeqToArray(seq, buf.ptr(), CV_WHOLE_SEQ); - return buf; - } - CV_Error(cv::Error::StsBadArg, "Unknown array type"); -} - -void extractImageCOI(const CvArr* arr, OutputArray _ch, int coi) -{ - Mat mat = cvarrToMat(arr, false, true, 1); - _ch.create(mat.dims, mat.size, mat.depth()); - Mat ch = _ch.getMat(); - if(coi < 0) - { - CV_Assert( CV_IS_IMAGE(arr) ); - coi = cvGetImageCOI((const IplImage*)arr)-1; - } - CV_Assert(0 <= coi && coi < mat.channels()); - int _pairs[] = { coi, 0 }; - mixChannels( &mat, 1, &ch, 1, _pairs, 1 ); -} - -} // cv:: - -// operations - -CV_IMPL void cvSetIdentity( CvArr* arr, CvScalar value ) -{ - cv::Mat m = cv::cvarrToMat(arr); - cv::setIdentity(m, value); -} - - -CV_IMPL CvScalar cvTrace( const CvArr* arr ) -{ - return cvScalar(cv::trace(cv::cvarrToMat(arr))); -} - - -CV_IMPL void cvTranspose( const CvArr* srcarr, CvArr* dstarr ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.rows == dst.cols && src.cols == dst.rows && src.type() == dst.type() ); - transpose( src, dst ); -} - - -CV_IMPL void cvCompleteSymm( CvMat* matrix, int LtoR ) -{ - cv::Mat m = cv::cvarrToMat(matrix); - cv::completeSymm( m, LtoR != 0 ); -} - - -CV_IMPL void cvCrossProduct( const CvArr* srcAarr, const CvArr* srcBarr, CvArr* dstarr ) -{ - cv::Mat srcA = cv::cvarrToMat(srcAarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( srcA.size() == dst.size() && srcA.type() == dst.type() ); - srcA.cross(cv::cvarrToMat(srcBarr)).copyTo(dst); -} - - -CV_IMPL void -cvReduce( const CvArr* srcarr, CvArr* dstarr, int dim, int op ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - if( dim < 0 ) - dim = src.rows > dst.rows ? 0 : src.cols > dst.cols ? 1 : dst.cols == 1; - - if( dim > 1 ) - CV_Error( cv::Error::StsOutOfRange, "The reduced dimensionality index is out of range" ); - - if( (dim == 0 && (dst.cols != src.cols || dst.rows != 1)) || - (dim == 1 && (dst.rows != src.rows || dst.cols != 1)) ) - CV_Error( cv::Error::StsBadSize, "The output array size is incorrect" ); - - if( src.channels() != dst.channels() ) - CV_Error( cv::Error::StsUnmatchedFormats, "Input and output arrays must have the same number of channels" ); - - cv::reduce(src, dst, dim, op, dst.type()); -} - - -CV_IMPL CvArr* -cvRange( CvArr* arr, double start, double end ) -{ - CvMat stub, *mat = (CvMat*)arr; - int step; - double val = start; - - if( !CV_IS_MAT(mat) ) - mat = cvGetMat( mat, &stub); - - int rows = mat->rows; - int cols = mat->cols; - int type = CV_MAT_TYPE(mat->type); - double delta = (end-start)/(rows*cols); - - if( CV_IS_MAT_CONT(mat->type) ) - { - cols *= rows; - rows = 1; - step = 1; - } - else - step = mat->step / CV_ELEM_SIZE(type); - - if( type == CV_32SC1 ) - { - int* idata = mat->data.i; - int ival = cvRound(val), idelta = cvRound(delta); - - if( fabs(val - ival) < DBL_EPSILON && - fabs(delta - idelta) < DBL_EPSILON ) - { - for( int i = 0; i < rows; i++, idata += step ) - for( int j = 0; j < cols; j++, ival += idelta ) - idata[j] = ival; - } - else - { - for( int i = 0; i < rows; i++, idata += step ) - for( int j = 0; j < cols; j++, val += delta ) - idata[j] = cvRound(val); - } - } - else if( type == CV_32FC1 ) - { - float* fdata = mat->data.fl; - for( int i = 0; i < rows; i++, fdata += step ) - for( int j = 0; j < cols; j++, val += delta ) - fdata[j] = (float)val; - } - else - CV_Error( cv::Error::StsUnsupportedFormat, "The function only supports 32sC1 and 32fC1 datatypes" ); - - return arr; -} - -#endif // OPENCV_EXCLUDE_C_API diff --git a/modules/core/src/matrix_expressions.cpp b/modules/core/src/matrix_expressions.cpp index b8ae284048..f42f7bff33 100644 --- a/modules/core/src/matrix_expressions.cpp +++ b/modules/core/src/matrix_expressions.cpp @@ -554,7 +554,7 @@ void MatOp::matmul(const MatExpr& e1, const MatExpr& e2, MatExpr& res) const if( isT(e1) ) { - flags = CV_GEMM_A_T; + flags = cv::GEMM_1_T; scale = e1.alpha; m1 = e1.a; } @@ -568,7 +568,7 @@ void MatOp::matmul(const MatExpr& e1, const MatExpr& e2, MatExpr& res) const if( isT(e2) ) { - flags |= CV_GEMM_B_T; + flags |= cv::GEMM_2_T; scale *= e2.alpha; m2 = e2.a; } @@ -946,7 +946,7 @@ MatExpr operator < (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LT, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_LT, a, b); return e; } @@ -954,7 +954,7 @@ MatExpr operator < (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LT, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_LT, a, s); return e; } @@ -962,7 +962,7 @@ MatExpr operator < (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GT, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_GT, a, s); return e; } @@ -970,7 +970,7 @@ MatExpr operator <= (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LE, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_LE, a, b); return e; } @@ -978,7 +978,7 @@ MatExpr operator <= (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_LE, a, s); return e; } @@ -986,7 +986,7 @@ MatExpr operator <= (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_GE, a, s); return e; } @@ -994,7 +994,7 @@ MatExpr operator == (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_EQ, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_EQ, a, b); return e; } @@ -1002,7 +1002,7 @@ MatExpr operator == (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_EQ, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_EQ, a, s); return e; } @@ -1010,7 +1010,7 @@ MatExpr operator == (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_EQ, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_EQ, a, s); return e; } @@ -1018,7 +1018,7 @@ MatExpr operator != (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_NE, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_NE, a, b); return e; } @@ -1026,7 +1026,7 @@ MatExpr operator != (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_NE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_NE, a, s); return e; } @@ -1034,7 +1034,7 @@ MatExpr operator != (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_NE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_NE, a, s); return e; } @@ -1042,7 +1042,7 @@ MatExpr operator >= (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GE, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_GE, a, b); return e; } @@ -1050,7 +1050,7 @@ MatExpr operator >= (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_GE, a, s); return e; } @@ -1058,7 +1058,7 @@ MatExpr operator >= (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LE, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_LE, a, s); return e; } @@ -1066,7 +1066,7 @@ MatExpr operator > (const Mat& a, const Mat& b) { checkOperandsExist(a, b); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GT, a, b); + MatOp_Cmp::makeExpr(e, cv::CMP_GT, a, b); return e; } @@ -1074,7 +1074,7 @@ MatExpr operator > (const Mat& a, double s) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_GT, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_GT, a, s); return e; } @@ -1082,7 +1082,7 @@ MatExpr operator > (double s, const Mat& a) { checkOperandsExist(a); MatExpr e; - MatOp_Cmp::makeExpr(e, CV_CMP_LT, a, s); + MatOp_Cmp::makeExpr(e, cv::CMP_LT, a, s); return e; } @@ -1574,10 +1574,10 @@ void MatOp_GEMM::add(const MatExpr& e1, const MatExpr& e2, MatExpr& res) const double alpha1 = i1 ? 1 : e1.alpha, alpha2 = i2 ? 1 : e2.alpha; if( isMatProd(e1) && (i2 || isScaled(e2) || isT(e2)) ) - MatOp_GEMM::makeExpr(res, (e1.flags & ~CV_GEMM_C_T)|(isT(e2) ? CV_GEMM_C_T : 0), + MatOp_GEMM::makeExpr(res, (e1.flags & ~cv::GEMM_3_T)|(isT(e2) ? cv::GEMM_3_T : 0), e1.a, e1.b, alpha1, e2.a, alpha2); else if( isMatProd(e2) && (i1 || isScaled(e1) || isT(e1)) ) - MatOp_GEMM::makeExpr(res, (e2.flags & ~CV_GEMM_C_T)|(isT(e1) ? CV_GEMM_C_T : 0), + MatOp_GEMM::makeExpr(res, (e2.flags & ~cv::GEMM_3_T)|(isT(e1) ? cv::GEMM_3_T : 0), e2.a, e2.b, alpha2, e1.a, alpha1); else if( this == e2.op ) MatOp::add(e1, e2, res); @@ -1593,10 +1593,10 @@ void MatOp_GEMM::subtract(const MatExpr& e1, const MatExpr& e2, MatExpr& res) co double alpha1 = i1 ? 1 : e1.alpha, alpha2 = i2 ? 1 : e2.alpha; if( isMatProd(e1) && (i2 || isScaled(e2) || isT(e2)) ) - MatOp_GEMM::makeExpr(res, (e1.flags & ~CV_GEMM_C_T)|(isT(e2) ? CV_GEMM_C_T : 0), + MatOp_GEMM::makeExpr(res, (e1.flags & ~cv::GEMM_3_T)|(isT(e2) ? cv::GEMM_3_T : 0), e1.a, e1.b, alpha1, e2.a, -alpha2); else if( isMatProd(e2) && (i1 || isScaled(e1) || isT(e1)) ) - MatOp_GEMM::makeExpr(res, (e2.flags & ~CV_GEMM_C_T)|(isT(e1) ? CV_GEMM_C_T : 0), + MatOp_GEMM::makeExpr(res, (e2.flags & ~cv::GEMM_3_T)|(isT(e1) ? cv::GEMM_3_T : 0), e2.a, e2.b, -alpha2, e1.a, alpha1); else if( this == e2.op ) MatOp::subtract(e1, e2, res); @@ -1618,9 +1618,9 @@ void MatOp_GEMM::transpose(const MatExpr& e, MatExpr& res) const CV_INSTRUMENT_REGION(); res = e; - res.flags = (!(e.flags & CV_GEMM_A_T) ? CV_GEMM_B_T : 0) | - (!(e.flags & CV_GEMM_B_T) ? CV_GEMM_A_T : 0) | - (!(e.flags & CV_GEMM_C_T) ? CV_GEMM_C_T : 0); + res.flags = (!(e.flags & cv::GEMM_1_T) ? cv::GEMM_2_T : 0) | + (!(e.flags & cv::GEMM_2_T) ? cv::GEMM_1_T : 0) | + (!(e.flags & cv::GEMM_3_T) ? cv::GEMM_3_T : 0); swap(res.a, res.b); } diff --git a/modules/core/src/matrix_operations.cpp b/modules/core/src/matrix_operations.cpp index fba9102d92..774ae6ad3a 100644 --- a/modules/core/src/matrix_operations.cpp +++ b/modules/core/src/matrix_operations.cpp @@ -4,7 +4,6 @@ #include "precomp.hpp" #include "opencv2/core/mat.hpp" -#include "opencv2/core/types_c.h" #include "opencl_kernels_core.hpp" #undef HAVE_IPP diff --git a/modules/core/src/matrix_sparse.cpp b/modules/core/src/matrix_sparse.cpp index 6ce9860956..9903e39dea 100644 --- a/modules/core/src/matrix_sparse.cpp +++ b/modules/core/src/matrix_sparse.cpp @@ -4,7 +4,6 @@ #include "precomp.hpp" #include "opencv2/core/mat.hpp" -#include "opencv2/core/types_c.h" namespace cv { @@ -851,41 +850,3 @@ void normalize( const SparseMat& src, SparseMat& dst, double a, int norm_type ) } } // cv:: - -// -// C-API glue -// -CvSparseMat* cvCreateSparseMat(const cv::SparseMat& sm) -{ - if( !sm.hdr || sm.hdr->dims > (int)cv::SparseMat::MAX_DIM) - return 0; - - CvSparseMat* m = cvCreateSparseMat(sm.hdr->dims, sm.hdr->size, sm.type()); - - cv::SparseMatConstIterator from = sm.begin(); - size_t i, N = sm.nzcount(), esz = sm.elemSize(); - - for( i = 0; i < N; i++, ++from ) - { - const cv::SparseMat::Node* n = from.node(); - uchar* to = cvPtrND(m, n->idx, 0, -2, 0); - cv::copyElem(from.ptr, to, esz); - } - return m; -} - -void CvSparseMat::copyToSparseMat(cv::SparseMat& m) const -{ - m.create( dims, &size[0], type ); - - CvSparseMatIterator it; - CvSparseNode* n = cvInitSparseMatIterator(this, &it); - size_t esz = m.elemSize(); - - for( ; n != 0; n = cvGetNextSparseNode(&it) ) - { - const int* idx = CV_NODE_IDX(this, n); - uchar* to = m.newNode(idx, m.hash(idx)); - cv::copyElem((const uchar*)CV_NODE_VAL(this, n), to, esz); - } -} diff --git a/modules/core/src/norm.cpp b/modules/core/src/norm.cpp index e2833e8e12..c2b5b5a2f7 100644 --- a/modules/core/src/norm.cpp +++ b/modules/core/src/norm.cpp @@ -1026,7 +1026,7 @@ static bool ipp_norm(InputArray _src1, InputArray _src2, int normType, InputArra #if IPP_VERSION_X100 >= 700 Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat(); - if( normType & CV_RELATIVE ) + if( normType & NORM_RELATIVE ) { normType &= NORM_TYPE_MASK; @@ -1257,9 +1257,9 @@ double norm( InputArray _src1, InputArray _src2, int normType, InputArray _mask CV_IPP_RUN(IPP_VERSION_X100 >= 700, ipp_norm(_src1, _src2, normType, _mask, _result), _result); - if( normType & CV_RELATIVE ) + if( normType & NORM_RELATIVE ) { - return norm(_src1, _src2, normType & ~CV_RELATIVE, _mask)/(norm(_src2, normType, _mask) + DBL_EPSILON); + return norm(_src1, _src2, normType & ~NORM_RELATIVE, _mask)/(norm(_src2, normType, _mask) + DBL_EPSILON); } Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat(); diff --git a/modules/core/src/pca.cpp b/modules/core/src/pca.cpp index 117002d946..e36afe4ff3 100644 --- a/modules/core/src/pca.cpp +++ b/modules/core/src/pca.cpp @@ -65,7 +65,7 @@ PCA::PCA(InputArray data, InputArray _mean, int flags, double retainedVariance) PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComponents) { Mat data = _data.getMat(), _mean = __mean.getMat(); - int covar_flags = CV_COVAR_SCALE; + int covar_flags = cv::COVAR_SCALE; int len, in_count; Size mean_sz; @@ -74,14 +74,14 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp { len = data.rows; in_count = data.cols; - covar_flags |= CV_COVAR_COLS; + covar_flags |= cv::COVAR_COLS; mean_sz = Size(1, len); } else { len = data.cols; in_count = data.rows; - covar_flags |= CV_COVAR_ROWS; + covar_flags |= cv::COVAR_ROWS; mean_sz = Size(len, 1); } @@ -92,7 +92,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp // "scrambled" way to compute PCA (when cols(A)>rows(A)): // B = A'A; B*x=b*x; C = AA'; C*y=c*y -> AA'*y=c*y -> A'A*(A'*y)=c*(A'*y) -> c = b, x=A'*y if( len <= in_count ) - covar_flags |= CV_COVAR_NORMAL; + covar_flags |= cv::COVAR_NORMAL; int ctype = std::max(CV_32F, data.depth()); mean.create( mean_sz, ctype ); @@ -103,13 +103,13 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp { CV_Assert( _mean.size() == mean_sz ); _mean.convertTo(mean, ctype); - covar_flags |= CV_COVAR_USE_AVG; + covar_flags |= cv::COVAR_USE_AVG; } calcCovarMatrix( data, covar, mean, covar_flags, ctype ); eigen( covar, eigenvalues, eigenvectors ); - if( !(covar_flags & CV_COVAR_NORMAL) ) + if( !(covar_flags & cv::COVAR_NORMAL) ) { // PCA::DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A // PCA::DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A' @@ -127,7 +127,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp Mat evects1(count, len, ctype); gemm( eigenvectors, tmp_data, 1, Mat(), 0, evects1, - (flags & PCA::DATA_AS_COL) ? CV_GEMM_B_T : 0); + (flags & PCA::DATA_AS_COL) ? cv::GEMM_2_T : 0); eigenvectors = evects1; // normalize eigenvectors @@ -201,7 +201,7 @@ int computeCumulativeEnergy(const Mat& eigenvalues, double retainedVariance) PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double retainedVariance) { Mat data = _data.getMat(), _mean = __mean.getMat(); - int covar_flags = CV_COVAR_SCALE; + int covar_flags = cv::COVAR_SCALE; int len, in_count; Size mean_sz; @@ -210,14 +210,14 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta { len = data.rows; in_count = data.cols; - covar_flags |= CV_COVAR_COLS; + covar_flags |= cv::COVAR_COLS; mean_sz = Size(1, len); } else { len = data.cols; in_count = data.rows; - covar_flags |= CV_COVAR_ROWS; + covar_flags |= cv::COVAR_ROWS; mean_sz = Size(len, 1); } @@ -228,7 +228,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta // "scrambled" way to compute PCA (when cols(A)>rows(A)): // B = A'A; B*x=b*x; C = AA'; C*y=c*y -> AA'*y=c*y -> A'A*(A'*y)=c*(A'*y) -> c = b, x=A'*y if( len <= in_count ) - covar_flags |= CV_COVAR_NORMAL; + covar_flags |= cv::COVAR_NORMAL; int ctype = std::max(CV_32F, data.depth()); mean.create( mean_sz, ctype ); @@ -239,13 +239,13 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta { CV_Assert( _mean.size() == mean_sz ); _mean.convertTo(mean, ctype); - covar_flags |= CV_COVAR_USE_AVG; + covar_flags |= cv::COVAR_USE_AVG; } calcCovarMatrix( data, covar, mean, covar_flags, ctype ); eigen( covar, eigenvalues, eigenvectors ); - if( !(covar_flags & CV_COVAR_NORMAL) ) + if( !(covar_flags & cv::COVAR_NORMAL) ) { // PCA::DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A // PCA::DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A' @@ -263,7 +263,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta Mat evects1(count, len, ctype); gemm( eigenvectors, tmp_data, 1, Mat(), 0, evects1, - (flags & PCA::DATA_AS_COL) ? CV_GEMM_B_T : 0); + (flags & PCA::DATA_AS_COL) ? cv::GEMM_2_T : 0); eigenvectors = evects1; // normalize all eigenvectors diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 693c830057..d0ed1c9a74 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -11,6 +11,8 @@ #include +#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) + namespace cv { diff --git a/modules/core/src/persistence.hpp b/modules/core/src/persistence.hpp index 2a1f73cba8..55ccd51254 100644 --- a/modules/core/src/persistence.hpp +++ b/modules/core/src/persistence.hpp @@ -6,7 +6,6 @@ #ifndef SRC_PERSISTENCE_HPP #define SRC_PERSISTENCE_HPP -#include "opencv2/core/types_c.h" #include #include #include diff --git a/modules/core/src/precomp.hpp b/modules/core/src/precomp.hpp index 2f430a8b7b..d274bcdb42 100644 --- a/modules/core/src/precomp.hpp +++ b/modules/core/src/precomp.hpp @@ -56,7 +56,6 @@ #include "cvconfig.h" #include "opencv2/core/utility.hpp" -#include "opencv2/core/core_c.h" #include "opencv2/core/cuda.hpp" #include "opencv2/core/opengl.hpp" #include "opencv2/core/va_intel.hpp" diff --git a/modules/core/src/rand.cpp b/modules/core/src/rand.cpp index f3234dae6b..604d3f6ac0 100644 --- a/modules/core/src/rand.cpp +++ b/modules/core/src/rand.cpp @@ -47,6 +47,8 @@ namespace cv ///////////////////////////// Functions Declaration ////////////////////////////////////// +#define CV_RNG_COEFF 4164903690U + /* Multiply-with-carry generator is used here: temp = ( A*X(n) + carry ) diff --git a/modules/core/src/stat_c.cpp b/modules/core/src/stat_c.cpp deleted file mode 100644 index 8b6f0f09e4..0000000000 --- a/modules/core/src/stat_c.cpp +++ /dev/null @@ -1,123 +0,0 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - - -#include "precomp.hpp" - -#ifndef OPENCV_EXCLUDE_C_API - -CV_IMPL CvScalar cvSum( const CvArr* srcarr ) -{ - cv::Scalar sum = cv::sum(cv::cvarrToMat(srcarr, false, true, 1)); - if( CV_IS_IMAGE(srcarr) ) - { - int coi = cvGetImageCOI((IplImage*)srcarr); - if( coi ) - { - CV_Assert( 0 < coi && coi <= 4 ); - sum = cv::Scalar(sum[coi-1]); - } - } - return cvScalar(sum); -} - -CV_IMPL int cvCountNonZero( const CvArr* imgarr ) -{ - cv::Mat img = cv::cvarrToMat(imgarr, false, true, 1); - if( img.channels() > 1 ) - cv::extractImageCOI(imgarr, img); - return countNonZero(img); -} - - -CV_IMPL CvScalar -cvAvg( const void* imgarr, const void* maskarr ) -{ - cv::Mat img = cv::cvarrToMat(imgarr, false, true, 1); - cv::Scalar mean = !maskarr ? cv::mean(img) : cv::mean(img, cv::cvarrToMat(maskarr)); - if( CV_IS_IMAGE(imgarr) ) - { - int coi = cvGetImageCOI((IplImage*)imgarr); - if( coi ) - { - CV_Assert( 0 < coi && coi <= 4 ); - mean = cv::Scalar(mean[coi-1]); - } - } - return cvScalar(mean); -} - - -CV_IMPL void -cvAvgSdv( const CvArr* imgarr, CvScalar* _mean, CvScalar* _sdv, const void* maskarr ) -{ - cv::Scalar mean, sdv; - - cv::Mat mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - - cv::meanStdDev(cv::cvarrToMat(imgarr, false, true, 1), mean, sdv, mask ); - - if( CV_IS_IMAGE(imgarr) ) - { - int coi = cvGetImageCOI((IplImage*)imgarr); - if( coi ) - { - CV_Assert( 0 < coi && coi <= 4 ); - mean = cv::Scalar(mean[coi-1]); - sdv = cv::Scalar(sdv[coi-1]); - } - } - - if( _mean ) - *(cv::Scalar*)_mean = mean; - if( _sdv ) - *(cv::Scalar*)_sdv = sdv; -} - - -CV_IMPL void -cvMinMaxLoc( const void* imgarr, double* _minVal, double* _maxVal, - CvPoint* _minLoc, CvPoint* _maxLoc, const void* maskarr ) -{ - cv::Mat mask, img = cv::cvarrToMat(imgarr, false, true, 1); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - if( img.channels() > 1 ) - cv::extractImageCOI(imgarr, img); - - cv::minMaxLoc( img, _minVal, _maxVal, - (cv::Point*)_minLoc, (cv::Point*)_maxLoc, mask ); -} - - -CV_IMPL double -cvNorm( const void* imgA, const void* imgB, int normType, const void* maskarr ) -{ - cv::Mat a, mask; - if( !imgA ) - { - imgA = imgB; - imgB = 0; - } - - a = cv::cvarrToMat(imgA, false, true, 1); - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - - if( a.channels() > 1 && CV_IS_IMAGE(imgA) && cvGetImageCOI((const IplImage*)imgA) > 0 ) - cv::extractImageCOI(imgA, a); - - if( !imgB ) - return !maskarr ? cv::norm(a, normType) : cv::norm(a, normType, mask); - - cv::Mat b = cv::cvarrToMat(imgB, false, true, 1); - if( b.channels() > 1 && CV_IS_IMAGE(imgB) && cvGetImageCOI((const IplImage*)imgB) > 0 ) - cv::extractImageCOI(imgB, b); - - return !maskarr ? cv::norm(a, b, normType) : cv::norm(a, b, normType, mask); -} - -#endif // OPENCV_EXCLUDE_C_API diff --git a/modules/core/src/system.cpp b/modules/core/src/system.cpp index 662469f471..4f62701e47 100644 --- a/modules/core/src/system.cpp +++ b/modules/core/src/system.cpp @@ -42,6 +42,7 @@ //M*/ #include "precomp.hpp" +//#include "opencv2/core/core_c.h" #include #include #include @@ -1380,57 +1381,6 @@ void terminate(Error::Code _code, const String& _err, const char* _func, const c } -CV_IMPL int cvGetErrMode(void) -{ - return 0; -} - -CV_IMPL int cvSetErrMode(int) -{ - return 0; -} - -CV_IMPL int cvGetErrStatus(void) -{ - return 0; -} - -CV_IMPL void cvSetErrStatus(int) -{ -} - -/* function, which converts int to int */ -CV_IMPL int -cvErrorFromIppStatus( int status ) -{ - switch (status) - { - case CV_BADSIZE_ERR: return cv::Error::StsBadSize; - case CV_BADMEMBLOCK_ERR: return cv::Error::StsBadMemBlock; - case CV_NULLPTR_ERR: return cv::Error::StsNullPtr; - case CV_DIV_BY_ZERO_ERR: return cv::Error::StsDivByZero; - case CV_BADSTEP_ERR: return cv::Error::BadStep; - case CV_OUTOFMEM_ERR: return cv::Error::StsNoMem; - case CV_BADARG_ERR: return cv::Error::StsBadArg; - case CV_NOTDEFINED_ERR: return cv::Error::StsError; - case CV_INPLACE_NOT_SUPPORTED_ERR: return cv::Error::StsInplaceNotSupported; - case CV_NOTFOUND_ERR: return cv::Error::StsObjectNotFound; - case CV_BADCONVERGENCE_ERR: return cv::Error::StsNoConv; - case CV_BADDEPTH_ERR: return cv::Error::BadDepth; - case CV_UNMATCHED_FORMATS_ERR: return cv::Error::StsUnmatchedFormats; - case CV_UNSUPPORTED_COI_ERR: return cv::Error::BadCOI; - case CV_UNSUPPORTED_CHANNELS_ERR: return cv::Error::BadNumChannels; - case CV_BADFLAG_ERR: return cv::Error::StsBadFlag; - case CV_BADRANGE_ERR: return cv::Error::StsBadArg; - case CV_BADCOEF_ERR: return cv::Error::StsBadArg; - case CV_BADFACTOR_ERR: return cv::Error::StsBadArg; - case CV_BADPOINT_ERR: return cv::Error::StsBadPoint; - - default: - return cv::Error::StsError; - } -} - namespace cv { bool __termination = false;