diff --git a/HuaGoCorrect/HuaGoCorrect.vcxproj b/HuaGoCorrect/HuaGoCorrect.vcxproj index 110900f..cb14a15 100644 --- a/HuaGoCorrect/HuaGoCorrect.vcxproj +++ b/HuaGoCorrect/HuaGoCorrect.vcxproj @@ -101,8 +101,7 @@ Windows true .\pub\external\lib;.\pub\opencv\lib;D:\local\boost_1_71_0_b1_rc1\lib32-msvc-14.1 - turbojpeg.lib;opencv_core2410d.lib;opencv_highgui2410d.lib; -opencv_imgproc2410d.lib;%(AdditionalDependencies) + turbojpeg.lib;opencv_world346d.lib;%(AdditionalDependencies) false @@ -160,8 +159,7 @@ opencv_imgproc2410d.lib;%(AdditionalDependencies) true true .\pub\external\lib;.\pub\opencv\lib;D:\local\boost_1_71_0_b1_rc1\lib32-msvc-14.1 - turbojpeg.lib;opencv_core2410.lib;opencv_highgui2410.lib; -opencv_imgproc2410.lib;%(AdditionalDependencies) + turbojpeg.lib;opencv_world346.lib;%(AdditionalDependencies) false diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_core2410.dll b/HuaGoCorrect/pub/opencv/bin/opencv_core2410.dll deleted file mode 100644 index 8cf9b7e..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_core2410.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_core2410d.dll b/HuaGoCorrect/pub/opencv/bin/opencv_core2410d.dll deleted file mode 100644 index da33716..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_core2410d.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410.dll b/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410.dll deleted file mode 100644 index 1ee478f..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410d.dll b/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410d.dll deleted file mode 100644 index b57cd8a..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_highgui2410d.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410.dll b/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410.dll deleted file mode 100644 index cd4368e..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410d.dll b/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410d.dll deleted file mode 100644 index 9f41689..0000000 Binary files a/HuaGoCorrect/pub/opencv/bin/opencv_imgproc2410d.dll and /dev/null differ diff --git a/HuaGoCorrect/pub/opencv/bin/opencv_world346.dll b/HuaGoCorrect/pub/opencv/bin/opencv_world346.dll new file mode 100644 index 0000000..2b0a2c6 Binary files /dev/null and b/HuaGoCorrect/pub/opencv/bin/opencv_world346.dll differ diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cv.h b/HuaGoCorrect/pub/opencv/include/opencv/cv.h index 77d0971..19a74e2 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cv.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/cv.h @@ -40,8 +40,8 @@ // //M*/ -#ifndef __OPENCV_OLD_CV_H__ -#define __OPENCV_OLD_CV_H__ +#ifndef OPENCV_OLD_CV_H +#define OPENCV_OLD_CV_H #if defined(_MSC_VER) #define CV_DO_PRAGMA(x) __pragma(x) @@ -61,22 +61,13 @@ //CV_WARNING("This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module") #include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/video/tracking.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/flann/flann.hpp" -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/objdetect/objdetect.hpp" -#include "opencv2/legacy/compat.hpp" +#include "opencv2/photo/photo_c.h" +#include "opencv2/video/tracking_c.h" +#include "opencv2/objdetect/objdetect_c.h" #if !defined(CV_IMPL) #define CV_IMPL extern "C" #endif //CV_IMPL -#if defined(__cplusplus) -#include "opencv2/core/internal.hpp" -#endif //__cplusplus - #endif // __OPENCV_OLD_CV_H_ diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cv.hpp b/HuaGoCorrect/pub/opencv/include/opencv/cv.hpp index 37b523b..8673956 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cv.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv/cv.hpp @@ -40,13 +40,21 @@ // //M*/ -#ifndef __OPENCV_OLD_CV_HPP__ -#define __OPENCV_OLD_CV_HPP__ +#ifndef OPENCV_OLD_CV_HPP +#define OPENCV_OLD_CV_HPP //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif -#include +#include "cv.h" +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/photo.hpp" +#include "opencv2/video.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/features2d.hpp" +#include "opencv2/calib3d.hpp" +#include "opencv2/objdetect.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cvaux.h b/HuaGoCorrect/pub/opencv/include/opencv/cvaux.h index b15d068..c0367cc 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cvaux.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/cvaux.h @@ -39,26 +39,18 @@ // //M*/ -#ifndef __OPENCV_OLD_AUX_H__ -#define __OPENCV_OLD_AUX_H__ +#ifndef OPENCV_OLD_AUX_H +#define OPENCV_OLD_AUX_H //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/video/tracking.hpp" -#include "opencv2/video/background_segm.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/objdetect/objdetect.hpp" -#include "opencv2/legacy/legacy.hpp" -#include "opencv2/legacy/compat.hpp" -#include "opencv2/legacy/blobtrack.hpp" -#include "opencv2/contrib/contrib.hpp" +#include "opencv2/photo/photo_c.h" +#include "opencv2/video/tracking_c.h" +#include "opencv2/objdetect/objdetect_c.h" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cvaux.hpp b/HuaGoCorrect/pub/opencv/include/opencv/cvaux.hpp index 952210b..4888eef 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cvaux.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv/cvaux.hpp @@ -39,13 +39,14 @@ // //M*/ -#ifndef __OPENCV_OLD_AUX_HPP__ -#define __OPENCV_OLD_AUX_HPP__ +#ifndef OPENCV_OLD_AUX_HPP +#define OPENCV_OLD_AUX_HPP //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif -#include +#include "cvaux.h" +#include "opencv2/core/utility.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cvwimage.h b/HuaGoCorrect/pub/opencv/include/opencv/cvwimage.h index de89c92..ec0ab14 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cvwimage.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/cvwimage.h @@ -38,8 +38,8 @@ // the use of this software, even if advised of the possibility of such damage. -#ifndef __OPENCV_OLD_WIMAGE_HPP__ -#define __OPENCV_OLD_WIMAGE_HPP__ +#ifndef OPENCV_OLD_WIMAGE_HPP +#define OPENCV_OLD_WIMAGE_HPP #include "opencv2/core/wimage.hpp" diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cxcore.h b/HuaGoCorrect/pub/opencv/include/opencv/cxcore.h index d52ad4f..dc070c7 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cxcore.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/cxcore.h @@ -40,14 +40,13 @@ // //M*/ -#ifndef __OPENCV_OLD_CXCORE_H__ -#define __OPENCV_OLD_CXCORE_H__ +#ifndef OPENCV_OLD_CXCORE_H +#define OPENCV_OLD_CXCORE_H //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cxcore.hpp b/HuaGoCorrect/pub/opencv/include/opencv/cxcore.hpp index 033b365..c371677 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cxcore.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv/cxcore.hpp @@ -40,13 +40,14 @@ // //M*/ -#ifndef __OPENCV_OLD_CXCORE_HPP__ -#define __OPENCV_OLD_CXCORE_HPP__ +#ifndef OPENCV_OLD_CXCORE_HPP +#define OPENCV_OLD_CXCORE_HPP //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif -#include +#include "cxcore.h" +#include "opencv2/core.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cxeigen.hpp b/HuaGoCorrect/pub/opencv/include/opencv/cxeigen.hpp index 1f04d1a..1d3df91 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cxeigen.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv/cxeigen.hpp @@ -40,8 +40,8 @@ // //M*/ -#ifndef __OPENCV_OLD_EIGEN_HPP__ -#define __OPENCV_OLD_EIGEN_HPP__ +#ifndef OPENCV_OLD_EIGEN_HPP +#define OPENCV_OLD_EIGEN_HPP #include "opencv2/core/eigen.hpp" diff --git a/HuaGoCorrect/pub/opencv/include/opencv/cxmisc.h b/HuaGoCorrect/pub/opencv/include/opencv/cxmisc.h index 6446944..9b9bc82 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/cxmisc.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/cxmisc.h @@ -1,6 +1,8 @@ -#ifndef __OPENCV_OLD_CXMISC_H__ -#define __OPENCV_OLD_CXMISC_H__ +#ifndef OPENCV_OLD_CXMISC_H +#define OPENCV_OLD_CXMISC_H -#include "opencv2/core/internal.hpp" +#ifdef __cplusplus +# include "opencv2/core/utility.hpp" +#endif #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/highgui.h b/HuaGoCorrect/pub/opencv/include/opencv/highgui.h index 9725c9f..69b394e 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/highgui.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/highgui.h @@ -39,12 +39,10 @@ // //M*/ -#ifndef __OPENCV_OLD_HIGHGUI_H__ -#define __OPENCV_OLD_HIGHGUI_H__ +#ifndef OPENCV_OLD_HIGHGUI_H +#define OPENCV_OLD_HIGHGUI_H #include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui_c.h" -#include "opencv2/highgui/highgui.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv/ml.h b/HuaGoCorrect/pub/opencv/include/opencv/ml.h index 0383a2f..0c376ba 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv/ml.h +++ b/HuaGoCorrect/pub/opencv/include/opencv/ml.h @@ -38,11 +38,10 @@ // //M*/ -#ifndef __OPENCV_OLD_ML_H__ -#define __OPENCV_OLD_ML_H__ +#ifndef OPENCV_OLD_ML_H +#define OPENCV_OLD_ML_H #include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" -#include "opencv2/ml/ml.hpp" +#include "opencv2/ml.hpp" #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/calib3d/calib3d.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/calib3d/calib3d.hpp index 5e9cde8..b3da45e 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/calib3d/calib3d.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/calib3d/calib3d.hpp @@ -7,11 +7,12 @@ // copy or use the software. // // -// License Agreement +// 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, @@ -40,772 +41,8 @@ // //M*/ -#ifndef __OPENCV_CALIB3D_HPP__ -#define __OPENCV_CALIB3D_HPP__ - -#include "opencv2/core/core.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/core/affine.hpp" - -#ifdef __cplusplus -extern "C" { +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library #endif -/****************************************************************************************\ -* Camera Calibration, Pose Estimation and Stereo * -\****************************************************************************************/ - -typedef struct CvPOSITObject CvPOSITObject; - -/* Allocates and initializes CvPOSITObject structure before doing cvPOSIT */ -CVAPI(CvPOSITObject*) cvCreatePOSITObject( CvPoint3D32f* points, int point_count ); - - -/* Runs POSIT (POSe from ITeration) algorithm for determining 3d position of - an object given its model and projection in a weak-perspective case */ -CVAPI(void) cvPOSIT( CvPOSITObject* posit_object, CvPoint2D32f* image_points, - double focal_length, CvTermCriteria criteria, - float* rotation_matrix, float* translation_vector); - -/* Releases CvPOSITObject structure */ -CVAPI(void) cvReleasePOSITObject( CvPOSITObject** posit_object ); - -/* updates the number of RANSAC iterations */ -CVAPI(int) cvRANSACUpdateNumIters( double p, double err_prob, - int model_points, int max_iters ); - -CVAPI(void) cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst ); - -/* Calculates fundamental matrix given a set of corresponding points */ -#define CV_FM_7POINT 1 -#define CV_FM_8POINT 2 - -#define CV_LMEDS 4 -#define CV_RANSAC 8 - -#define CV_FM_LMEDS_ONLY CV_LMEDS -#define CV_FM_RANSAC_ONLY CV_RANSAC -#define CV_FM_LMEDS CV_LMEDS -#define CV_FM_RANSAC CV_RANSAC - -enum -{ - CV_ITERATIVE = 0, - CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" - CV_P3P = 2 // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" -}; - -CVAPI(int) cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, - CvMat* fundamental_matrix, - int method CV_DEFAULT(CV_FM_RANSAC), - double param1 CV_DEFAULT(3.), double param2 CV_DEFAULT(0.99), - CvMat* status CV_DEFAULT(NULL) ); - -/* For each input point on one of images - computes parameters of the corresponding - epipolar line on the other image */ -CVAPI(void) cvComputeCorrespondEpilines( const CvMat* points, - int which_image, - const CvMat* fundamental_matrix, - CvMat* correspondent_lines ); - -/* Triangulation functions */ - -CVAPI(void) cvTriangulatePoints(CvMat* projMatr1, CvMat* projMatr2, - CvMat* projPoints1, CvMat* projPoints2, - CvMat* points4D); - -CVAPI(void) cvCorrectMatches(CvMat* F, CvMat* points1, CvMat* points2, - CvMat* new_points1, CvMat* new_points2); - - -/* Computes the optimal new camera matrix according to the free scaling parameter alpha: - alpha=0 - only valid pixels will be retained in the undistorted image - alpha=1 - all the source image pixels will be retained in the undistorted image -*/ -CVAPI(void) cvGetOptimalNewCameraMatrix( const CvMat* camera_matrix, - const CvMat* dist_coeffs, - CvSize image_size, double alpha, - CvMat* new_camera_matrix, - CvSize new_imag_size CV_DEFAULT(cvSize(0,0)), - CvRect* valid_pixel_ROI CV_DEFAULT(0), - int center_principal_point CV_DEFAULT(0)); - -/* Converts rotation vector to rotation matrix or vice versa */ -CVAPI(int) cvRodrigues2( const CvMat* src, CvMat* dst, - CvMat* jacobian CV_DEFAULT(0) ); - -/* Finds perspective transformation between the object plane and image (view) plane */ -CVAPI(int) cvFindHomography( const CvMat* src_points, - const CvMat* dst_points, - CvMat* homography, - int method CV_DEFAULT(0), - double ransacReprojThreshold CV_DEFAULT(3), - CvMat* mask CV_DEFAULT(0)); - -/* Computes RQ decomposition for 3x3 matrices */ -CVAPI(void) cvRQDecomp3x3( const CvMat *matrixM, CvMat *matrixR, CvMat *matrixQ, - CvMat *matrixQx CV_DEFAULT(NULL), - CvMat *matrixQy CV_DEFAULT(NULL), - CvMat *matrixQz CV_DEFAULT(NULL), - CvPoint3D64f *eulerAngles CV_DEFAULT(NULL)); - -/* Computes projection matrix decomposition */ -CVAPI(void) cvDecomposeProjectionMatrix( const CvMat *projMatr, CvMat *calibMatr, - CvMat *rotMatr, CvMat *posVect, - CvMat *rotMatrX CV_DEFAULT(NULL), - CvMat *rotMatrY CV_DEFAULT(NULL), - CvMat *rotMatrZ CV_DEFAULT(NULL), - CvPoint3D64f *eulerAngles CV_DEFAULT(NULL)); - -/* Computes d(AB)/dA and d(AB)/dB */ -CVAPI(void) cvCalcMatMulDeriv( const CvMat* A, const CvMat* B, CvMat* dABdA, CvMat* dABdB ); - -/* Computes r3 = rodrigues(rodrigues(r2)*rodrigues(r1)), - t3 = rodrigues(r2)*t1 + t2 and the respective derivatives */ -CVAPI(void) cvComposeRT( const CvMat* _rvec1, const CvMat* _tvec1, - const CvMat* _rvec2, const CvMat* _tvec2, - CvMat* _rvec3, CvMat* _tvec3, - CvMat* dr3dr1 CV_DEFAULT(0), CvMat* dr3dt1 CV_DEFAULT(0), - CvMat* dr3dr2 CV_DEFAULT(0), CvMat* dr3dt2 CV_DEFAULT(0), - CvMat* dt3dr1 CV_DEFAULT(0), CvMat* dt3dt1 CV_DEFAULT(0), - CvMat* dt3dr2 CV_DEFAULT(0), CvMat* dt3dt2 CV_DEFAULT(0) ); - -/* Projects object points to the view plane using - the specified extrinsic and intrinsic camera parameters */ -CVAPI(void) cvProjectPoints2( const CvMat* object_points, const CvMat* rotation_vector, - const CvMat* translation_vector, const CvMat* camera_matrix, - const CvMat* distortion_coeffs, CvMat* image_points, - CvMat* dpdrot CV_DEFAULT(NULL), CvMat* dpdt CV_DEFAULT(NULL), - CvMat* dpdf CV_DEFAULT(NULL), CvMat* dpdc CV_DEFAULT(NULL), - CvMat* dpddist CV_DEFAULT(NULL), - double aspect_ratio CV_DEFAULT(0)); - -/* Finds extrinsic camera parameters from - a few known corresponding point pairs and intrinsic parameters */ -CVAPI(void) cvFindExtrinsicCameraParams2( const CvMat* object_points, - const CvMat* image_points, - const CvMat* camera_matrix, - const CvMat* distortion_coeffs, - CvMat* rotation_vector, - CvMat* translation_vector, - int use_extrinsic_guess CV_DEFAULT(0) ); - -/* Computes initial estimate of the intrinsic camera parameters - in case of planar calibration target (e.g. chessboard) */ -CVAPI(void) cvInitIntrinsicParams2D( const CvMat* object_points, - const CvMat* image_points, - const CvMat* npoints, CvSize image_size, - CvMat* camera_matrix, - double aspect_ratio CV_DEFAULT(1.) ); - -#define CV_CALIB_CB_ADAPTIVE_THRESH 1 -#define CV_CALIB_CB_NORMALIZE_IMAGE 2 -#define CV_CALIB_CB_FILTER_QUADS 4 -#define CV_CALIB_CB_FAST_CHECK 8 - -// Performs a fast check if a chessboard is in the input image. This is a workaround to -// a problem of cvFindChessboardCorners being slow on images with no chessboard -// - src: input image -// - size: chessboard size -// Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, -// 0 if there is no chessboard, -1 in case of error -CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size); - - /* Detects corners on a chessboard calibration pattern */ -CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size, - CvPoint2D32f* corners, - int* corner_count CV_DEFAULT(NULL), - int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) ); - -/* Draws individual chessboard corners or the whole chessboard detected */ -CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size, - CvPoint2D32f* corners, - int count, int pattern_was_found ); - -#define CV_CALIB_USE_INTRINSIC_GUESS 1 -#define CV_CALIB_FIX_ASPECT_RATIO 2 -#define CV_CALIB_FIX_PRINCIPAL_POINT 4 -#define CV_CALIB_ZERO_TANGENT_DIST 8 -#define CV_CALIB_FIX_FOCAL_LENGTH 16 -#define CV_CALIB_FIX_K1 32 -#define CV_CALIB_FIX_K2 64 -#define CV_CALIB_FIX_K3 128 -#define CV_CALIB_FIX_K4 2048 -#define CV_CALIB_FIX_K5 4096 -#define CV_CALIB_FIX_K6 8192 -#define CV_CALIB_RATIONAL_MODEL 16384 - -/* Finds intrinsic and extrinsic camera parameters - from a few views of known calibration pattern */ -CVAPI(double) cvCalibrateCamera2( const CvMat* object_points, - const CvMat* image_points, - const CvMat* point_counts, - CvSize image_size, - CvMat* camera_matrix, - CvMat* distortion_coeffs, - CvMat* rotation_vectors CV_DEFAULT(NULL), - CvMat* translation_vectors CV_DEFAULT(NULL), - int flags CV_DEFAULT(0), - CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria( - CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON)) ); - -/* Computes various useful characteristics of the camera from the data computed by - cvCalibrateCamera2 */ -CVAPI(void) cvCalibrationMatrixValues( const CvMat *camera_matrix, - CvSize image_size, - double aperture_width CV_DEFAULT(0), - double aperture_height CV_DEFAULT(0), - double *fovx CV_DEFAULT(NULL), - double *fovy CV_DEFAULT(NULL), - double *focal_length CV_DEFAULT(NULL), - CvPoint2D64f *principal_point CV_DEFAULT(NULL), - double *pixel_aspect_ratio CV_DEFAULT(NULL)); - -#define CV_CALIB_FIX_INTRINSIC 256 -#define CV_CALIB_SAME_FOCAL_LENGTH 512 - -/* Computes the transformation from one camera coordinate system to another one - from a few correspondent views of the same calibration target. Optionally, calibrates - both cameras */ -CVAPI(double) cvStereoCalibrate( const CvMat* object_points, const CvMat* image_points1, - const CvMat* image_points2, const CvMat* npoints, - CvMat* camera_matrix1, CvMat* dist_coeffs1, - CvMat* camera_matrix2, CvMat* dist_coeffs2, - CvSize image_size, CvMat* R, CvMat* T, - CvMat* E CV_DEFAULT(0), CvMat* F CV_DEFAULT(0), - CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria( - CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,1e-6)), - int flags CV_DEFAULT(CV_CALIB_FIX_INTRINSIC)); - -#define CV_CALIB_ZERO_DISPARITY 1024 - -/* Computes 3D rotations (+ optional shift) for each camera coordinate system to make both - views parallel (=> to make all the epipolar lines horizontal or vertical) */ -CVAPI(void) cvStereoRectify( const CvMat* camera_matrix1, const CvMat* camera_matrix2, - const CvMat* dist_coeffs1, const CvMat* dist_coeffs2, - CvSize image_size, const CvMat* R, const CvMat* T, - CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2, - CvMat* Q CV_DEFAULT(0), - int flags CV_DEFAULT(CV_CALIB_ZERO_DISPARITY), - double alpha CV_DEFAULT(-1), - CvSize new_image_size CV_DEFAULT(cvSize(0,0)), - CvRect* valid_pix_ROI1 CV_DEFAULT(0), - CvRect* valid_pix_ROI2 CV_DEFAULT(0)); - -/* Computes rectification transformations for uncalibrated pair of images using a set - of point correspondences */ -CVAPI(int) cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2, - const CvMat* F, CvSize img_size, - CvMat* H1, CvMat* H2, - double threshold CV_DEFAULT(5)); - - - -/* stereo correspondence parameters and functions */ - -#define CV_STEREO_BM_NORMALIZED_RESPONSE 0 -#define CV_STEREO_BM_XSOBEL 1 - -/* Block matching algorithm structure */ -typedef struct CvStereoBMState -{ - // pre-filtering (normalization of input images) - int preFilterType; // =CV_STEREO_BM_NORMALIZED_RESPONSE now - int preFilterSize; // averaging window size: ~5x5..21x21 - int preFilterCap; // the output of pre-filtering is clipped by [-preFilterCap,preFilterCap] - - // correspondence using Sum of Absolute Difference (SAD) - int SADWindowSize; // ~5x5..21x21 - int minDisparity; // minimum disparity (can be negative) - int numberOfDisparities; // maximum disparity - minimum disparity (> 0) - - // post-filtering - int textureThreshold; // the disparity is only computed for pixels - // with textured enough neighborhood - int uniquenessRatio; // accept the computed disparity d* only if - // SAD(d) >= SAD(d*)*(1 + uniquenessRatio/100.) - // for any d != d*+/-1 within the search range. - int speckleWindowSize; // disparity variation window - int speckleRange; // acceptable range of variation in window - - int trySmallerWindows; // if 1, the results may be more accurate, - // at the expense of slower processing - CvRect roi1, roi2; - int disp12MaxDiff; - - // temporary buffers - CvMat* preFilteredImg0; - CvMat* preFilteredImg1; - CvMat* slidingSumBuf; - CvMat* cost; - CvMat* disp; -} CvStereoBMState; - -#define CV_STEREO_BM_BASIC 0 -#define CV_STEREO_BM_FISH_EYE 1 -#define CV_STEREO_BM_NARROW 2 - -CVAPI(CvStereoBMState*) cvCreateStereoBMState(int preset CV_DEFAULT(CV_STEREO_BM_BASIC), - int numberOfDisparities CV_DEFAULT(0)); - -CVAPI(void) cvReleaseStereoBMState( CvStereoBMState** state ); - -CVAPI(void) cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, - CvArr* disparity, CvStereoBMState* state ); - -CVAPI(CvRect) cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity, - int numberOfDisparities, int SADWindowSize ); - -CVAPI(void) cvValidateDisparity( CvArr* disparity, const CvArr* cost, - int minDisparity, int numberOfDisparities, - int disp12MaxDiff CV_DEFAULT(1) ); - -/* Reprojects the computed disparity image to the 3D space using the specified 4x4 matrix */ -CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage, - CvArr* _3dImage, const CvMat* Q, - int handleMissingValues CV_DEFAULT(0) ); - - -#ifdef __cplusplus -} - -////////////////////////////////////////////////////////////////////////////////////////// -class CV_EXPORTS CvLevMarq -{ -public: - CvLevMarq(); - CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - ~CvLevMarq(); - void init( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); - bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - - void clear(); - void step(); - enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - - cv::Ptr mask; - cv::Ptr prevParam; - cv::Ptr param; - cv::Ptr J; - cv::Ptr err; - cv::Ptr JtJ; - cv::Ptr JtJN; - cv::Ptr JtErr; - cv::Ptr JtJV; - cv::Ptr JtJW; - double prevErrNorm, errNorm; - int lambdaLg10; - CvTermCriteria criteria; - int state; - int iters; - bool completeSymmFlag; -}; - -namespace cv -{ -//! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation -CV_EXPORTS_W void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian=noArray()); - -//! type of the robust estimation algorithm -enum -{ - LMEDS=CV_LMEDS, //!< least-median algorithm - RANSAC=CV_RANSAC //!< RANSAC algorithm -}; - -//! computes the best-fit perspective transformation mapping srcPoints to dstPoints. -CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, - int method=0, double ransacReprojThreshold=3, - OutputArray mask=noArray()); - -//! variant of findHomography for backward compatibility -CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, - OutputArray mask, int method=0, double ransacReprojThreshold=3); - -//! Computes RQ decomposition of 3x3 matrix -CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, - OutputArray Qx=noArray(), - OutputArray Qy=noArray(), - OutputArray Qz=noArray()); - -//! Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector -CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, - OutputArray rotMatrix, OutputArray transVect, - OutputArray rotMatrixX=noArray(), - OutputArray rotMatrixY=noArray(), - OutputArray rotMatrixZ=noArray(), - OutputArray eulerAngles=noArray() ); - -//! computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients -CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, - OutputArray dABdA, - OutputArray dABdB ); - -//! composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments -CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, - InputArray rvec2, InputArray tvec2, - OutputArray rvec3, OutputArray tvec3, - OutputArray dr3dr1=noArray(), OutputArray dr3dt1=noArray(), - OutputArray dr3dr2=noArray(), OutputArray dr3dt2=noArray(), - OutputArray dt3dr1=noArray(), OutputArray dt3dt1=noArray(), - OutputArray dt3dr2=noArray(), OutputArray dt3dt2=noArray() ); - -//! projects points from the model coordinate space to the image coordinates. Also computes derivatives of the image coordinates w.r.t the intrinsic and extrinsic camera parameters -CV_EXPORTS_W void projectPoints( InputArray objectPoints, - InputArray rvec, InputArray tvec, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray imagePoints, - OutputArray jacobian=noArray(), - double aspectRatio=0 ); - -//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled. -enum -{ - ITERATIVE=CV_ITERATIVE, - EPNP=CV_EPNP, - P3P=CV_P3P -}; -CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess=false, int flags=ITERATIVE); - -//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. -CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints, - InputArray imagePoints, - InputArray cameraMatrix, - InputArray distCoeffs, - OutputArray rvec, - OutputArray tvec, - bool useExtrinsicGuess = false, - int iterationsCount = 100, - float reprojectionError = 8.0, - int minInliersCount = 100, - OutputArray inliers = noArray(), - int flags = ITERATIVE); - -//! initializes camera matrix from a few 3D points and the corresponding projections. -CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, - Size imageSize, double aspectRatio=1. ); - -enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2, - CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8 }; - -//! finds checkerboard pattern of the specified size in the image -CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, - OutputArray corners, - int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE ); - -//! finds subpixel-accurate positions of the chessboard corners -CV_EXPORTS bool find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size region_size); - -//! draws the checkerboard pattern (found or partly found) in the image -CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, - InputArray corners, bool patternWasFound ); - -enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2, - CALIB_CB_CLUSTERING = 4 }; - -//! finds circles' grid pattern of the specified size in the image -CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, - OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, - const Ptr &blobDetector = new SimpleBlobDetector()); - -//! the deprecated function. Use findCirclesGrid() instead of it. -CV_EXPORTS_W bool findCirclesGridDefault( InputArray image, Size patternSize, - OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID ); -enum -{ - CALIB_USE_INTRINSIC_GUESS = CV_CALIB_USE_INTRINSIC_GUESS, - CALIB_FIX_ASPECT_RATIO = CV_CALIB_FIX_ASPECT_RATIO, - CALIB_FIX_PRINCIPAL_POINT = CV_CALIB_FIX_PRINCIPAL_POINT, - CALIB_ZERO_TANGENT_DIST = CV_CALIB_ZERO_TANGENT_DIST, - CALIB_FIX_FOCAL_LENGTH = CV_CALIB_FIX_FOCAL_LENGTH, - CALIB_FIX_K1 = CV_CALIB_FIX_K1, - CALIB_FIX_K2 = CV_CALIB_FIX_K2, - CALIB_FIX_K3 = CV_CALIB_FIX_K3, - CALIB_FIX_K4 = CV_CALIB_FIX_K4, - CALIB_FIX_K5 = CV_CALIB_FIX_K5, - CALIB_FIX_K6 = CV_CALIB_FIX_K6, - CALIB_RATIONAL_MODEL = CV_CALIB_RATIONAL_MODEL, - // only for stereo - CALIB_FIX_INTRINSIC = CV_CALIB_FIX_INTRINSIC, - CALIB_SAME_FOCAL_LENGTH = CV_CALIB_SAME_FOCAL_LENGTH, - // for stereo rectification - CALIB_ZERO_DISPARITY = CV_CALIB_ZERO_DISPARITY -}; - -//! finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern. -CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, - Size imageSize, - CV_OUT InputOutputArray cameraMatrix, - CV_OUT InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags=0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) ); - -//! computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size. -CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, - Size imageSize, - double apertureWidth, - double apertureHeight, - CV_OUT double& fovx, - CV_OUT double& fovy, - CV_OUT double& focalLength, - CV_OUT Point2d& principalPoint, - CV_OUT double& aspectRatio ); - -//! finds intrinsic and extrinsic parameters of a stereo camera -CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, - InputArrayOfArrays imagePoints2, - CV_OUT InputOutputArray cameraMatrix1, - CV_OUT InputOutputArray distCoeffs1, - CV_OUT InputOutputArray cameraMatrix2, - CV_OUT InputOutputArray distCoeffs2, - Size imageSize, OutputArray R, - OutputArray T, OutputArray E, OutputArray F, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6), - int flags=CALIB_FIX_INTRINSIC ); - - -//! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters -CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - Size imageSize, InputArray R, InputArray T, - OutputArray R1, OutputArray R2, - OutputArray P1, OutputArray P2, - OutputArray Q, int flags=CALIB_ZERO_DISPARITY, - double alpha=-1, Size newImageSize=Size(), - CV_OUT Rect* validPixROI1=0, CV_OUT Rect* validPixROI2=0 ); - -//! computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed) -CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, - InputArray F, Size imgSize, - OutputArray H1, OutputArray H2, - double threshold=5 ); - -//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. -CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - InputArray cameraMatrix3, InputArray distCoeffs3, - InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, - Size imageSize, InputArray R12, InputArray T12, - InputArray R13, InputArray T13, - OutputArray R1, OutputArray R2, OutputArray R3, - OutputArray P1, OutputArray P2, OutputArray P3, - OutputArray Q, double alpha, Size newImgSize, - CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); - -//! returns the optimal new camera matrix -CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, double alpha, Size newImgSize=Size(), - CV_OUT Rect* validPixROI=0, bool centerPrincipalPoint=false); - -//! converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) -CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); - -//! converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) -CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); - -//! for backward compatibility -CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); - -//! the algorithm for finding fundamental matrix -enum -{ - FM_7POINT = CV_FM_7POINT, //!< 7-point algorithm - FM_8POINT = CV_FM_8POINT, //!< 8-point algorithm - FM_LMEDS = CV_FM_LMEDS, //!< least-median algorithm - FM_RANSAC = CV_FM_RANSAC //!< RANSAC algorithm -}; - -//! finds fundamental matrix from a set of corresponding 2D points -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - int method=FM_RANSAC, - double param1=3., double param2=0.99, - OutputArray mask=noArray()); - -//! variant of findFundamentalMat for backward compatibility -CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, - OutputArray mask, int method=FM_RANSAC, - double param1=3., double param2=0.99); - -//! finds coordinates of epipolar lines corresponding the specified points -CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, - int whichImage, InputArray F, - OutputArray lines ); - -CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, - InputArray projPoints1, InputArray projPoints2, - OutputArray points4D ); - -CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, - OutputArray newPoints1, OutputArray newPoints2 ); - -template<> CV_EXPORTS void Ptr::delete_obj(); - -/*! - Block Matching Stereo Correspondence Algorithm - - The class implements BM stereo correspondence algorithm by K. Konolige. -*/ -class CV_EXPORTS_W StereoBM -{ -public: - enum { PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1, - BASIC_PRESET=0, FISH_EYE_PRESET=1, NARROW_PRESET=2 }; - - //! the default constructor - CV_WRAP StereoBM(); - //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size - CV_WRAP StereoBM(int preset, int ndisparities=0, int SADWindowSize=21); - //! the method that reinitializes the state. The previous content is destroyed - void init(int preset, int ndisparities=0, int SADWindowSize=21); - //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair - CV_WRAP_AS(compute) void operator()( InputArray left, InputArray right, - OutputArray disparity, int disptype=CV_16S ); - - //! pointer to the underlying CvStereoBMState - Ptr state; -}; - - -/*! - Semi-Global Block Matching Stereo Correspondence Algorithm - - The class implements the original SGBM stereo correspondence algorithm by H. Hirschmuller and some its modification. - */ -class CV_EXPORTS_W StereoSGBM -{ -public: - enum { DISP_SHIFT=4, DISP_SCALE = (1<(X,Y,Z) using the matrix Q returned by cv::stereoRectify -CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, - OutputArray _3dImage, InputArray Q, - bool handleMissingValues=false, - int ddepth=-1 ); - -CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, - OutputArray out, OutputArray inliers, - double ransacThreshold=3, double confidence=0.99); - -namespace fisheye -{ - enum{ - CALIB_USE_INTRINSIC_GUESS = 1, - CALIB_RECOMPUTE_EXTRINSIC = 2, - CALIB_CHECK_COND = 4, - CALIB_FIX_SKEW = 8, - CALIB_FIX_K1 = 16, - CALIB_FIX_K2 = 32, - CALIB_FIX_K3 = 64, - CALIB_FIX_K4 = 128, - CALIB_FIX_INTRINSIC = 256 - }; - - //! projects 3D points using fisheye model - CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - //! projects points using fisheye model - CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - //! distorts 2D points using fisheye model - CV_EXPORTS void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); - - //! undistorts 2D points using fisheye model - CV_EXPORTS void undistortPoints(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray()); - - //! computing undistortion and rectification maps for image transform by cv::remap() - //! If D is empty zero distortion is used, if R or P is empty identity matrixes are used - CV_EXPORTS void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, - const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); - - //! undistorts image, optionally changes resolution and camera matrix. If Knew zero identity matrix is used - CV_EXPORTS void undistortImage(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); - - //! estimates new camera matrix for undistortion or rectification - CV_EXPORTS void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, - OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); - - //! performs camera calibaration - CV_EXPORTS double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, - InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - //! stereo rectification estimation - CV_EXPORTS void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, - OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), - double balance = 0.0, double fov_scale = 1.0); - - //! performs stereo calibaration - CV_EXPORTS double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, - OutputArray R, OutputArray T, int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - -} - -} - -#endif -#endif +#include "opencv2/calib3d.hpp" diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/affine.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/core/affine.hpp index 827d044..7e2ed30 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/affine.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/affine.hpp @@ -41,15 +41,87 @@ // //M*/ -#ifndef __OPENCV_CORE_AFFINE3_HPP__ -#define __OPENCV_CORE_AFFINE3_HPP__ +#ifndef OPENCV_CORE_AFFINE3_HPP +#define OPENCV_CORE_AFFINE3_HPP #ifdef __cplusplus -#include +#include namespace cv { + +//! @addtogroup core +//! @{ + + /** @brief Affine transform + * + * It represents a 4x4 homogeneous transformation matrix \f$T\f$ + * + * \f[T = + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector. + * + * You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector, + * which is converted to a 3x3 rotation matrix by the Rodrigues formula. + * + * To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation + * angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use + * + * @code + * cv::Vec3f r, t; + * cv::Affine3f T(r, t); + * @endcode + * + * If you already have the rotation matrix \f$R\f$, then you can use + * + * @code + * cv::Matx33f R; + * cv::Affine3f T(R, t); + * @endcode + * + * To extract the rotation matrix \f$R\f$ from \f$T\f$, use + * + * @code + * cv::Matx33f R = T.rotation(); + * @endcode + * + * To extract the translation vector \f$t\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f t = T.translation(); + * @endcode + * + * To extract the rotation vector \f$r\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f r = T.rvec(); + * @endcode + * + * Note that since the mapping from rotation vectors to rotation matrices + * is many to one. The returned rotation vector is not necessarily the one + * you used before to set the matrix. + * + * If you have two transformations \f$T = T_1 * T_2\f$, use + * + * @code + * cv::Affine3f T, T1, T2; + * T = T2.concatenate(T1); + * @endcode + * + * To get the inverse transform of \f$T\f$, use + * + * @code + * cv::Affine3f T, T_inv; + * T_inv = T.inv(); + * @endcode + * + */ template class Affine3 { @@ -59,56 +131,139 @@ namespace cv typedef Matx Mat4; typedef Vec Vec3; + //! Default constructor. It represents a 4x4 identity matrix. Affine3(); - //Augmented affine matrix + //! Augmented affine matrix Affine3(const Mat4& affine); - //Rotation matrix + /** + * The resulting 4x4 matrix is + * + * \f[ + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * @param R 3x3 rotation matrix. + * @param t 3x1 translation vector. + */ Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); - //Rodrigues vector + /** + * Rodrigues vector. + * + * The last row of the current matrix is set to [0,0,0,1]. + * + * @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length + * indicates the rotation angle in radian (using right hand rule). + * @param t 3x1 translation vector. + */ Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); - //Combines all contructors above. Supports 4x4, 4x3, 3x3, 1x3, 3x1 sizes of data matrix + /** + * Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix. + * + * The last row of the current matrix is set to [0,0,0,1] when data is not 4x4. + * + * @param data 1-channel matrix. + * when it is 4x4, it is copied to the current matrix and t is not used. + * When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used. + * When it is 3x3, it is copied to the upper left 3x3 part of the current matrix. + * When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used + * to compute a 3x3 rotation matrix. + * @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4. + */ explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); - //From 16th element array + //! From 16-element array explicit Affine3(const float_type* vals); + //! Create an 4x4 identity transform static Affine3 Identity(); - //Rotation matrix + /** + * Rotation matrix. + * + * Copy the rotation matrix to the upper left 3x3 part of the current matrix. + * The remaining elements of the current matrix are not changed. + * + * @param R 3x3 rotation matrix. + * + */ void rotation(const Mat3& R); - //Rodrigues vector + /** + * Rodrigues vector. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param rvec 3x1 rotation vector. The direction indicates the rotation axis and + * its length indicates the rotation angle in radian (using the right thumb convention). + */ void rotation(const Vec3& rvec); - //Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix; + /** + * Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param data 1-channel matrix. + * When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix. + * When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula + * is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix. + */ void rotation(const Mat& data); + /** + * Copy the 3x3 matrix L to the upper left part of the current matrix + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param L 3x3 matrix. + */ void linear(const Mat3& L); + + /** + * Copy t to the first three elements of the last column of the current matrix + * + * It sets the upper right 3x1 part of the matrix. The remaining part is unaffected. + * + * @param t 3x1 translation vector. + */ void translation(const Vec3& t); + //! @return the upper left 3x3 part Mat3 rotation() const; + + //! @return the upper left 3x3 part Mat3 linear() const; + + //! @return the upper right 3x1 part Vec3 translation() const; - //Rodrigues vector + //! Rodrigues vector. + //! @return a vector representing the upper left 3x3 rotation matrix of the current matrix. + //! @warning Since the mapping between rotation vectors and rotation matrices is many to one, + //! this function returns only one rotation vector that represents the current rotation matrix, + //! which is not necessarily the same one set by `rotation(const Vec3& rvec)`. Vec3 rvec() const; + //! @return the inverse of the current matrix. Affine3 inv(int method = cv::DECOMP_SVD) const; - // a.rotate(R) is equivalent to Affine(R, 0) * a; + //! a.rotate(R) is equivalent to Affine(R, 0) * a; Affine3 rotate(const Mat3& R) const; - // a.rotate(R) is equivalent to Affine(rvec, 0) * a; + //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; Affine3 rotate(const Vec3& rvec) const; - // a.translate(t) is equivalent to Affine(E, t) * a; + //! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix Affine3 translate(const Vec3& t) const; - // a.concatenate(affine) is equivalent to affine * a; + //! a.concatenate(affine) is equivalent to affine * a; Affine3 concatenate(const Affine3& affine) const; template operator Affine3() const; @@ -128,6 +283,7 @@ namespace cv template static Affine3 operator*(const Affine3& affine1, const Affine3& affine2); + //! V is a 3-element vector with member fields x, y and z template static V operator*(const Affine3& affine, const V& vector); @@ -145,19 +301,32 @@ namespace cv typedef _Tp channel_type; enum { generic_type = 0, - depth = DataType::depth, channels = 16, - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif }; typedef Vec vec_type; }; + + namespace traits { + template + struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; }; + template + struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; }; + } // namespace + +//! @} core + } +//! @cond IGNORED /////////////////////////////////////////////////////////////////////////////////// -/// Implementaiton +// Implementation template inline cv::Affine3::Affine3() @@ -190,7 +359,8 @@ cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) template inline cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) { - CV_Assert(data.type() == cv::DataType::type); + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); if (data.cols == 4 && data.rows == 4) { @@ -201,11 +371,13 @@ cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) { rotation(data(Rect(0, 0, 3, 3))); translation(data(Rect(3, 0, 1, 3))); - return; + } + else + { + rotation(data); + translation(t); } - rotation(data); - translation(t); matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; matrix.val[15] = 1; } @@ -229,40 +401,36 @@ void cv::Affine3::rotation(const Mat3& R) template inline void cv::Affine3::rotation(const Vec3& _rvec) { - double rx = _rvec[0], ry = _rvec[1], rz = _rvec[2]; - double theta = std::sqrt(rx*rx + ry*ry + rz*rz); + double theta = norm(_rvec); if (theta < DBL_EPSILON) rotation(Mat3::eye()); else { - const double I[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - double c = std::cos(theta); double s = std::sin(theta); double c1 = 1. - c; - double itheta = theta ? 1./theta : 0.; + double itheta = (theta != 0) ? 1./theta : 0.; - rx *= itheta; ry *= itheta; rz *= itheta; + Point3_ r = _rvec*itheta; - double rrt[] = { rx*rx, rx*ry, rx*rz, rx*ry, ry*ry, ry*rz, rx*rz, ry*rz, rz*rz }; - double _r_x_[] = { 0, -rz, ry, rz, 0, -rx, -ry, rx, 0 }; - Mat3 R; + Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z ); + Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 ); // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] - for(int k = 0; k < 9; ++k) - R.val[k] = static_cast(c*I[k] + c1*rrt[k] + s*_r_x_[k]); + Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x; rotation(R); } } -//Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix; +//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix; template inline void cv::Affine3::rotation(const cv::Mat& data) { - CV_Assert(data.type() == cv::DataType::type); + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); if (data.cols == 3 && data.rows == 3) { @@ -277,7 +445,7 @@ void cv::Affine3::rotation(const cv::Mat& data) rotation(_rvec); } else - CV_Assert(!"Input marix can be 3x3, 1x3 or 3x1"); + CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1"); } template inline @@ -476,21 +644,21 @@ cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) template inline cv::Affine3::Affine3(const Eigen::Transform& affine) { - cv::Mat(4, 4, cv::DataType::type, affine.matrix().data()).copyTo(matrix); + cv::Mat(4, 4, cv::traits::Type::value, affine.matrix().data()).copyTo(matrix); } template inline cv::Affine3::Affine3(const Eigen::Transform& affine) { Eigen::Transform a = affine; - cv::Mat(4, 4, cv::DataType::type, a.matrix().data()).copyTo(matrix); + cv::Mat(4, 4, cv::traits::Type::value, a.matrix().data()).copyTo(matrix); } template inline cv::Affine3::operator Eigen::Transform() const { Eigen::Transform r; - cv::Mat hdr(4, 4, cv::DataType::type, r.matrix().data()); + cv::Mat hdr(4, 4, cv::traits::Type::value, r.matrix().data()); cv::Mat(matrix, false).copyTo(hdr); return r; } @@ -503,7 +671,8 @@ cv::Affine3::operator Eigen::Transform() const #endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ +//! @endcond #endif /* __cplusplus */ -#endif /* __OPENCV_CORE_AFFINE3_HPP__ */ +#endif /* OPENCV_CORE_AFFINE3_HPP */ diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/core.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/core/core.hpp index a0a7392..4389183 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/core.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/core.hpp @@ -1,6 +1,3 @@ -/*! \file core.hpp - \brief The Core Functionality - */ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. @@ -10,11 +7,12 @@ // copy or use the software. // // -// License Agreement +// License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2011, Willow Garage Inc., 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, @@ -43,4821 +41,8 @@ // //M*/ -#ifndef __OPENCV_CORE_HPP__ -#define __OPENCV_CORE_HPP__ - -#include "opencv2/core/types_c.h" -#include "opencv2/core/version.hpp" - -#ifdef __cplusplus - -#ifndef SKIP_INCLUDES -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif // SKIP_INCLUDES - -/*! \namespace cv - Namespace where all the C++ OpenCV functionality resides -*/ -namespace cv { - -#undef abs -#undef min -#undef max -#undef Complex - -using std::vector; -using std::string; -using std::ptrdiff_t; - -template class Size_; -template class Point_; -template class Rect_; -template class Vec; -template class Matx; - -typedef std::string String; - -class Mat; -class SparseMat; -typedef Mat MatND; - -namespace ogl { - class Buffer; - class Texture2D; - class Arrays; -} - -// < Deprecated -class GlBuffer; -class GlTexture; -class GlArrays; -class GlCamera; -// > - -namespace gpu { - class GpuMat; -} - -class CV_EXPORTS MatExpr; -class CV_EXPORTS MatOp_Base; -class CV_EXPORTS MatArg; -class CV_EXPORTS MatConstIterator; - -template class Mat_; -template class MatIterator_; -template class MatConstIterator_; -template class MatCommaInitializer_; - -#if !defined(ANDROID) || (defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_WCHAR_T) -typedef std::basic_string WString; - -CV_EXPORTS string fromUtf16(const WString& str); -CV_EXPORTS WString toUtf16(const string& str); +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library #endif -CV_EXPORTS string format( const char* fmt, ... ); -CV_EXPORTS string tempfile( const char* suffix CV_DEFAULT(0)); - -// matrix decomposition types -enum { DECOMP_LU=0, DECOMP_SVD=1, DECOMP_EIG=2, DECOMP_CHOLESKY=3, DECOMP_QR=4, DECOMP_NORMAL=16 }; -enum { NORM_INF=1, NORM_L1=2, NORM_L2=4, NORM_L2SQR=5, NORM_HAMMING=6, NORM_HAMMING2=7, NORM_TYPE_MASK=7, NORM_RELATIVE=8, NORM_MINMAX=32 }; -enum { CMP_EQ=0, CMP_GT=1, CMP_GE=2, CMP_LT=3, CMP_LE=4, CMP_NE=5 }; -enum { GEMM_1_T=1, GEMM_2_T=2, GEMM_3_T=4 }; -enum { DFT_INVERSE=1, DFT_SCALE=2, DFT_ROWS=4, DFT_COMPLEX_OUTPUT=16, DFT_REAL_OUTPUT=32, - DCT_INVERSE = DFT_INVERSE, DCT_ROWS=DFT_ROWS }; - - -/*! - The standard OpenCV exception class. - Instances of the class are thrown by various functions and methods in the case of critical errors. - */ -class CV_EXPORTS Exception : public std::exception -{ -public: - /*! - Default constructor - */ - Exception(); - /*! - Full constructor. Normally the constuctor is not called explicitly. - Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. - */ - Exception(int _code, const string& _err, const string& _func, const string& _file, int _line); - virtual ~Exception() throw(); - - /*! - \return the error description and the context as a text string. - */ - virtual const char *what() const throw(); - void formatMessage(); - - string msg; ///< the formatted error message - - int code; ///< error code @see CVStatus - string err; ///< error description - string func; ///< function name. Available only when the compiler supports getting it - string file; ///< source file name where the error has occured - int line; ///< line number in the source file where the error has occured -}; - - -//! Signals an error and raises the exception. - -/*! - By default the function prints information about the error to stderr, - then it either stops if setBreakOnError() had been called before or raises the exception. - It is possible to alternate error processing by using redirectError(). - - \param exc the exception raisen. - */ -CV_EXPORTS void error( const Exception& exc ); - -//! Sets/resets the break-on-error mode. - -/*! - When the break-on-error mode is set, the default error handler - issues a hardware exception, which can make debugging more convenient. - - \return the previous state - */ -CV_EXPORTS bool setBreakOnError(bool flag); - -typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name, - const char* err_msg, const char* file_name, - int line, void* userdata ); - -//! Sets the new error handler and the optional user data. - -/*! - The function sets the new error handler, called from cv::error(). - - \param errCallback the new error handler. If NULL, the default error handler is used. - \param userdata the optional user data pointer, passed to the callback. - \param prevUserdata the optional output parameter where the previous user data pointer is stored - - \return the previous error handler -*/ -CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, - void* userdata=0, void** prevUserdata=0); - - -#if defined __GNUC__ -#define CV_Func __func__ -#elif defined _MSC_VER -#define CV_Func __FUNCTION__ -#else -#define CV_Func "" -#endif - -#define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, CV_Func, __FILE__, __LINE__) ) -#define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, CV_Func, __FILE__, __LINE__) ) -#define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, CV_Func, __FILE__, __LINE__) ) - -#ifdef _DEBUG -#define CV_DbgAssert(expr) CV_Assert(expr) -#else -#define CV_DbgAssert(expr) -#endif - -CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); - -CV_EXPORTS void setNumThreads(int nthreads); -CV_EXPORTS int getNumThreads(); -CV_EXPORTS int getThreadNum(); - -CV_EXPORTS_W const string& getBuildInformation(); - -//! Returns the number of ticks. - -/*! - The function returns the number of ticks since the certain event (e.g. when the machine was turned on). - It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count - before and after the function call. The granularity of ticks depends on the hardware and OS used. Use - cv::getTickFrequency() to convert ticks to seconds. -*/ -CV_EXPORTS_W int64 getTickCount(); - -/*! - Returns the number of ticks per seconds. - - The function returns the number of ticks (as returned by cv::getTickCount()) per second. - The following code computes the execution time in milliseconds: - - \code - double exec_time = (double)getTickCount(); - // do something ... - exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency(); - \endcode -*/ -CV_EXPORTS_W double getTickFrequency(); - -/*! - Returns the number of CPU ticks. - - On platforms where the feature is available, the function returns the number of CPU ticks - since the certain event (normally, the system power-on moment). Using this function - one can accurately measure the execution time of very small code fragments, - for which cv::getTickCount() granularity is not enough. -*/ -CV_EXPORTS_W int64 getCPUTickCount(); - -/*! - Returns SSE etc. support status - - The function returns true if certain hardware features are available. - Currently, the following features are recognized: - - CV_CPU_MMX - MMX - - CV_CPU_SSE - SSE - - CV_CPU_SSE2 - SSE 2 - - CV_CPU_SSE3 - SSE 3 - - CV_CPU_SSSE3 - SSSE 3 - - CV_CPU_SSE4_1 - SSE 4.1 - - CV_CPU_SSE4_2 - SSE 4.2 - - CV_CPU_POPCNT - POPCOUNT - - CV_CPU_AVX - AVX - - CV_CPU_AVX2 - AVX2 - - \note {Note that the function output is not static. Once you called cv::useOptimized(false), - most of the hardware acceleration is disabled and thus the function will returns false, - until you call cv::useOptimized(true)} -*/ -CV_EXPORTS_W bool checkHardwareSupport(int feature); - -//! returns the number of CPUs (including hyper-threading) -CV_EXPORTS_W int getNumberOfCPUs(); - -/*! - Allocates memory buffer - - This is specialized OpenCV memory allocation function that returns properly aligned memory buffers. - The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree(). - If there is not enough memory, the function calls cv::error(), which raises an exception. - - \param bufSize buffer size in bytes - \return the allocated memory buffer. -*/ -CV_EXPORTS void* fastMalloc(size_t bufSize); - -/*! - Frees the memory allocated with cv::fastMalloc - - This is the corresponding deallocation function for cv::fastMalloc(). - When ptr==NULL, the function has no effect. -*/ -CV_EXPORTS void fastFree(void* ptr); - -template static inline _Tp* allocate(size_t n) -{ - return new _Tp[n]; -} - -template static inline void deallocate(_Tp* ptr, size_t) -{ - delete[] ptr; -} - -/*! - Aligns pointer by the certain number of bytes - - This small inline function aligns the pointer by the certian number of bytes by shifting - it forward by 0 or a positive offset. -*/ -template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) -{ - return (_Tp*)(((size_t)ptr + n-1) & -n); -} - -/*! - Aligns buffer size by the certain number of bytes - - This small inline function aligns a buffer size by the certian number of bytes by enlarging it. -*/ -static inline size_t alignSize(size_t sz, int n) -{ - assert((n & (n - 1)) == 0); // n is a power of 2 - return (sz + n-1) & -n; -} - -/*! - Turns on/off available optimization - - The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled - or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way. - - \note{Since optimization may imply using special data structures, it may be unsafe - to call this function anywhere in the code. Instead, call it somewhere at the top level.} -*/ -CV_EXPORTS_W void setUseOptimized(bool onoff); - -/*! - Returns the current optimization status - - The function returns the current optimization status, which is controlled by cv::setUseOptimized(). -*/ -CV_EXPORTS_W bool useOptimized(); - -/*! - The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree() -*/ -template class Allocator -{ -public: - typedef _Tp value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - template class rebind { typedef Allocator other; }; - - explicit Allocator() {} - ~Allocator() {} - explicit Allocator(Allocator const&) {} - template - explicit Allocator(Allocator const&) {} - - // address - pointer address(reference r) { return &r; } - const_pointer address(const_reference r) { return &r; } - - pointer allocate(size_type count, const void* =0) - { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } - - void deallocate(pointer p, size_type) {fastFree(p); } - - size_type max_size() const - { return max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } - - void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } - void destroy(pointer p) { p->~_Tp(); } -}; - -/////////////////////// Vec (used as element of multi-channel images ///////////////////// - -/*! - A helper class for cv::DataType - - The class is specialized for each fundamental numerical data type supported by OpenCV. - It provides DataDepth::value constant. -*/ -template class DataDepth {}; - -template<> class DataDepth { public: enum { value = CV_8U, fmt=(int)'u' }; }; -template<> class DataDepth { public: enum { value = CV_8U, fmt=(int)'u' }; }; -template<> class DataDepth { public: enum { value = CV_8S, fmt=(int)'c' }; }; -template<> class DataDepth { public: enum { value = CV_8S, fmt=(int)'c' }; }; -template<> class DataDepth { public: enum { value = CV_16U, fmt=(int)'w' }; }; -template<> class DataDepth { public: enum { value = CV_16S, fmt=(int)'s' }; }; -template<> class DataDepth { public: enum { value = CV_32S, fmt=(int)'i' }; }; -// this is temporary solution to support 32-bit unsigned integers -template<> class DataDepth { public: enum { value = CV_32S, fmt=(int)'i' }; }; -template<> class DataDepth { public: enum { value = CV_32F, fmt=(int)'f' }; }; -template<> class DataDepth { public: enum { value = CV_64F, fmt=(int)'d' }; }; -template class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; }; - - -////////////////////////////// Small Matrix /////////////////////////// - -/*! - A short numerical vector. - - This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) - on which you can perform basic arithmetical operations, access individual elements using [] operator etc. - The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., - which elements are dynamically allocated in the heap. - - The template takes 2 parameters: - -# _Tp element type - -# cn the number of elements - - In addition to the universal notation like Vec, you can use shorter aliases - for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. - */ - -struct CV_EXPORTS Matx_AddOp {}; -struct CV_EXPORTS Matx_SubOp {}; -struct CV_EXPORTS Matx_ScaleOp {}; -struct CV_EXPORTS Matx_MulOp {}; -struct CV_EXPORTS Matx_MatMulOp {}; -struct CV_EXPORTS Matx_TOp {}; - -template class Matx -{ -public: - typedef _Tp value_type; - typedef Matx<_Tp, (m < n ? m : n), 1> diag_type; - typedef Matx<_Tp, m, n> mat_type; - enum { depth = DataDepth<_Tp>::value, rows = m, cols = n, channels = rows*cols, - type = CV_MAKETYPE(depth, channels) }; - - //! default constructor - Matx(); - - Matx(_Tp v0); //!< 1x1 matrix - Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix - explicit Matx(const _Tp* vals); //!< initialize from a plain array - - static Matx all(_Tp alpha); - static Matx zeros(); - static Matx ones(); - static Matx eye(); - static Matx diag(const diag_type& d); - static Matx randu(_Tp a, _Tp b); - static Matx randn(_Tp a, _Tp b); - - //! dot product computed with the default precision - _Tp dot(const Matx<_Tp, m, n>& v) const; - - //! dot product computed in double-precision arithmetics - double ddot(const Matx<_Tp, m, n>& v) const; - - //! conversion to another data type - template operator Matx() const; - - //! change the matrix shape - template Matx<_Tp, m1, n1> reshape() const; - - //! extract part of the matrix - template Matx<_Tp, m1, n1> get_minor(int i, int j) const; - - //! extract the matrix row - Matx<_Tp, 1, n> row(int i) const; - - //! extract the matrix column - Matx<_Tp, m, 1> col(int i) const; - - //! extract the matrix diagonal - diag_type diag() const; - - //! transpose the matrix - Matx<_Tp, n, m> t() const; - - //! invert matrix the matrix - Matx<_Tp, n, m> inv(int method=DECOMP_LU) const; - - //! solve linear system - template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; - Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; - - //! multiply two matrices element-wise - Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; - - //! element access - const _Tp& operator ()(int i, int j) const; - _Tp& operator ()(int i, int j); - - //! 1D element access - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); - template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); - template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); - Matx(const Matx<_Tp, n, m>& a, Matx_TOp); - - _Tp val[m*n]; //< matrix elements -}; - - -typedef Matx Matx12f; -typedef Matx Matx12d; -typedef Matx Matx13f; -typedef Matx Matx13d; -typedef Matx Matx14f; -typedef Matx Matx14d; -typedef Matx Matx16f; -typedef Matx Matx16d; - -typedef Matx Matx21f; -typedef Matx Matx21d; -typedef Matx Matx31f; -typedef Matx Matx31d; -typedef Matx Matx41f; -typedef Matx Matx41d; -typedef Matx Matx61f; -typedef Matx Matx61d; - -typedef Matx Matx22f; -typedef Matx Matx22d; -typedef Matx Matx23f; -typedef Matx Matx23d; -typedef Matx Matx32f; -typedef Matx Matx32d; - -typedef Matx Matx33f; -typedef Matx Matx33d; - -typedef Matx Matx34f; -typedef Matx Matx34d; -typedef Matx Matx43f; -typedef Matx Matx43d; - -typedef Matx Matx44f; -typedef Matx Matx44d; -typedef Matx Matx66f; -typedef Matx Matx66d; - - -/*! - A short numerical vector. - - This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) - on which you can perform basic arithmetical operations, access individual elements using [] operator etc. - The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., - which elements are dynamically allocated in the heap. - - The template takes 2 parameters: - -# _Tp element type - -# cn the number of elements - - In addition to the universal notation like Vec, you can use shorter aliases - for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. -*/ -template class Vec : public Matx<_Tp, cn, 1> -{ -public: - typedef _Tp value_type; - enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) }; - - //! default constructor - Vec(); - - Vec(_Tp v0); //!< 1-element vector constructor - Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor - explicit Vec(const _Tp* values); - - Vec(const Vec<_Tp, cn>& v); - - static Vec all(_Tp alpha); - - //! per-element multiplication - Vec mul(const Vec<_Tp, cn>& v) const; - - //! conjugation (makes sense for complex numbers and quaternions) - Vec conj() const; - - /*! - cross product of the two 3D vectors. - - For other dimensionalities the exception is raised - */ - Vec cross(const Vec& v) const; - //! conversion to another data type - template operator Vec() const; - //! conversion to 4-element CvScalar. - operator CvScalar() const; - - /*! element access */ - const _Tp& operator [](int i) const; - _Tp& operator[](int i); - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); - template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); -}; - - -/* \typedef - - Shorter aliases for the most popular specializations of Vec -*/ -typedef Vec Vec2b; -typedef Vec Vec3b; -typedef Vec Vec4b; - -typedef Vec Vec2s; -typedef Vec Vec3s; -typedef Vec Vec4s; - -typedef Vec Vec2w; -typedef Vec Vec3w; -typedef Vec Vec4w; - -typedef Vec Vec2i; -typedef Vec Vec3i; -typedef Vec Vec4i; -typedef Vec Vec6i; -typedef Vec Vec8i; - -typedef Vec Vec2f; -typedef Vec Vec3f; -typedef Vec Vec4f; -typedef Vec Vec6f; - -typedef Vec Vec2d; -typedef Vec Vec3d; -typedef Vec Vec4d; -typedef Vec Vec6d; - - -//////////////////////////////// Complex ////////////////////////////// - -/*! - A complex number class. - - The template class is similar and compatible with std::complex, however it provides slightly - more convenient access to the real and imaginary parts using through the simple field access, as opposite - to std::complex::real() and std::complex::imag(). -*/ -template class Complex -{ -public: - - //! constructors - Complex(); - Complex( _Tp _re, _Tp _im=0 ); - Complex( const std::complex<_Tp>& c ); - - //! conversion to another data type - template operator Complex() const; - //! conjugation - Complex conj() const; - //! conversion to std::complex - operator std::complex<_Tp>() const; - - _Tp re, im; //< the real and the imaginary parts -}; - - -/*! - \typedef -*/ -typedef Complex Complexf; -typedef Complex Complexd; - - -//////////////////////////////// Point_ //////////////////////////////// - -/*! - template 2D point class. - - The class defines a point in 2D space. Data type of the point coordinates is specified - as a template parameter. There are a few shorter aliases available for user convenience. - See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d. -*/ -template class Point_ -{ -public: - typedef _Tp value_type; - - // various constructors - Point_(); - Point_(_Tp _x, _Tp _y); - Point_(const Point_& pt); - Point_(const CvPoint& pt); - Point_(const CvPoint2D32f& pt); - Point_(const Size_<_Tp>& sz); - Point_(const Vec<_Tp, 2>& v); - - Point_& operator = (const Point_& pt); - //! conversion to another data type - template operator Point_<_Tp2>() const; - - //! conversion to the old-style C structures - operator CvPoint() const; - operator CvPoint2D32f() const; - operator Vec<_Tp, 2>() const; - - //! dot product - _Tp dot(const Point_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point_& pt) const; - //! cross-product - double cross(const Point_& pt) const; - //! checks whether the point is inside the specified rectangle - bool inside(const Rect_<_Tp>& r) const; - - _Tp x, y; //< the point coordinates -}; - -/*! - template 3D point class. - - The class defines a point in 3D space. Data type of the point coordinates is specified - as a template parameter. - - \see cv::Point3i, cv::Point3f and cv::Point3d -*/ -template class Point3_ -{ -public: - typedef _Tp value_type; - - // various constructors - Point3_(); - Point3_(_Tp _x, _Tp _y, _Tp _z); - Point3_(const Point3_& pt); - explicit Point3_(const Point_<_Tp>& pt); - Point3_(const CvPoint3D32f& pt); - Point3_(const Vec<_Tp, 3>& v); - - Point3_& operator = (const Point3_& pt); - //! conversion to another data type - template operator Point3_<_Tp2>() const; - //! conversion to the old-style CvPoint... - operator CvPoint3D32f() const; - //! conversion to cv::Vec<> - operator Vec<_Tp, 3>() const; - - //! dot product - _Tp dot(const Point3_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point3_& pt) const; - //! cross product of the 2 3D points - Point3_ cross(const Point3_& pt) const; - - _Tp x, y, z; //< the point coordinates -}; - -//////////////////////////////// Size_ //////////////////////////////// - -/*! - The 2D size class - - The class represents the size of a 2D rectangle, image size, matrix size etc. - Normally, cv::Size ~ cv::Size_ is used. -*/ -template class Size_ -{ -public: - typedef _Tp value_type; - - //! various constructors - Size_(); - Size_(_Tp _width, _Tp _height); - Size_(const Size_& sz); - Size_(const CvSize& sz); - Size_(const CvSize2D32f& sz); - Size_(const Point_<_Tp>& pt); - - Size_& operator = (const Size_& sz); - //! the area (width*height) - _Tp area() const; - - //! conversion of another data type. - template operator Size_<_Tp2>() const; - - //! conversion to the old-style OpenCV types - operator CvSize() const; - operator CvSize2D32f() const; - - _Tp width, height; // the width and the height -}; - -//////////////////////////////// Rect_ //////////////////////////////// - -/*! - The 2D up-right rectangle class - - The class represents a 2D rectangle with coordinates of the specified data type. - Normally, cv::Rect ~ cv::Rect_ is used. -*/ -template class Rect_ -{ -public: - typedef _Tp value_type; - - //! various constructors - Rect_(); - Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); - Rect_(const Rect_& r); - Rect_(const CvRect& r); - Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); - Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); - - Rect_& operator = ( const Rect_& r ); - //! the top-left corner - Point_<_Tp> tl() const; - //! the bottom-right corner - Point_<_Tp> br() const; - - //! size (width, height) of the rectangle - Size_<_Tp> size() const; - //! area (width*height) of the rectangle - _Tp area() const; - - //! conversion to another data type - template operator Rect_<_Tp2>() const; - //! conversion to the old-style CvRect - operator CvRect() const; - - //! checks whether the rectangle contains the point - bool contains(const Point_<_Tp>& pt) const; - - _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle -}; - - -/*! - \typedef - - shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations -*/ -typedef Point_ Point2i; -typedef Point2i Point; -typedef Size_ Size2i; -typedef Size_ Size2d; -typedef Size2i Size; -typedef Rect_ Rect; -typedef Point_ Point2f; -typedef Point_ Point2d; -typedef Size_ Size2f; -typedef Point3_ Point3i; -typedef Point3_ Point3f; -typedef Point3_ Point3d; - - -/*! - The rotated 2D rectangle. - - The class represents rotated (i.e. not up-right) rectangles on a plane. - Each rectangle is described by the center point (mass center), length of each side - (represented by cv::Size2f structure) and the rotation angle in degrees. -*/ -class CV_EXPORTS RotatedRect -{ -public: - //! various constructors - RotatedRect(); - RotatedRect(const Point2f& center, const Size2f& size, float angle); - RotatedRect(const CvBox2D& box); - - //! returns 4 vertices of the rectangle - void points(Point2f pts[]) const; - //! returns the minimal up-right rectangle containing the rotated rectangle - Rect boundingRect() const; - //! conversion to the old-style CvBox2D structure - operator CvBox2D() const; - - Point2f center; //< the rectangle mass center - Size2f size; //< width and height of the rectangle - float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. -}; - -//////////////////////////////// Scalar_ /////////////////////////////// - -/*! - The template scalar class. - - This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements. - Normally, cv::Scalar ~ cv::Scalar_ is used. -*/ -template class Scalar_ : public Vec<_Tp, 4> -{ -public: - //! various constructors - Scalar_(); - Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); - Scalar_(const CvScalar& s); - Scalar_(_Tp v0); - - //! returns a scalar with all elements set to v0 - static Scalar_<_Tp> all(_Tp v0); - //! conversion to the old-style CvScalar - operator CvScalar() const; - - //! conversion to another data type - template operator Scalar_() const; - - //! per-element product - Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const; - - // returns (v0, -v1, -v2, -v3) - Scalar_<_Tp> conj() const; - - // returns true iff v1 == v2 == v3 == 0 - bool isReal() const; -}; - -typedef Scalar_ Scalar; - -CV_EXPORTS void scalarToRawData(const Scalar& s, void* buf, int type, int unroll_to=0); - -//////////////////////////////// Range ///////////////////////////////// - -/*! - The 2D range class - - This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix. -*/ -class CV_EXPORTS Range -{ -public: - Range(); - Range(int _start, int _end); - Range(const CvSlice& slice); - int size() const; - bool empty() const; - static Range all(); - operator CvSlice() const; - - int start, end; -}; - -/////////////////////////////// DataType //////////////////////////////// - -/*! - Informative template class for OpenCV "scalars". - - The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float), - as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc. - The common property of all such types (called "scalars", do not confuse it with cv::Scalar_) - is that each of them is basically a tuple of numbers of the same type. Each "scalar" can be represented - by the depth id (CV_8U ... CV_64F) and the number of channels. - OpenCV matrices, 2D or nD, dense or sparse, can store "scalars", - as long as the number of channels does not exceed CV_CN_MAX. -*/ -template class DataType -{ -public: - typedef _Tp value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 1, depth = -1, channels = 1, fmt=0, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef bool value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef uchar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef ushort value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef short value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef int value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef float value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template<> class DataType -{ -public: - typedef double value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 1, - fmt=DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template class DataType > -{ -public: - typedef Matx<_Tp, m, n> value_type; - typedef Matx::work_type, m, n> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = m*n, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template class DataType > -{ -public: - typedef Vec<_Tp, cn> value_type; - typedef Vec::work_type, cn> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - enum { generic_type = 0, depth = DataDepth::value, channels = cn, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; -}; - -template class DataType > -{ -public: - typedef std::complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 2, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 2, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Point_<_Tp> value_type; - typedef Point_::work_type> work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 2, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Point3_<_Tp> value_type; - typedef Point3_::work_type> work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 3, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Size_<_Tp> value_type; - typedef Size_::work_type> work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 2, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Rect_<_Tp> value_type; - typedef Rect_::work_type> work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 4, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template class DataType > -{ -public: - typedef Scalar_<_Tp> value_type; - typedef Scalar_::work_type> work_type; - typedef _Tp channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 4, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -template<> class DataType -{ -public: - typedef Range value_type; - typedef value_type work_type; - typedef int channel_type; - enum { generic_type = 0, depth = DataDepth::value, channels = 2, - fmt = ((channels-1)<<8) + DataDepth::fmt, - type = CV_MAKETYPE(depth, channels) }; - typedef Vec vec_type; -}; - -//////////////////// generic_type ref-counting pointer class for C/C++ objects //////////////////////// - -/*! - Smart pointer to dynamically allocated objects. - - This is template pointer-wrapping class that stores the associated reference counter along with the - object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard, - but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library). - - Basically, you can use "Ptr ptr" (or faster "const Ptr& ptr" for read-only access) - everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class. - To make it all work, you need to specialize Ptr<>::delete_obj(), like: - - \code - template<> void Ptr::delete_obj() { call_destructor_func(obj); } - \endcode - - \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(), - since the default implementation calls "delete obj;"} - - \note{Another good property of the class is that the operations on the reference counter are atomic, - i.e. it is safe to use the class in multi-threaded applications} -*/ -template class Ptr -{ -public: - //! empty constructor - Ptr(); - //! take ownership of the pointer. The associated reference counter is allocated and set to 1 - Ptr(_Tp* _obj); - //! calls release() - ~Ptr(); - //! copy constructor. Copies the members and calls addref() - Ptr(const Ptr& ptr); - template Ptr(const Ptr<_Tp2>& ptr); - //! copy operator. Calls ptr.addref() and release() before copying the members - Ptr& operator = (const Ptr& ptr); - //! increments the reference counter - void addref(); - //! decrements the reference counter. If it reaches 0, delete_obj() is called - void release(); - //! deletes the object. Override if needed - void delete_obj(); - //! returns true iff obj==NULL - bool empty() const; - - //! cast pointer to another type - template Ptr<_Tp2> ptr(); - template const Ptr<_Tp2> ptr() const; - - //! helper operators making "Ptr ptr" use very similar to "T* ptr". - _Tp* operator -> (); - const _Tp* operator -> () const; - - operator _Tp* (); - operator const _Tp*() const; - - _Tp* obj; //< the object pointer. - int* refcount; //< the associated reference counter -}; - - -//////////////////////// Input/Output Array Arguments ///////////////////////////////// - -/*! - Proxy datatype for passing Mat's and vector<>'s as input parameters - */ -class CV_EXPORTS _InputArray -{ -public: - enum { - KIND_SHIFT = 16, - FIXED_TYPE = 0x8000 << KIND_SHIFT, - FIXED_SIZE = 0x4000 << KIND_SHIFT, - KIND_MASK = ~(FIXED_TYPE|FIXED_SIZE) - (1 << KIND_SHIFT) + 1, - - NONE = 0 << KIND_SHIFT, - MAT = 1 << KIND_SHIFT, - MATX = 2 << KIND_SHIFT, - STD_VECTOR = 3 << KIND_SHIFT, - STD_VECTOR_VECTOR = 4 << KIND_SHIFT, - STD_VECTOR_MAT = 5 << KIND_SHIFT, - EXPR = 6 << KIND_SHIFT, - OPENGL_BUFFER = 7 << KIND_SHIFT, - OPENGL_TEXTURE = 8 << KIND_SHIFT, - GPU_MAT = 9 << KIND_SHIFT, - OCL_MAT =10 << KIND_SHIFT - }; - _InputArray(); - - _InputArray(const Mat& m); - _InputArray(const MatExpr& expr); - template _InputArray(const _Tp* vec, int n); - template _InputArray(const vector<_Tp>& vec); - template _InputArray(const vector >& vec); - _InputArray(const vector& vec); - template _InputArray(const vector >& vec); - template _InputArray(const Mat_<_Tp>& m); - template _InputArray(const Matx<_Tp, m, n>& matx); - _InputArray(const Scalar& s); - _InputArray(const double& val); - // < Deprecated - _InputArray(const GlBuffer& buf); - _InputArray(const GlTexture& tex); - // > - _InputArray(const gpu::GpuMat& d_mat); - _InputArray(const ogl::Buffer& buf); - _InputArray(const ogl::Texture2D& tex); - - virtual Mat getMat(int i=-1) const; - virtual void getMatVector(vector& mv) const; - // < Deprecated - virtual GlBuffer getGlBuffer() const; - virtual GlTexture getGlTexture() const; - // > - virtual gpu::GpuMat getGpuMat() const; - /*virtual*/ ogl::Buffer getOGlBuffer() const; - /*virtual*/ ogl::Texture2D getOGlTexture2D() const; - - virtual int kind() const; - virtual Size size(int i=-1) const; - virtual size_t total(int i=-1) const; - virtual int type(int i=-1) const; - virtual int depth(int i=-1) const; - virtual int channels(int i=-1) const; - virtual bool empty() const; - -#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY - virtual ~_InputArray(); -#endif - - int flags; - void* obj; - Size sz; -}; - - -enum -{ - DEPTH_MASK_8U = 1 << CV_8U, - DEPTH_MASK_8S = 1 << CV_8S, - DEPTH_MASK_16U = 1 << CV_16U, - DEPTH_MASK_16S = 1 << CV_16S, - DEPTH_MASK_32S = 1 << CV_32S, - DEPTH_MASK_32F = 1 << CV_32F, - DEPTH_MASK_64F = 1 << CV_64F, - DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, - DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, - DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F -}; - - -/*! - Proxy datatype for passing Mat's and vector<>'s as input parameters - */ -class CV_EXPORTS _OutputArray : public _InputArray -{ -public: - _OutputArray(); - - _OutputArray(Mat& m); - template _OutputArray(vector<_Tp>& vec); - template _OutputArray(vector >& vec); - _OutputArray(vector& vec); - template _OutputArray(vector >& vec); - template _OutputArray(Mat_<_Tp>& m); - template _OutputArray(Matx<_Tp, m, n>& matx); - template _OutputArray(_Tp* vec, int n); - _OutputArray(gpu::GpuMat& d_mat); - _OutputArray(ogl::Buffer& buf); - _OutputArray(ogl::Texture2D& tex); - - _OutputArray(const Mat& m); - template _OutputArray(const vector<_Tp>& vec); - template _OutputArray(const vector >& vec); - _OutputArray(const vector& vec); - template _OutputArray(const vector >& vec); - template _OutputArray(const Mat_<_Tp>& m); - template _OutputArray(const Matx<_Tp, m, n>& matx); - template _OutputArray(const _Tp* vec, int n); - _OutputArray(const gpu::GpuMat& d_mat); - _OutputArray(const ogl::Buffer& buf); - _OutputArray(const ogl::Texture2D& tex); - - virtual bool fixedSize() const; - virtual bool fixedType() const; - virtual bool needed() const; - virtual Mat& getMatRef(int i=-1) const; - /*virtual*/ gpu::GpuMat& getGpuMatRef() const; - /*virtual*/ ogl::Buffer& getOGlBufferRef() const; - /*virtual*/ ogl::Texture2D& getOGlTexture2DRef() const; - virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; - virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; - virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; - virtual void release() const; - virtual void clear() const; - -#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY - virtual ~_OutputArray(); -#endif -}; - -typedef const _InputArray& InputArray; -typedef InputArray InputArrayOfArrays; -typedef const _OutputArray& OutputArray; -typedef OutputArray OutputArrayOfArrays; -typedef OutputArray InputOutputArray; -typedef OutputArray InputOutputArrayOfArrays; - -CV_EXPORTS OutputArray noArray(); - -/////////////////////////////////////// Mat /////////////////////////////////////////// - -enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 }; - -static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); } - -/*! - Custom array allocator - -*/ -class CV_EXPORTS MatAllocator -{ -public: - MatAllocator() {} - virtual ~MatAllocator() {} - virtual void allocate(int dims, const int* sizes, int type, int*& refcount, - uchar*& datastart, uchar*& data, size_t* step) = 0; - virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; -}; - -/*! - The n-dimensional matrix class. - - The class represents an n-dimensional dense numerical array that can act as - a matrix, image, optical flow map, 3-focal tensor etc. - It is very similar to CvMat and CvMatND types from earlier versions of OpenCV, - and similarly to those types, the matrix can be multi-channel. It also fully supports ROI mechanism. - - There are many different ways to create cv::Mat object. Here are the some popular ones: -
    -
  • using cv::Mat::create(nrows, ncols, type) method or - the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor. - A new matrix of the specified size and specifed type will be allocated. - "type" has the same meaning as in cvCreateMat function, - e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex) - floating-point matrix etc: - - \code - // make 7x7 complex matrix filled with 1+3j. - cv::Mat M(7,7,CV_32FC2,Scalar(1,3)); - // and now turn M to 100x60 15-channel 8-bit matrix. - // The old content will be deallocated - M.create(100,60,CV_8UC(15)); - \endcode - - As noted in the introduction of this chapter, Mat::create() - will only allocate a new matrix when the current matrix dimensionality - or type are different from the specified. - -
  • by using a copy constructor or assignment operator, where on the right side it can - be a matrix or expression, see below. Again, as noted in the introduction, - matrix assignment is O(1) operation because it only copies the header - and increases the reference counter. cv::Mat::clone() method can be used to get a full - (a.k.a. deep) copy of the matrix when you need it. - -
  • by constructing a header for a part of another matrix. It can be a single row, single column, - several rows, several columns, rectangular region in the matrix (called a minor in algebra) or - a diagonal. Such operations are also O(1), because the new header will reference the same data. - You can actually modify a part of the matrix using this feature, e.g. - - \code - // add 5-th row, multiplied by 3 to the 3rd row - M.row(3) = M.row(3) + M.row(5)*3; - - // now copy 7-th column to the 1-st column - // M.col(1) = M.col(7); // this will not work - Mat M1 = M.col(1); - M.col(7).copyTo(M1); - - // create new 320x240 image - cv::Mat img(Size(320,240),CV_8UC3); - // select a roi - cv::Mat roi(img, Rect(10,10,100,100)); - // fill the ROI with (0,255,0) (which is green in RGB space); - // the original 320x240 image will be modified - roi = Scalar(0,255,0); - \endcode - - Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to - compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI(): - - \code - Mat A = Mat::eye(10, 10, CV_32S); - // extracts A columns, 1 (inclusive) to 3 (exclusive). - Mat B = A(Range::all(), Range(1, 3)); - // extracts B rows, 5 (inclusive) to 9 (exclusive). - // that is, C ~ A(Range(5, 9), Range(1, 3)) - Mat C = B(Range(5, 9), Range::all()); - Size size; Point ofs; - C.locateROI(size, ofs); - // size will be (width=10,height=10) and the ofs will be (x=1, y=5) - \endcode - - As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method - of the extracted sub-matrices. - -
  • by making a header for user-allocated-data. It can be useful for -
      -
    1. processing "foreign" data using OpenCV (e.g. when you implement - a DirectShow filter or a processing module for gstreamer etc.), e.g. - - \code - void process_video_frame(const unsigned char* pixels, - int width, int height, int step) - { - cv::Mat img(height, width, CV_8UC3, pixels, step); - cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5); - } - \endcode - -
    2. for quick initialization of small matrices and/or super-fast element access - - \code - double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; - cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv(); - \endcode -
    - - partial yet very common cases of this "user-allocated data" case are conversions - from CvMat and IplImage to cv::Mat. For this purpose there are special constructors - taking pointers to CvMat or IplImage and the optional - flag indicating whether to copy the data or not. - - Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators - cv::Mat::operator CvMat() an cv::Mat::operator IplImage(). - The operators do not copy the data. - - - \code - IplImage* img = cvLoadImage("greatwave.jpg", 1); - Mat mtx(img); // convert IplImage* -> cv::Mat - CvMat oldmat = mtx; // convert cv::Mat -> CvMat - CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height && - oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep); - \endcode - -
  • by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.: - - \code - // create a double-precision identity martix and add it to M. - M += Mat::eye(M.rows, M.cols, CV_64F); - \endcode - -
  • by using comma-separated initializer: - - \code - // create 3x3 double-precision identity matrix - Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); - \endcode - - here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix, - and then we just put "<<" operator followed by comma-separated values that can be constants, - variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors. - -
- - Once matrix is created, it will be automatically managed by using reference-counting mechanism - (unless the matrix header is built on top of user-allocated data, - in which case you should handle the data by yourself). - The matrix data will be deallocated when no one points to it; - if you want to release the data pointed by a matrix header before the matrix destructor is called, - use cv::Mat::release(). - - The next important thing to learn about the matrix class is element access. Here is how the matrix is stored. - The elements are stored in row-major order (row by row). The cv::Mat::data member points to the first element of the first row, - cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member, - cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be - a part of another matrix or because there can some padding space in the end of each row for a proper alignment. - - \image html roi.png - - Given these parameters, address of the matrix element M_{ij} is computed as following: - - addr(M_{ij})=M.data + M.step*i + j*M.elemSize() - - if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method: - - addr(M_{ij})=&M.at(i,j) - - (where & is used to convert the reference returned by cv::Mat::at() to a pointer). - if you need to process a whole row of matrix, the most efficient way is to get - the pointer to the row first, and then just use plain C operator []: - - \code - // compute sum of positive matrix elements - // (assuming that M is double-precision matrix) - double sum=0; - for(int i = 0; i < M.rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < M.cols; j++) - sum += std::max(Mi[j], 0.); - } - \endcode - - Some operations, like the above one, do not actually depend on the matrix shape, - they just process elements of a matrix one by one (or elements from multiple matrices - that are sitting in the same place, e.g. matrix addition). Such operations are called - element-wise and it makes sense to check whether all the input/output matrices are continuous, - i.e. have no gaps in the end of each row, and if yes, process them as a single long row: - - \code - // compute sum of positive matrix elements, optimized variant - double sum=0; - int cols = M.cols, rows = M.rows; - if(M.isContinuous()) - { - cols *= rows; - rows = 1; - } - for(int i = 0; i < rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < cols; j++) - sum += std::max(Mi[j], 0.); - } - \endcode - in the case of continuous matrix the outer loop body will be executed just once, - so the overhead will be smaller, which will be especially noticeable in the case of small matrices. - - Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: - \code - // compute sum of positive matrix elements, iterator-based variant - double sum=0; - MatConstIterator_ it = M.begin(), it_end = M.end(); - for(; it != it_end; ++it) - sum += std::max(*it, 0.); - \endcode - - The matrix iterators are random-access iterators, so they can be passed - to any STL algorithm, including std::sort(). -*/ -class CV_EXPORTS Mat -{ -public: - //! default constructor - Mat(); - //! constructs 2D matrix of the specified size and type - // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) - Mat(int rows, int cols, int type); - Mat(Size size, int type); - //! constucts 2D matrix and fills it with the specified value _s. - Mat(int rows, int cols, int type, const Scalar& s); - Mat(Size size, int type, const Scalar& s); - - //! constructs n-dimensional matrix - Mat(int ndims, const int* sizes, int type); - Mat(int ndims, const int* sizes, int type, const Scalar& s); - - //! copy constructor - Mat(const Mat& m); - //! constructor for matrix headers pointing to user-allocated data - Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); - Mat(Size size, int type, void* data, size_t step=AUTO_STEP); - Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); - - //! creates a matrix header for a part of the bigger matrix - Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); - Mat(const Mat& m, const Rect& roi); - Mat(const Mat& m, const Range* ranges); - //! converts old-style CvMat to the new matrix; the data is not copied by default - Mat(const CvMat* m, bool copyData=false); - //! converts old-style CvMatND to the new matrix; the data is not copied by default - Mat(const CvMatND* m, bool copyData=false); - //! converts old-style IplImage to the new matrix; the data is not copied by default - Mat(const IplImage* img, bool copyData=false); - //! builds matrix from std::vector with or without copying the data - template explicit Mat(const vector<_Tp>& vec, bool copyData=false); - //! builds matrix from cv::Vec; the data is copied by default - template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); - //! builds matrix from cv::Matx; the data is copied by default - template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); - //! builds matrix from a 2D point - template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); - //! builds matrix from a 3D point - template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); - //! builds matrix from comma initializer - template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); - - //! download data from GpuMat - explicit Mat(const gpu::GpuMat& m); - - //! destructor - calls release() - ~Mat(); - //! assignment operators - Mat& operator = (const Mat& m); - Mat& operator = (const MatExpr& expr); - - //! returns a new matrix header for the specified row - Mat row(int y) const; - //! returns a new matrix header for the specified column - Mat col(int x) const; - //! ... for the specified row span - Mat rowRange(int startrow, int endrow) const; - Mat rowRange(const Range& r) const; - //! ... for the specified column span - Mat colRange(int startcol, int endcol) const; - Mat colRange(const Range& r) const; - //! ... for the specified diagonal - // (d=0 - the main diagonal, - // >0 - a diagonal from the lower half, - // <0 - a diagonal from the upper half) - Mat diag(int d=0) const; - //! constructs a square diagonal matrix which main diagonal is vector "d" - static Mat diag(const Mat& d); - - //! returns deep copy of the matrix, i.e. the data is copied - Mat clone() const; - //! copies the matrix content to "m". - // It calls m.create(this->size(), this->type()). - void copyTo( OutputArray m ) const; - //! copies those matrix elements to "m" that are marked with non-zero mask elements. - void copyTo( OutputArray m, InputArray mask ) const; - //! converts matrix to another datatype with optional scalng. See cvConvertScale. - void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; - - void assignTo( Mat& m, int type=-1 ) const; - - //! sets every matrix element to s - Mat& operator = (const Scalar& s); - //! sets some of the matrix elements to s, according to the mask - Mat& setTo(InputArray value, InputArray mask=noArray()); - //! creates alternative matrix header for the same data, with different - // number of channels and/or different number of rows. see cvReshape. - Mat reshape(int cn, int rows=0) const; - Mat reshape(int cn, int newndims, const int* newsz) const; - - //! matrix transposition by means of matrix expressions - MatExpr t() const; - //! matrix inversion by means of matrix expressions - MatExpr inv(int method=DECOMP_LU) const; - //! per-element matrix multiplication by means of matrix expressions - MatExpr mul(InputArray m, double scale=1) const; - - //! computes cross-product of 2 3D vectors - Mat cross(InputArray m) const; - //! computes dot-product - double dot(InputArray m) const; - - //! Matlab-style matrix initialization - static MatExpr zeros(int rows, int cols, int type); - static MatExpr zeros(Size size, int type); - static MatExpr zeros(int ndims, const int* sz, int type); - static MatExpr ones(int rows, int cols, int type); - static MatExpr ones(Size size, int type); - static MatExpr ones(int ndims, const int* sz, int type); - static MatExpr eye(int rows, int cols, int type); - static MatExpr eye(Size size, int type); - - //! allocates new matrix data unless the matrix already has specified size and type. - // previous data is unreferenced if needed. - void create(int rows, int cols, int type); - void create(Size size, int type); - void create(int ndims, const int* sizes, int type); - - //! increases the reference counter; use with care to avoid memleaks - void addref(); - //! decreases reference counter; - // deallocates the data when reference counter reaches 0. - void release(); - - //! deallocates the matrix data - void deallocate(); - //! internal use function; properly re-allocates _size, _step arrays - void copySize(const Mat& m); - - //! reserves enough space to fit sz hyper-planes - void reserve(size_t sz); - //! resizes matrix to the specified number of hyper-planes - void resize(size_t sz); - //! resizes matrix to the specified number of hyper-planes; initializes the newly added elements - void resize(size_t sz, const Scalar& s); - //! internal function - void push_back_(const void* elem); - //! adds element to the end of 1d matrix (or possibly multiple elements when _Tp=Mat) - template void push_back(const _Tp& elem); - template void push_back(const Mat_<_Tp>& elem); - void push_back(const Mat& m); - //! removes several hyper-planes from bottom of the matrix - void pop_back(size_t nelems=1); - - //! locates matrix header within a parent matrix. See below - void locateROI( Size& wholeSize, Point& ofs ) const; - //! moves/resizes the current matrix ROI inside the parent matrix. - Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - //! extracts a rectangular sub-matrix - // (this is a generalized form of row, rowRange etc.) - Mat operator()( Range rowRange, Range colRange ) const; - Mat operator()( const Rect& roi ) const; - Mat operator()( const Range* ranges ) const; - - //! converts header to CvMat; no data is copied - operator CvMat() const; - //! converts header to CvMatND; no data is copied - operator CvMatND() const; - //! converts header to IplImage; no data is copied - operator IplImage() const; - - template operator vector<_Tp>() const; - template operator Vec<_Tp, n>() const; - template operator Matx<_Tp, m, n>() const; - - //! returns true iff the matrix data is continuous - // (i.e. when there are no gaps between successive rows). - // similar to CV_IS_MAT_CONT(cvmat->type) - bool isContinuous() const; - - //! returns true if the matrix is a submatrix of another matrix - bool isSubmatrix() const; - - //! returns element size in bytes, - // similar to CV_ELEM_SIZE(cvmat->type) - size_t elemSize() const; - //! returns the size of element channel in bytes. - size_t elemSize1() const; - //! returns element type, similar to CV_MAT_TYPE(cvmat->type) - int type() const; - //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) - int depth() const; - //! returns element type, similar to CV_MAT_CN(cvmat->type) - int channels() const; - //! returns step/elemSize1() - size_t step1(int i=0) const; - //! returns true if matrix data is NULL - bool empty() const; - //! returns the total number of matrix elements - size_t total() const; - - //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise - int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; - - //! returns pointer to i0-th submatrix along the dimension #0 - uchar* ptr(int i0=0); - const uchar* ptr(int i0=0) const; - - //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1 - uchar* ptr(int i0, int i1); - const uchar* ptr(int i0, int i1) const; - - //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2 - uchar* ptr(int i0, int i1, int i2); - const uchar* ptr(int i0, int i1, int i2) const; - - //! returns pointer to the matrix element - uchar* ptr(const int* idx); - //! returns read-only pointer to the matrix element - const uchar* ptr(const int* idx) const; - - template uchar* ptr(const Vec& idx); - template const uchar* ptr(const Vec& idx) const; - - //! template version of the above method - template _Tp* ptr(int i0=0); - template const _Tp* ptr(int i0=0) const; - - template _Tp* ptr(int i0, int i1); - template const _Tp* ptr(int i0, int i1) const; - - template _Tp* ptr(int i0, int i1, int i2); - template const _Tp* ptr(int i0, int i1, int i2) const; - - template _Tp* ptr(const int* idx); - template const _Tp* ptr(const int* idx) const; - - template _Tp* ptr(const Vec& idx); - template const _Tp* ptr(const Vec& idx) const; - - //! the same as above, with the pointer dereferencing - template _Tp& at(int i0=0); - template const _Tp& at(int i0=0) const; - - template _Tp& at(int i0, int i1); - template const _Tp& at(int i0, int i1) const; - - template _Tp& at(int i0, int i1, int i2); - template const _Tp& at(int i0, int i1, int i2) const; - - template _Tp& at(const int* idx); - template const _Tp& at(const int* idx) const; - - template _Tp& at(const Vec& idx); - template const _Tp& at(const Vec& idx) const; - - //! special versions for 2D arrays (especially convenient for referencing image pixels) - template _Tp& at(Point pt); - template const _Tp& at(Point pt) const; - - //! template methods for iteration over matrix elements. - // the iterators take care of skipping gaps in the end of rows (if any) - template MatIterator_<_Tp> begin(); - template MatIterator_<_Tp> end(); - template MatConstIterator_<_Tp> begin() const; - template MatConstIterator_<_Tp> end() const; - - enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG }; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - //! the matrix dimensionality, >= 2 - int dims; - //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions - int rows, cols; - //! pointer to the data - uchar* data; - - //! pointer to the reference counter; - // when matrix points to user-allocated data, the pointer is NULL - int* refcount; - - //! helper fields used in locateROI and adjustROI - uchar* datastart; - uchar* dataend; - uchar* datalimit; - - //! custom allocator - MatAllocator* allocator; - - struct CV_EXPORTS MSize - { - MSize(int* _p); - Size operator()() const; - const int& operator[](int i) const; - int& operator[](int i); - operator const int*() const; - bool operator == (const MSize& sz) const; - bool operator != (const MSize& sz) const; - - int* p; - }; - - struct CV_EXPORTS MStep - { - MStep(); - MStep(size_t s); - const size_t& operator[](int i) const; - size_t& operator[](int i); - operator size_t() const; - MStep& operator = (size_t s); - - size_t* p; - size_t buf[2]; - protected: - MStep& operator = (const MStep&); - }; - - MSize size; - MStep step; - -protected: - void initEmpty(); -}; - - -/*! - Random Number Generator - - The class implements RNG using Multiply-with-Carry algorithm -*/ -class CV_EXPORTS RNG -{ -public: - enum { UNIFORM=0, NORMAL=1 }; - - RNG(); - RNG(uint64 state); - //! updates the state and returns the next 32-bit unsigned integer random number - unsigned next(); - - operator uchar(); - operator schar(); - operator ushort(); - operator short(); - operator unsigned(); - //! returns a random integer sampled uniformly from [0, N). - unsigned operator ()(unsigned N); - unsigned operator ()(); - operator int(); - operator float(); - operator double(); - //! returns uniformly distributed integer random number from [a,b) range - int uniform(int a, int b); - //! returns uniformly distributed floating-point random number from [a,b) range - float uniform(float a, float b); - //! returns uniformly distributed double-precision floating-point random number from [a,b) range - double uniform(double a, double b); - void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false ); - //! returns Gaussian random variate with mean zero. - double gaussian(double sigma); - - uint64 state; -}; - -/*! - Random Number Generator - MT - - The class implements RNG using the Mersenne Twister algorithm -*/ -class CV_EXPORTS RNG_MT19937 -{ -public: - RNG_MT19937(); - RNG_MT19937(unsigned s); - void seed(unsigned s); - - unsigned next(); - - operator int(); - operator unsigned(); - operator float(); - operator double(); - - unsigned operator ()(unsigned N); - unsigned operator ()(); - - //! returns uniformly distributed integer random number from [a,b) range - int uniform(int a, int b); - //! returns uniformly distributed floating-point random number from [a,b) range - float uniform(float a, float b); - //! returns uniformly distributed double-precision floating-point random number from [a,b) range - double uniform(double a, double b); - -private: - enum PeriodParameters {N = 624, M = 397}; - unsigned state[N]; - int mti; -}; - -/*! - Termination criteria in iterative algorithms - */ -class CV_EXPORTS TermCriteria -{ -public: - enum - { - COUNT=1, //!< the maximum number of iterations or elements to compute - MAX_ITER=COUNT, //!< ditto - EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops - }; - - //! default constructor - TermCriteria(); - //! full constructor - TermCriteria(int type, int maxCount, double epsilon); - //! conversion from CvTermCriteria - TermCriteria(const CvTermCriteria& criteria); - //! conversion to CvTermCriteria - operator CvTermCriteria() const; - - int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS - int maxCount; // the maximum number of iterations/elements - double epsilon; // the desired accuracy -}; - - -typedef void (*BinaryFunc)(const uchar* src1, size_t step1, - const uchar* src2, size_t step2, - uchar* dst, size_t step, Size sz, - void*); - -CV_EXPORTS BinaryFunc getConvertFunc(int sdepth, int ddepth); -CV_EXPORTS BinaryFunc getConvertScaleFunc(int sdepth, int ddepth); -CV_EXPORTS BinaryFunc getCopyMaskFunc(size_t esz); - -//! swaps two matrices -CV_EXPORTS void swap(Mat& a, Mat& b); - -//! converts array (CvMat or IplImage) to cv::Mat -CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, - bool allowND=true, int coiMode=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); -//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage -CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); - -//! adds one matrix to another (dst = src1 + src2) -CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask=noArray(), int dtype=-1); -//! subtracts one matrix from another (dst = src1 - src2) -CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask=noArray(), int dtype=-1); - -//! computes element-wise weighted product of the two arrays (dst = scale*src1*src2) -CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, - OutputArray dst, double scale=1, int dtype=-1); - -//! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2) -CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, - double scale=1, int dtype=-1); - -//! computes element-wise weighted reciprocal of an array (dst = scale/src2) -CV_EXPORTS_W void divide(double scale, InputArray src2, - OutputArray dst, int dtype=-1); - -//! adds scaled array to another one (dst = alpha*src1 + src2) -CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); - -//! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) -CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, - double beta, double gamma, OutputArray dst, int dtype=-1); - -//! scales array elements, computes absolute values and converts the results to 8-bit unsigned integers: dst(i)=saturate_castabs(src(i)*alpha+beta) -CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, - double alpha=1, double beta=0); -//! transforms array of numbers using a lookup table: dst(i)=lut(src(i)) -CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst, - int interpolation=0); - -//! computes sum of array elements -CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); -//! computes the number of nonzero array elements -CV_EXPORTS_W int countNonZero( InputArray src ); -//! returns the list of locations of non-zero pixels -CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); - -//! computes mean value of selected array elements -CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask=noArray()); -//! computes mean value and standard deviation of all or selected array elements -CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, - InputArray mask=noArray()); -//! computes norm of the selected array part -CV_EXPORTS_W double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray()); -//! computes norm of selected part of the difference between two arrays -CV_EXPORTS_W double norm(InputArray src1, InputArray src2, - int normType=NORM_L2, InputArray mask=noArray()); - -//! naive nearest neighbor finder -CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, - OutputArray dist, int dtype, OutputArray nidx, - int normType=NORM_L2, int K=0, - InputArray mask=noArray(), int update=0, - bool crosscheck=false); - -//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values -CV_EXPORTS_W void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0, - int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray()); - -//! finds global minimum and maximum array elements and returns their values and their locations -CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, - CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0, - CV_OUT Point* maxLoc=0, InputArray mask=noArray()); -CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal, - int* minIdx=0, int* maxIdx=0, InputArray mask=noArray()); - -//! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows -CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1); - -//! makes multi-channel array out of several single-channel arrays -CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); -CV_EXPORTS void merge(const vector& mv, OutputArray dst ); - -//! makes multi-channel array out of several single-channel arrays -CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); - -//! copies each plane of a multi-channel array to a dedicated array -CV_EXPORTS void split(const Mat& src, Mat* mvbegin); -CV_EXPORTS void split(const Mat& m, vector& mv ); - -//! copies each plane of a multi-channel array to a dedicated array -CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); - -//! copies selected channels from the input arrays to the selected channels of the output arrays -CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, - const int* fromTo, size_t npairs); -CV_EXPORTS void mixChannels(const vector& src, vector& dst, - const int* fromTo, size_t npairs); -CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputArrayOfArrays dst, - const vector& fromTo); - -//! extracts a single channel from src (coi is 0-based index) -CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); - -//! inserts a single channel to dst (coi is 0-based index) -CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); - -//! reverses the order of the rows, columns or both in a matrix -CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); - -//! replicates the input matrix the specified number of times in the horizontal and/or vertical direction -CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst); -CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx); - -CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst); -CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); -CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); - -CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); -CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); -CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); - -//! computes bitwise conjunction of the two arrays (dst = src1 & src2) -CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask=noArray()); -//! computes bitwise disjunction of the two arrays (dst = src1 | src2) -CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask=noArray()); -//! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2) -CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask=noArray()); -//! inverts each bit of array (dst = ~src) -CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, - InputArray mask=noArray()); -//! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2)) -CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); -//! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) -CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, - InputArray upperb, OutputArray dst); -//! compares elements of two arrays (dst = src1 src2) -CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); -//! computes per-element minimum of two arrays (dst = min(src1, src2)) -CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); -//! computes per-element maximum of two arrays (dst = max(src1, src2)) -CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); - -//! computes per-element minimum of two arrays (dst = min(src1, src2)) -CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); -//! computes per-element minimum of array and scalar (dst = min(src1, src2)) -CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst); -//! computes per-element maximum of two arrays (dst = max(src1, src2)) -CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); -//! computes per-element maximum of array and scalar (dst = max(src1, src2)) -CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst); - -//! computes square root of each matrix element (dst = src**0.5) -CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); -//! raises the input matrix elements to the specified power (b = a**power) -CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); -//! computes exponent of each matrix element (dst = e**src) -CV_EXPORTS_W void exp(InputArray src, OutputArray dst); -//! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src)) -CV_EXPORTS_W void log(InputArray src, OutputArray dst); -//! computes cube root of the argument -CV_EXPORTS_W float cubeRoot(float val); -//! computes the angle in degrees (0..360) of the vector (x,y) -CV_EXPORTS_W float fastAtan2(float y, float x); - -CV_EXPORTS void exp(const float* src, float* dst, int n); -CV_EXPORTS void log(const float* src, float* dst, int n); -CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); -CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); - -//! converts polar coordinates to Cartesian -CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, - OutputArray x, OutputArray y, bool angleInDegrees=false); -//! converts Cartesian coordinates to polar -CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, - OutputArray magnitude, OutputArray angle, - bool angleInDegrees=false); -//! computes angle (angle(i)) of each (x(i), y(i)) vector -CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, - bool angleInDegrees=false); -//! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector -CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); -//! checks that each matrix element is within the specified range. -CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pos=0, - double minVal=-DBL_MAX, double maxVal=DBL_MAX); -//! converts NaN's to the given number -CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val=0); - -//! implements generalized matrix product algorithm GEMM from BLAS -CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, - InputArray src3, double beta, OutputArray dst, int flags=0); -//! multiplies matrix by its transposition from the left or from the right -CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, - InputArray delta=noArray(), - double scale=1, int dtype=-1 ); -//! transposes the matrix -CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); -//! performs affine transformation of each element of multi-channel input matrix -CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); -//! performs perspective transformation of each element of multi-channel input matrix -CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); - -//! extends the symmetrical matrix from the lower half or from the upper half -CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false); -//! initializes scaled identity matrix -CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1)); -//! computes determinant of a square matrix -CV_EXPORTS_W double determinant(InputArray mtx); -//! computes trace of a matrix -CV_EXPORTS_W Scalar trace(InputArray mtx); -//! computes inverse or pseudo-inverse matrix -CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags=DECOMP_LU); -//! solves linear system or a least-square problem -CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, - OutputArray dst, int flags=DECOMP_LU); - -enum -{ - SORT_EVERY_ROW=0, - SORT_EVERY_COLUMN=1, - SORT_ASCENDING=0, - SORT_DESCENDING=16 -}; - -//! sorts independently each matrix row or each matrix column -CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); -//! sorts independently each matrix row or each matrix column -CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); -//! finds real roots of a cubic polynomial -CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); -//! finds real and complex roots of a polynomial -CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300); -//! finds eigenvalues of a symmetric matrix -CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1, - int highindex=-1); -//! finds eigenvalues and eigenvectors of a symmetric matrix -CV_EXPORTS bool eigen(InputArray src, OutputArray eigenvalues, - OutputArray eigenvectors, - int lowindex=-1, int highindex=-1); -CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors, - OutputArray eigenvalues, OutputArray eigenvectors); - -enum -{ - COVAR_SCRAMBLED=0, - COVAR_NORMAL=1, - COVAR_USE_AVG=2, - COVAR_SCALE=4, - COVAR_ROWS=8, - COVAR_COLS=16 -}; - -//! computes covariation matrix of a set of samples -CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, - int flags, int ctype=CV_64F); -//! computes covariation matrix of a set of samples -CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, - OutputArray mean, int flags, int ctype=CV_64F); - -/*! - Principal Component Analysis - - The class PCA is used to compute the special basis for a set of vectors. - The basis will consist of eigenvectors of the covariance matrix computed - from the input set of vectors. After PCA is performed, vectors can be transformed from - the original high-dimensional space to the subspace formed by a few most - prominent eigenvectors (called the principal components), - corresponding to the largest eigenvalues of the covariation matrix. - Thus the dimensionality of the vector and the correlation between the coordinates is reduced. - - The following sample is the function that takes two matrices. The first one stores the set - of vectors (a row per vector) that is used to compute PCA, the second one stores another - "test" set of vectors (a row per vector) that are first compressed with PCA, - then reconstructed back and then the reconstruction error norm is computed and printed for each vector. - - \code - using namespace cv; - - PCA compressPCA(const Mat& pcaset, int maxComponents, - const Mat& testset, Mat& compressed) - { - PCA pca(pcaset, // pass the data - Mat(), // we do not have a pre-computed mean vector, - // so let the PCA engine to compute it - CV_PCA_DATA_AS_ROW, // indicate that the vectors - // are stored as matrix rows - // (use CV_PCA_DATA_AS_COL if the vectors are - // the matrix columns) - maxComponents // specify, how many principal components to retain - ); - // if there is no test data, just return the computed basis, ready-to-use - if( !testset.data ) - return pca; - CV_Assert( testset.cols == pcaset.cols ); - - compressed.create(testset.rows, maxComponents, testset.type()); - - Mat reconstructed; - for( int i = 0; i < testset.rows; i++ ) - { - Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; - // compress the vector, the result will be stored - // in the i-th row of the output matrix - pca.project(vec, coeffs); - // and then reconstruct it - pca.backProject(coeffs, reconstructed); - // and measure the error - printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); - } - return pca; - } - \endcode -*/ -class CV_EXPORTS PCA -{ -public: - //! default constructor - PCA(); - //! the constructor that performs PCA - PCA(InputArray data, InputArray mean, int flags, int maxComponents=0); - PCA(InputArray data, InputArray mean, int flags, double retainedVariance); - //! operator that performs PCA. The previously stored data, if any, is released - PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0); - PCA& computeVar(InputArray data, InputArray mean, int flags, double retainedVariance); - //! projects vector from the original space to the principal components subspace - Mat project(InputArray vec) const; - //! projects vector from the original space to the principal components subspace - void project(InputArray vec, OutputArray result) const; - //! reconstructs the original vector from the projection - Mat backProject(InputArray vec) const; - //! reconstructs the original vector from the projection - void backProject(InputArray vec, OutputArray result) const; - - Mat eigenvectors; //!< eigenvectors of the covariation matrix - Mat eigenvalues; //!< eigenvalues of the covariation matrix - Mat mean; //!< mean value subtracted before the projection and added after the back projection -}; - -CV_EXPORTS_W void PCACompute(InputArray data, CV_OUT InputOutputArray mean, - OutputArray eigenvectors, int maxComponents=0); - -CV_EXPORTS_W void PCAComputeVar(InputArray data, CV_OUT InputOutputArray mean, - OutputArray eigenvectors, double retainedVariance); - -CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - -CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - - -/*! - Singular Value Decomposition class - - The class is used to compute Singular Value Decomposition of a floating-point matrix and then - use it to solve least-square problems, under-determined linear systems, invert matrices, - compute condition numbers etc. - - For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix - when it is not necessarily to preserve it. If you want to compute condition number of a matrix - or absolute value of its determinant - you do not need SVD::u or SVD::vt, - so you can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that the full-size SVD::u and SVD::vt - must be computed, which is not necessary most of the time. -*/ -class CV_EXPORTS SVD -{ -public: - enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 }; - //! the default constructor - SVD(); - //! the constructor that performs SVD - SVD( InputArray src, int flags=0 ); - //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released. - SVD& operator ()( InputArray src, int flags=0 ); - - //! decomposes matrix and stores the results to user-provided matrices - static void compute( InputArray src, OutputArray w, - OutputArray u, OutputArray vt, int flags=0 ); - //! computes singular values of a matrix - static void compute( InputArray src, OutputArray w, int flags=0 ); - //! performs back substitution - static void backSubst( InputArray w, InputArray u, - InputArray vt, InputArray rhs, - OutputArray dst ); - - template static void compute( const Matx<_Tp, m, n>& a, - Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); - template static void compute( const Matx<_Tp, m, n>& a, - Matx<_Tp, nm, 1>& w ); - template static void backSubst( const Matx<_Tp, nm, 1>& w, - const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); - - //! finds dst = arg min_{|dst|=1} |m*dst| - static void solveZ( InputArray src, OutputArray dst ); - //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix - void backSubst( InputArray rhs, OutputArray dst ) const; - - Mat u, w, vt; -}; - -//! computes SVD of src -CV_EXPORTS_W void SVDecomp( InputArray src, CV_OUT OutputArray w, - CV_OUT OutputArray u, CV_OUT OutputArray vt, int flags=0 ); - -//! performs back substitution for the previously computed SVD -CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, - InputArray rhs, CV_OUT OutputArray dst ); - -//! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix -CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); -//! a synonym for Mahalanobis -CV_EXPORTS double Mahalonobis(InputArray v1, InputArray v2, InputArray icovar); - -//! performs forward or inverse 1D or 2D Discrete Fourier Transformation -CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0); -//! performs inverse 1D or 2D Discrete Fourier Transformation -CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0); -//! performs forward or inverse 1D or 2D Discrete Cosine Transformation -CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags=0); -//! performs inverse 1D or 2D Discrete Cosine Transformation -CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags=0); -//! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication -CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, - int flags, bool conjB=false); -//! computes the minimal vector size vecsize1 >= vecsize so that the dft() of the vector of length vecsize1 can be computed efficiently -CV_EXPORTS_W int getOptimalDFTSize(int vecsize); - -/*! - Various k-Means flags -*/ -enum -{ - KMEANS_RANDOM_CENTERS=0, // Chooses random centers for k-Means initialization - KMEANS_PP_CENTERS=2, // Uses k-Means++ algorithm for initialization - KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization -}; -//! clusters the input data using k-Means algorithm -CV_EXPORTS_W double kmeans( InputArray data, int K, CV_OUT InputOutputArray bestLabels, - TermCriteria criteria, int attempts, - int flags, OutputArray centers=noArray() ); - -//! returns the thread-local Random number generator -CV_EXPORTS RNG& theRNG(); - -//! returns the next unifomly-distributed random number of the specified type -template static inline _Tp randu() { return (_Tp)theRNG(); } - -//! fills array with uniformly-distributed random numbers from the range [low, high) -CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); - -//! fills array with normally-distributed random numbers with the specified mean and the standard deviation -CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); - -//! shuffles the input array elements -CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0); -CV_EXPORTS_AS(randShuffle) void randShuffle_(InputOutputArray dst, double iterFactor=1.); - -//! draws the line segment (pt1, pt2) in the image -CV_EXPORTS_W void line(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color, - int thickness=1, int lineType=8, int shift=0); - -//! draws an arrow from pt1 to pt2 in the image -CV_EXPORTS_W void arrowedLine(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color, - int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); - -//! draws the rectangle outline or a solid rectangle with the opposite corners pt1 and pt2 in the image -CV_EXPORTS_W void rectangle(CV_IN_OUT Mat& img, Point pt1, Point pt2, - const Scalar& color, int thickness=1, - int lineType=8, int shift=0); - -//! draws the rectangle outline or a solid rectangle covering rec in the image -CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec, - const Scalar& color, int thickness=1, - int lineType=8, int shift=0); - -//! draws the circle outline or a solid circle in the image -CV_EXPORTS_W void circle(CV_IN_OUT Mat& img, Point center, int radius, - const Scalar& color, int thickness=1, - int lineType=8, int shift=0); - -//! draws an elliptic arc, ellipse sector or a rotated ellipse in the image -CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, Point center, Size axes, - double angle, double startAngle, double endAngle, - const Scalar& color, int thickness=1, - int lineType=8, int shift=0); - -//! draws a rotated ellipse in the image -CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, const RotatedRect& box, const Scalar& color, - int thickness=1, int lineType=8); - -//! draws a filled convex polygon in the image -CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts, - const Scalar& color, int lineType=8, - int shift=0); -CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, - const Scalar& color, int lineType=8, - int shift=0); - -//! fills an area bounded by one or more polygons -CV_EXPORTS void fillPoly(Mat& img, const Point** pts, - const int* npts, int ncontours, - const Scalar& color, int lineType=8, int shift=0, - Point offset=Point() ); - -CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, - const Scalar& color, int lineType=8, int shift=0, - Point offset=Point() ); - -//! draws one or more polygonal curves -CV_EXPORTS void polylines(Mat& img, const Point** pts, const int* npts, - int ncontours, bool isClosed, const Scalar& color, - int thickness=1, int lineType=8, int shift=0 ); - -CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, - bool isClosed, const Scalar& color, - int thickness=1, int lineType=8, int shift=0 ); - -//! clips the line segment by the rectangle Rect(0, 0, imgSize.width, imgSize.height) -CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); - -//! clips the line segment by the rectangle imgRect -CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); - -/*! - Line iterator class - - The class is used to iterate over all the pixels on the raster line - segment connecting two specified points. -*/ -class CV_EXPORTS LineIterator -{ -public: - //! intializes the iterator - LineIterator( const Mat& img, Point pt1, Point pt2, - int connectivity=8, bool leftToRight=false ); - //! returns pointer to the current pixel - uchar* operator *(); - //! prefix increment operator (++it). shifts iterator to the next pixel - LineIterator& operator ++(); - //! postfix increment operator (it++). shifts iterator to the next pixel - LineIterator operator ++(int); - //! returns coordinates of the current pixel - Point pos() const; - - uchar* ptr; - const uchar* ptr0; - int step, elemSize; - int err, count; - int minusDelta, plusDelta; - int minusStep, plusStep; -}; - -//! converts elliptic arc to a polygonal curve -CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, - int arcStart, int arcEnd, int delta, - CV_OUT vector& pts ); - -enum -{ - FONT_HERSHEY_SIMPLEX = 0, - FONT_HERSHEY_PLAIN = 1, - FONT_HERSHEY_DUPLEX = 2, - FONT_HERSHEY_COMPLEX = 3, - FONT_HERSHEY_TRIPLEX = 4, - FONT_HERSHEY_COMPLEX_SMALL = 5, - FONT_HERSHEY_SCRIPT_SIMPLEX = 6, - FONT_HERSHEY_SCRIPT_COMPLEX = 7, - FONT_ITALIC = 16 -}; - -//! renders text string in the image -CV_EXPORTS_W void putText( Mat& img, const string& text, Point org, - int fontFace, double fontScale, Scalar color, - int thickness=1, int lineType=8, - bool bottomLeftOrigin=false ); - -//! returns bounding box of the text string -CV_EXPORTS_W Size getTextSize(const string& text, int fontFace, - double fontScale, int thickness, - CV_OUT int* baseLine); - -///////////////////////////////// Mat_<_Tp> //////////////////////////////////// - -/*! - Template matrix class derived from Mat - - The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields, - nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes - can be safely converted one to another. But do it with care, for example: - - \code - // create 100x100 8-bit matrix - Mat M(100,100,CV_8U); - // this will compile fine. no any data conversion will be done. - Mat_& M1 = (Mat_&)M; - // the program will likely crash at the statement below - M1(99,99) = 1.f; - \endcode - - While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element - access operations and if you know matrix type at compile time. - Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the - same thing and run at the same speed, but the latter is certainly shorter: - - \code - Mat_ M(20,20); - for(int i = 0; i < M.rows; i++) - for(int j = 0; j < M.cols; j++) - M(i,j) = 1./(i+j+1); - Mat E, V; - eigen(M,E,V); - cout << E.at(0,0)/E.at(M.rows-1,0); - \endcode - - It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter: - - \code - // allocate 320x240 color image and fill it with green (in RGB space) - Mat_ img(240, 320, Vec3b(0,255,0)); - // now draw a diagonal white line - for(int i = 0; i < 100; i++) - img(i,i)=Vec3b(255,255,255); - // and now modify the 2nd (red) channel of each pixel - for(int i = 0; i < img.rows; i++) - for(int j = 0; j < img.cols; j++) - img(i,j)[2] ^= (uchar)(i ^ j); // img(y,x)[c] accesses c-th channel of the pixel (x,y) - \endcode -*/ -template class Mat_ : public Mat -{ -public: - typedef _Tp value_type; - typedef typename DataType<_Tp>::channel_type channel_type; - typedef MatIterator_<_Tp> iterator; - typedef MatConstIterator_<_Tp> const_iterator; - - //! default constructor - Mat_(); - //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) - Mat_(int _rows, int _cols); - //! constructor that sets each matrix element to specified value - Mat_(int _rows, int _cols, const _Tp& value); - //! equivalent to Mat(_size, DataType<_Tp>::type) - explicit Mat_(Size _size); - //! constructor that sets each matrix element to specified value - Mat_(Size _size, const _Tp& value); - //! n-dim array constructor - Mat_(int _ndims, const int* _sizes); - //! n-dim array constructor that sets each matrix element to specified value - Mat_(int _ndims, const int* _sizes, const _Tp& value); - //! copy/conversion contructor. If m is of different type, it's converted - Mat_(const Mat& m); - //! copy constructor - Mat_(const Mat_& m); - //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type - Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); - //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type - Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); - //! selects a submatrix - Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); - //! selects a submatrix - Mat_(const Mat_& m, const Rect& roi); - //! selects a submatrix, n-dim version - Mat_(const Mat_& m, const Range* ranges); - //! from a matrix expression - explicit Mat_(const MatExpr& e); - //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column - explicit Mat_(const vector<_Tp>& vec, bool copyData=false); - template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); - template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); - explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); - explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); - explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); - - Mat_& operator = (const Mat& m); - Mat_& operator = (const Mat_& m); - //! set all the elements to s. - Mat_& operator = (const _Tp& s); - //! assign a matrix expression - Mat_& operator = (const MatExpr& e); - - //! iterators; they are smart enough to skip gaps in the end of rows - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) - void create(int _rows, int _cols); - //! equivalent to Mat::create(_size, DataType<_Tp>::type) - void create(Size _size); - //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) - void create(int _ndims, const int* _sizes); - //! cross-product - Mat_ cross(const Mat_& m) const; - //! data type conversion - template operator Mat_() const; - //! overridden forms of Mat::row() etc. - Mat_ row(int y) const; - Mat_ col(int x) const; - Mat_ diag(int d=0) const; - Mat_ clone() const; - - //! overridden forms of Mat::elemSize() etc. - size_t elemSize() const; - size_t elemSize1() const; - int type() const; - int depth() const; - int channels() const; - size_t step1(int i=0) const; - //! returns step()/sizeof(_Tp) - size_t stepT(int i=0) const; - - //! overridden forms of Mat::zeros() etc. Data type is omitted, of course - static MatExpr zeros(int rows, int cols); - static MatExpr zeros(Size size); - static MatExpr zeros(int _ndims, const int* _sizes); - static MatExpr ones(int rows, int cols); - static MatExpr ones(Size size); - static MatExpr ones(int _ndims, const int* _sizes); - static MatExpr eye(int rows, int cols); - static MatExpr eye(Size size); - - //! some more overriden methods - Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); - Mat_ operator()( const Range& rowRange, const Range& colRange ) const; - Mat_ operator()( const Rect& roi ) const; - Mat_ operator()( const Range* ranges ) const; - - //! more convenient forms of row and element access operators - _Tp* operator [](int y); - const _Tp* operator [](int y) const; - - //! returns reference to the specified element - _Tp& operator ()(const int* idx); - //! returns read-only reference to the specified element - const _Tp& operator ()(const int* idx) const; - - //! returns reference to the specified element - template _Tp& operator ()(const Vec& idx); - //! returns read-only reference to the specified element - template const _Tp& operator ()(const Vec& idx) const; - - //! returns reference to the specified element (1D case) - _Tp& operator ()(int idx0); - //! returns read-only reference to the specified element (1D case) - const _Tp& operator ()(int idx0) const; - //! returns reference to the specified element (2D case) - _Tp& operator ()(int idx0, int idx1); - //! returns read-only reference to the specified element (2D case) - const _Tp& operator ()(int idx0, int idx1) const; - //! returns reference to the specified element (3D case) - _Tp& operator ()(int idx0, int idx1, int idx2); - //! returns read-only reference to the specified element (3D case) - const _Tp& operator ()(int idx0, int idx1, int idx2) const; - - _Tp& operator ()(Point pt); - const _Tp& operator ()(Point pt) const; - - //! conversion to vector. - operator vector<_Tp>() const; - //! conversion to Vec - template operator Vec::channel_type, n>() const; - //! conversion to Matx - template operator Matx::channel_type, m, n>() const; -}; - -typedef Mat_ Mat1b; -typedef Mat_ Mat2b; -typedef Mat_ Mat3b; -typedef Mat_ Mat4b; - -typedef Mat_ Mat1s; -typedef Mat_ Mat2s; -typedef Mat_ Mat3s; -typedef Mat_ Mat4s; - -typedef Mat_ Mat1w; -typedef Mat_ Mat2w; -typedef Mat_ Mat3w; -typedef Mat_ Mat4w; - -typedef Mat_ Mat1i; -typedef Mat_ Mat2i; -typedef Mat_ Mat3i; -typedef Mat_ Mat4i; - -typedef Mat_ Mat1f; -typedef Mat_ Mat2f; -typedef Mat_ Mat3f; -typedef Mat_ Mat4f; - -typedef Mat_ Mat1d; -typedef Mat_ Mat2d; -typedef Mat_ Mat3d; -typedef Mat_ Mat4d; - -//////////// Iterators & Comma initializers ////////////////// - -class CV_EXPORTS MatConstIterator -{ -public: - typedef uchar* value_type; - typedef ptrdiff_t difference_type; - typedef const uchar** pointer; - typedef uchar* reference; - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator(const Mat* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, const int* _idx); - //! copy constructor - MatConstIterator(const MatConstIterator& it); - - //! copy operator - MatConstIterator& operator = (const MatConstIterator& it); - //! returns the current matrix element - uchar* operator *() const; - //! returns the i-th matrix element, relative to the current - uchar* operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator& operator --(); - //! decrements the iterator - MatConstIterator operator --(int); - //! increments the iterator - MatConstIterator& operator ++(); - //! increments the iterator - MatConstIterator operator ++(int); - //! returns the current iterator position - Point pos() const; - //! returns the current iterator position - void pos(int* _idx) const; - ptrdiff_t lpos() const; - void seek(ptrdiff_t ofs, bool relative=false); - void seek(const int* _idx, bool relative=false); - - const Mat* m; - size_t elemSize; - uchar* ptr; - uchar* sliceStart; - uchar* sliceEnd; -}; - -/*! - Matrix read-only iterator - - */ -template -class MatConstIterator_ : public MatConstIterator -{ -public: - typedef _Tp value_type; - typedef ptrdiff_t difference_type; - typedef const _Tp* pointer; - typedef const _Tp& reference; - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator_(const Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatConstIterator_(const MatConstIterator_& it); - - //! copy operator - MatConstIterator_& operator = (const MatConstIterator_& it); - //! returns the current matrix element - _Tp operator *() const; - //! returns the i-th matrix element, relative to the current - _Tp operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator_& operator --(); - //! decrements the iterator - MatConstIterator_ operator --(int); - //! increments the iterator - MatConstIterator_& operator ++(); - //! increments the iterator - MatConstIterator_ operator ++(int); - //! returns the current iterator position - Point pos() const; -}; - - -/*! - Matrix read-write iterator - -*/ -template -class MatIterator_ : public MatConstIterator_<_Tp> -{ -public: - typedef _Tp* pointer; - typedef _Tp& reference; - typedef std::random_access_iterator_tag iterator_category; - - //! the default constructor - MatIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatIterator_(Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(const Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(const Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatIterator_(const MatIterator_& it); - //! copy operator - MatIterator_& operator = (const MatIterator_<_Tp>& it ); - - //! returns the current matrix element - _Tp& operator *() const; - //! returns the i-th matrix element, relative to the current - _Tp& operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatIterator_& operator --(); - //! decrements the iterator - MatIterator_ operator --(int); - //! increments the iterator - MatIterator_& operator ++(); - //! increments the iterator - MatIterator_ operator ++(int); -}; - -template class MatOp_Iter_; - -/*! - Comma-separated Matrix Initializer - - The class instances are usually not created explicitly. - Instead, they are created on "matrix << firstValue" operator. - - The sample below initializes 2x2 rotation matrix: - - \code - double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); - Mat R = (Mat_(2,2) << a, -b, b, a); - \endcode -*/ -template class MatCommaInitializer_ -{ -public: - //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat - MatCommaInitializer_(Mat_<_Tp>* _m); - //! the operator that takes the next value and put it to the matrix - template MatCommaInitializer_<_Tp>& operator , (T2 v); - //! another form of conversion operator - Mat_<_Tp> operator *() const; - operator Mat_<_Tp>() const; -protected: - MatIterator_<_Tp> it; -}; - - -template class MatxCommaInitializer -{ -public: - MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); - template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); - Matx<_Tp, m, n> operator *() const; - - Matx<_Tp, m, n>* dst; - int idx; -}; - -template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> -{ -public: - VecCommaInitializer(Vec<_Tp, m>* _vec); - template VecCommaInitializer<_Tp, m>& operator , (T2 val); - Vec<_Tp, m> operator *() const; -}; - -/*! - Automatically Allocated Buffer Class - - The class is used for temporary buffers in functions and methods. - If a temporary buffer is usually small (a few K's of memory), - but its size depends on the parameters, it makes sense to create a small - fixed-size array on stack and use it if it's large enough. If the required buffer size - is larger than the fixed size, another buffer of sufficient size is allocated dynamically - and released after the processing. Therefore, in typical cases, when the buffer size is small, - there is no overhead associated with malloc()/free(). - At the same time, there is no limit on the size of processed data. - - This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and - the number of stack-allocated elements. Here is how the class is used: - - \code - void my_func(const cv::Mat& m) - { - cv::AutoBuffer buf; // create automatic buffer containing 1000 floats - - buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, - // otherwise the buffer of "m.rows" floats will be allocated - // dynamically and deallocated in cv::AutoBuffer destructor - ... - } - \endcode -*/ -template class AutoBuffer -{ -public: - typedef _Tp value_type; - enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) }; - - //! the default contructor - AutoBuffer(); - //! constructor taking the real buffer size - AutoBuffer(size_t _size); - //! destructor. calls deallocate() - ~AutoBuffer(); - - //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used - void allocate(size_t _size); - //! deallocates the buffer if it was dynamically allocated - void deallocate(); - //! returns pointer to the real buffer, stack-allocated or head-allocated - operator _Tp* (); - //! returns read-only pointer to the real buffer, stack-allocated or head-allocated - operator const _Tp* () const; - -protected: - //! pointer to the real buffer, can point to buf if the buffer is small enough - _Tp* ptr; - //! size of the real buffer - size_t size; - //! pre-allocated buffer - _Tp buf[fixed_size+buffer_padding]; -}; - -/////////////////////////// multi-dimensional dense matrix ////////////////////////// - -/*! - n-Dimensional Dense Matrix Iterator Class. - - The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's). - - The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators. - It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays. - - Here is the example on how the iterator can be used to normalize 3D histogram: - - \code - void normalizeColorHist(Mat& hist) - { - #if 1 - // intialize iterator (the style is different from STL). - // after initialization the iterator will contain - // the number of slices or planes - // the iterator will go through - Mat* arrays[] = { &hist, 0 }; - Mat planes[1]; - NAryMatIterator it(arrays, planes); - double s = 0; - // iterate through the matrix. on each iteration - // it.planes[i] (of type Mat) will be set to the current plane of - // i-th n-dim matrix passed to the iterator constructor. - for(int p = 0; p < it.nplanes; p++, ++it) - s += sum(it.planes[0])[0]; - it = NAryMatIterator(hist); - s = 1./s; - for(int p = 0; p < it.nplanes; p++, ++it) - it.planes[0] *= s; - #elif 1 - // this is a shorter implementation of the above - // using built-in operations on Mat - double s = sum(hist)[0]; - hist.convertTo(hist, hist.type(), 1./s, 0); - #else - // and this is even shorter one - // (assuming that the histogram elements are non-negative) - normalize(hist, hist, 1, 0, NORM_L1); - #endif - } - \endcode - - You can iterate through several matrices simultaneously as long as they have the same geometry - (dimensionality and all the dimension sizes are the same), which is useful for binary - and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator. - Then, during the iteration it.planes[0], it.planes[1], ... will - be the slices of the corresponding matrices -*/ -class CV_EXPORTS NAryMatIterator -{ -public: - //! the default constructor - NAryMatIterator(); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); - //! the separate iterator initialization method - void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); - - //! proceeds to the next plane of every iterated matrix - NAryMatIterator& operator ++(); - //! proceeds to the next plane of every iterated matrix (postfix increment operator) - NAryMatIterator operator ++(int); - - //! the iterated arrays - const Mat** arrays; - //! the current planes - Mat* planes; - //! data pointers - uchar** ptrs; - //! the number of arrays - int narrays; - //! the number of hyper-planes that the iterator steps through - size_t nplanes; - //! the size of each segment (in elements) - size_t size; -protected: - int iterdepth; - size_t idx; -}; - -//typedef NAryMatIterator NAryMatNDIterator; - -typedef void (*ConvertData)(const void* from, void* to, int cn); -typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double beta); - -//! returns the function for converting pixels from one data type to another -CV_EXPORTS ConvertData getConvertElem(int fromType, int toType); -//! returns the function for converting pixels from one data type to another with the optional scaling -CV_EXPORTS ConvertScaleData getConvertScaleElem(int fromType, int toType); - - -/////////////////////////// multi-dimensional sparse matrix ////////////////////////// - -class SparseMatIterator; -class SparseMatConstIterator; -template class SparseMatIterator_; -template class SparseMatConstIterator_; - -/*! - Sparse matrix class. - - The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements - of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements - are stored (though, as a result of some operations on a sparse matrix, some of its stored elements - can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase(). - The non-zero elements are stored in a hash table that grows when it's filled enough, - so that the search time remains O(1) in average. Elements can be accessed using the following methods: - -
    -
  1. Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(), - cv::SparseMat::value() and cv::SparseMat::find, for example: - \code - const int dims = 5; - int size[] = {10, 10, 10, 10, 10}; - SparseMat sparse_mat(dims, size, CV_32F); - for(int i = 0; i < 1000; i++) - { - int idx[dims]; - for(int k = 0; k < dims; k++) - idx[k] = rand()%sparse_mat.size(k); - sparse_mat.ref(idx) += 1.f; - } - \endcode - -
  2. Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style, - that is, the iteration is done as following: - \code - // prints elements of a sparse floating-point matrix and the sum of elements. - SparseMatConstIterator_ - it = sparse_mat.begin(), - it_end = sparse_mat.end(); - double s = 0; - int dims = sparse_mat.dims(); - for(; it != it_end; ++it) - { - // print element indices and the element value - const Node* n = it.node(); - printf("(") - for(int i = 0; i < dims; i++) - printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')'); - printf(": %f\n", *it); - s += *it; - } - printf("Element sum is %g\n", s); - \endcode - If you run this loop, you will notice that elements are enumerated - in no any logical order (lexicographical etc.), - they come in the same order as they stored in the hash table, i.e. semi-randomly. - - You may collect pointers to the nodes and sort them to get the proper ordering. - Note, however, that pointers to the nodes may become invalid when you add more - elements to the matrix; this is because of possible buffer reallocation. - -
  3. A combination of the above 2 methods when you need to process 2 or more sparse - matrices simultaneously, e.g. this is how you can compute unnormalized - cross-correlation of the 2 floating-point sparse matrices: - \code - double crossCorr(const SparseMat& a, const SparseMat& b) - { - const SparseMat *_a = &a, *_b = &b; - // if b contains less elements than a, - // it's faster to iterate through b - if(_a->nzcount() > _b->nzcount()) - std::swap(_a, _b); - SparseMatConstIterator_ it = _a->begin(), - it_end = _a->end(); - double ccorr = 0; - for(; it != it_end; ++it) - { - // take the next element from the first matrix - float avalue = *it; - const Node* anode = it.node(); - // and try to find element with the same index in the second matrix. - // since the hash value depends only on the element index, - // we reuse hashvalue stored in the node - float bvalue = _b->value(anode->idx,&anode->hashval); - ccorr += avalue*bvalue; - } - return ccorr; - } - \endcode -
-*/ -class CV_EXPORTS SparseMat -{ -public: - typedef SparseMatIterator iterator; - typedef SparseMatConstIterator const_iterator; - - //! the sparse matrix header - struct CV_EXPORTS Hdr - { - Hdr(int _dims, const int* _sizes, int _type); - void clear(); - int refcount; - int dims; - int valueOffset; - size_t nodeSize; - size_t nodeCount; - size_t freeList; - vector pool; - vector hashtab; - int size[CV_MAX_DIM]; - }; - - //! sparse matrix node - element of a hash table - struct CV_EXPORTS Node - { - //! hash value - size_t hashval; - //! index of the next node in the same hash table entry - size_t next; - //! index of the matrix element - int idx[CV_MAX_DIM]; - }; - - //! default constructor - SparseMat(); - //! creates matrix of the specified size and type - SparseMat(int dims, const int* _sizes, int _type); - //! copy constructor - SparseMat(const SparseMat& m); - //! converts dense 2d matrix to the sparse form - /*! - \param m the input matrix - */ - explicit SparseMat(const Mat& m); - //! converts old-style sparse matrix to the new-style. All the data is copied - SparseMat(const CvSparseMat* m); - //! the destructor - ~SparseMat(); - - //! assignment operator. This is O(1) operation, i.e. no data is copied - SparseMat& operator = (const SparseMat& m); - //! equivalent to the corresponding constructor - SparseMat& operator = (const Mat& m); - - //! creates full copy of the matrix - SparseMat clone() const; - - //! copies all the data to the destination matrix. All the previous content of m is erased - void copyTo( SparseMat& m ) const; - //! converts sparse matrix to dense matrix. - void copyTo( Mat& m ) const; - //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type - void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; - //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. - /*! - \param rtype The output matrix data type. When it is =-1, the output array will have the same data type as (*this) - \param alpha The scale factor - \param beta The optional delta added to the scaled values before the conversion - */ - void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; - - // not used now - void assignTo( SparseMat& m, int type=-1 ) const; - - //! reallocates sparse matrix. - /*! - If the matrix already had the proper size and type, - it is simply cleared with clear(), otherwise, - the old matrix is released (using release()) and the new one is allocated. - */ - void create(int dims, const int* _sizes, int _type); - //! sets all the sparse matrix elements to 0, which means clearing the hash table. - void clear(); - //! manually increments the reference counter to the header. - void addref(); - // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. - void release(); - - //! converts sparse matrix to the old-style representation; all the elements are copied. - operator CvSparseMat*() const; - //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) - size_t elemSize() const; - //! returns elemSize()/channels() - size_t elemSize1() const; - - //! returns type of sparse matrix elements - int type() const; - //! returns the depth of sparse matrix elements - int depth() const; - //! returns the number of channels - int channels() const; - - //! returns the array of sizes, or NULL if the matrix is not allocated - const int* size() const; - //! returns the size of i-th matrix dimension (or 0) - int size(int i) const; - //! returns the matrix dimensionality - int dims() const; - //! returns the number of non-zero elements (=the number of hash table nodes) - size_t nzcount() const; - - //! computes the element hash value (1D case) - size_t hash(int i0) const; - //! computes the element hash value (2D case) - size_t hash(int i0, int i1) const; - //! computes the element hash value (3D case) - size_t hash(int i0, int i1, int i2) const; - //! computes the element hash value (nD case) - size_t hash(const int* idx) const; - - //@{ - /*! - specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. - - return pointer to the matrix element. -
    -
  • if the element is there (it's non-zero), the pointer to it is returned -
  • if it's not there and createMissing=false, NULL pointer is returned -
  • if it's not there and createMissing=true, then the new element - is created and initialized with 0. Pointer to it is returned -
  • if the optional hashval pointer is not NULL, the element hash value is - not computed, but *hashval is taken instead. -
- */ - //! returns pointer to the specified element (1D case) - uchar* ptr(int i0, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (2D case) - uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (3D case) - uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (nD case) - uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); - //@} - - //@{ - /*! - return read-write reference to the specified sparse matrix element. - - ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]). - The methods always return a valid reference. - If the element did not exist, it is created and initialiazed with 0. - */ - //! returns reference to the specified element (1D case) - template _Tp& ref(int i0, size_t* hashval=0); - //! returns reference to the specified element (2D case) - template _Tp& ref(int i0, int i1, size_t* hashval=0); - //! returns reference to the specified element (3D case) - template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! returns reference to the specified element (nD case) - template _Tp& ref(const int* idx, size_t* hashval=0); - //@} - - //@{ - /*! - return value of the specified sparse matrix element. - - value<_Tp>(i0,...[,hashval]) is equivalent - - \code - { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } - \endcode - - That is, if the element did not exist, the methods return 0. - */ - //! returns value of the specified element (1D case) - template _Tp value(int i0, size_t* hashval=0) const; - //! returns value of the specified element (2D case) - template _Tp value(int i0, int i1, size_t* hashval=0) const; - //! returns value of the specified element (3D case) - template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns value of the specified element (nD case) - template _Tp value(const int* idx, size_t* hashval=0) const; - //@} - - //@{ - /*! - Return pointer to the specified sparse matrix element if it exists - - find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]). - - If the specified element does not exist, the methods return NULL. - */ - //! returns pointer to the specified element (1D case) - template const _Tp* find(int i0, size_t* hashval=0) const; - //! returns pointer to the specified element (2D case) - template const _Tp* find(int i0, int i1, size_t* hashval=0) const; - //! returns pointer to the specified element (3D case) - template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns pointer to the specified element (nD case) - template const _Tp* find(const int* idx, size_t* hashval=0) const; - - //! erases the specified element (2D case) - void erase(int i0, int i1, size_t* hashval=0); - //! erases the specified element (3D case) - void erase(int i0, int i1, int i2, size_t* hashval=0); - //! erases the specified element (nD case) - void erase(const int* idx, size_t* hashval=0); - - //@{ - /*! - return the sparse matrix iterator pointing to the first sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix beginning - SparseMatIterator begin(); - //! returns the sparse matrix iterator at the matrix beginning - template SparseMatIterator_<_Tp> begin(); - //! returns the read-only sparse matrix iterator at the matrix beginning - SparseMatConstIterator begin() const; - //! returns the read-only sparse matrix iterator at the matrix beginning - template SparseMatConstIterator_<_Tp> begin() const; - //@} - /*! - return the sparse matrix iterator pointing to the element following the last sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix end - SparseMatIterator end(); - //! returns the read-only sparse matrix iterator at the matrix end - SparseMatConstIterator end() const; - //! returns the typed sparse matrix iterator at the matrix end - template SparseMatIterator_<_Tp> end(); - //! returns the typed read-only sparse matrix iterator at the matrix end - template SparseMatConstIterator_<_Tp> end() const; - - //! returns the value stored in the sparse martix node - template _Tp& value(Node* n); - //! returns the value stored in the sparse martix node - template const _Tp& value(const Node* n) const; - - ////////////// some internal-use methods /////////////// - Node* node(size_t nidx); - const Node* node(size_t nidx) const; - - uchar* newNode(const int* idx, size_t hashval); - void removeNode(size_t hidx, size_t nidx, size_t previdx); - void resizeHashTab(size_t newsize); - - enum { MAGIC_VAL=0x42FD0000, MAX_DIM=CV_MAX_DIM, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; - - int flags; - Hdr* hdr; -}; - -//! finds global minimum and maximum sparse array elements and returns their values and their locations -CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, - double* maxVal, int* minIdx=0, int* maxIdx=0); -//! computes norm of a sparse matrix -CV_EXPORTS double norm( const SparseMat& src, int normType ); -//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values -CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); - -/*! - Read-Only Sparse Matrix Iterator. - Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: - - \code - SparseMatConstIterator it = m.begin(), it_end = m.end(); - double s = 0; - CV_Assert( m.type() == CV_32F ); - for( ; it != it_end; ++it ) - s += it.value(); - \endcode -*/ -class CV_EXPORTS SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatConstIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator(const SparseMatConstIterator& it); - - //! the assignment operator - SparseMatConstIterator& operator = (const SparseMatConstIterator& it); - - //! template method returning the current matrix element - template const _Tp& value() const; - //! returns the current node of the sparse matrix. it.node->idx is the current element index - const SparseMat::Node* node() const; - - //! moves iterator to the previous element - SparseMatConstIterator& operator --(); - //! moves iterator to the previous element - SparseMatConstIterator operator --(int); - //! moves iterator to the next element - SparseMatConstIterator& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator operator ++(int); - - //! moves iterator to the element after the last element - void seekEnd(); - - const SparseMat* m; - size_t hashidx; - uchar* ptr; -}; - -/*! - Read-write Sparse Matrix Iterator - - The class is similar to cv::SparseMatConstIterator, - but can be used for in-place modification of the matrix elements. -*/ -class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator(SparseMat* _m); - //! the full constructor setting the iterator to the specified sparse matrix element - SparseMatIterator(SparseMat* _m, const int* idx); - //! the copy constructor - SparseMatIterator(const SparseMatIterator& it); - - //! the assignment operator - SparseMatIterator& operator = (const SparseMatIterator& it); - //! returns read-write reference to the current sparse matrix element - template _Tp& value() const; - //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) - SparseMat::Node* node() const; - - //! moves iterator to the next element - SparseMatIterator& operator ++(); - //! moves iterator to the next element - SparseMatIterator operator ++(int); -}; - -/*! - The Template Sparse Matrix class derived from cv::SparseMat - - The class provides slightly more convenient operations for accessing elements. - - \code - SparseMat m; - ... - SparseMat_ m_ = (SparseMat_&)m; - m_.ref(1)++; // equivalent to m.ref(1)++; - m_.ref(2) += m_(3); // equivalent to m.ref(2) += m.value(3); - \endcode -*/ -template class SparseMat_ : public SparseMat -{ -public: - typedef SparseMatIterator_<_Tp> iterator; - typedef SparseMatConstIterator_<_Tp> const_iterator; - - //! the default constructor - SparseMat_(); - //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type) - SparseMat_(int dims, const int* _sizes); - //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_(const SparseMat& m); - //! the copy constructor. This is O(1) operation - no data is copied - SparseMat_(const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_(const Mat& m); - //! converts the old-style sparse matrix to the C++ class. All the elements are copied - SparseMat_(const CvSparseMat* m); - //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_& operator = (const SparseMat& m); - //! the assignment operator. This is O(1) operation - no data is copied - SparseMat_& operator = (const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_& operator = (const Mat& m); - - //! makes full copy of the matrix. All the elements are duplicated - SparseMat_ clone() const; - //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) - void create(int dims, const int* _sizes); - //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied - operator CvSparseMat*() const; - - //! returns type of the matrix elements - int type() const; - //! returns depth of the matrix elements - int depth() const; - //! returns the number of channels in each matrix element - int channels() const; - - //! equivalent to SparseMat::ref<_Tp>(i0, hashval) - _Tp& ref(int i0, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) - _Tp& ref(int i0, int i1, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) - _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(idx, hashval) - _Tp& ref(const int* idx, size_t* hashval=0); - - //! equivalent to SparseMat::value<_Tp>(i0, hashval) - _Tp operator()(int i0, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) - _Tp operator()(int i0, int i1, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) - _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(idx, hashval) - _Tp operator()(const int* idx, size_t* hashval=0) const; - - //! returns sparse matrix iterator pointing to the first sparse matrix element - SparseMatIterator_<_Tp> begin(); - //! returns read-only sparse matrix iterator pointing to the first sparse matrix element - SparseMatConstIterator_<_Tp> begin() const; - //! returns sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatIterator_<_Tp> end(); - //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatConstIterator_<_Tp> end() const; -}; - - -/*! - Template Read-Only Sparse Matrix Iterator Class. - - This is the derived from SparseMatConstIterator class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatConstIterator_ : public SparseMatConstIterator -{ -public: - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatConstIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator_(const SparseMat_<_Tp>* _m); - SparseMatConstIterator_(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator_(const SparseMatConstIterator_& it); - - //! the assignment operator - SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); - //! the element access operator - const _Tp& operator *() const; - - //! moves iterator to the next element - SparseMatConstIterator_& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator_ operator ++(int); -}; - -/*! - Template Read-Write Sparse Matrix Iterator Class. - - This is the derived from cv::SparseMatConstIterator_ class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> -{ -public: - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator_(SparseMat_<_Tp>* _m); - SparseMatIterator_(SparseMat* _m); - //! the copy constructor - SparseMatIterator_(const SparseMatIterator_& it); - - //! the assignment operator - SparseMatIterator_& operator = (const SparseMatIterator_& it); - //! returns the reference to the current element - _Tp& operator *() const; - - //! moves the iterator to the next element - SparseMatIterator_& operator ++(); - //! moves the iterator to the next element - SparseMatIterator_ operator ++(int); -}; - -//////////////////// Fast Nearest-Neighbor Search Structure //////////////////// - -/*! - Fast Nearest Neighbor Search Class. - - The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last - approximate (or accurate) nearest neighbor search in multi-dimensional spaces. - - First, a set of vectors is passed to KDTree::KDTree() constructor - or KDTree::build() method, where it is reordered. - - Then arbitrary vectors can be passed to KDTree::findNearest() methods, which - find the K nearest neighbors among the vectors from the initial set. - The user can balance between the speed and accuracy of the search by varying Emax - parameter, which is the number of leaves that the algorithm checks. - The larger parameter values yield more accurate results at the expense of lower processing speed. - - \code - KDTree T(points, false); - const int K = 3, Emax = INT_MAX; - int idx[K]; - float dist[K]; - T.findNearest(query_vec, K, Emax, idx, 0, dist); - CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]); - \endcode -*/ -class CV_EXPORTS_W KDTree -{ -public: - /*! - The node of the search tree. - */ - struct Node - { - Node() : idx(-1), left(-1), right(-1), boundary(0.f) {} - Node(int _idx, int _left, int _right, float _boundary) - : idx(_idx), left(_left), right(_right), boundary(_boundary) {} - //! split dimension; >=0 for nodes (dim), < 0 for leaves (index of the point) - int idx; - //! node indices of the left and the right branches - int left, right; - //! go to the left if query_vec[node.idx]<=node.boundary, otherwise go to the right - float boundary; - }; - - //! the default constructor - CV_WRAP KDTree(); - //! the full constructor that builds the search tree - CV_WRAP KDTree(InputArray points, bool copyAndReorderPoints=false); - //! the full constructor that builds the search tree - CV_WRAP KDTree(InputArray points, InputArray _labels, - bool copyAndReorderPoints=false); - //! builds the search tree - CV_WRAP void build(InputArray points, bool copyAndReorderPoints=false); - //! builds the search tree - CV_WRAP void build(InputArray points, InputArray labels, - bool copyAndReorderPoints=false); - //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves - CV_WRAP int findNearest(InputArray vec, int K, int Emax, - OutputArray neighborsIdx, - OutputArray neighbors=noArray(), - OutputArray dist=noArray(), - OutputArray labels=noArray()) const; - //! finds all the points from the initial set that belong to the specified box - CV_WRAP void findOrthoRange(InputArray minBounds, - InputArray maxBounds, - OutputArray neighborsIdx, - OutputArray neighbors=noArray(), - OutputArray labels=noArray()) const; - //! returns vectors with the specified indices - CV_WRAP void getPoints(InputArray idx, OutputArray pts, - OutputArray labels=noArray()) const; - //! return a vector with the specified index - const float* getPoint(int ptidx, int* label=0) const; - //! returns the search space dimensionality - CV_WRAP int dims() const; - - vector nodes; //!< all the tree nodes - CV_PROP Mat points; //!< all the points. It can be a reordered copy of the input vector set or the original vector set. - CV_PROP vector labels; //!< the parallel array of labels. - CV_PROP int maxDepth; //!< maximum depth of the search tree. Do not modify it - CV_PROP_RW int normType; //!< type of the distance (cv::NORM_L1 or cv::NORM_L2) used for search. Initially set to cv::NORM_L2, but you can modify it -}; - -//////////////////////////////////////// XML & YAML I/O //////////////////////////////////// - -class CV_EXPORTS FileNode; - -/*! - XML/YAML File Storage Class. - - The class describes an object associated with XML or YAML file. - It can be used to store data to such a file or read and decode the data. - - The storage is organized as a tree of nested sequences (or lists) and mappings. - Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator. - Mapping is analogue of std::map or C structure, which elements are accessed by names. - The most top level structure is a mapping. - Leaves of the file storage tree are integers, floating-point numbers and text strings. - - For example, the following code: - - \code - // open file storage for writing. Type of the file is determined from the extension - FileStorage fs("test.yml", FileStorage::WRITE); - fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH"; - fs << "test_mat" << Mat::eye(3,3,CV_32F); - - fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" << - "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]"; - fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:"; - - const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1}; - fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0]))); - - fs << "]" << "}"; - \endcode - - will produce the following file: - - \verbatim - %YAML:1.0 - test_int: 5 - test_real: 3.1000000000000001e+00 - test_string: ABCDEFGH - test_mat: !!opencv-matrix - rows: 3 - cols: 3 - dt: f - data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ] - test_list: - - 1.0000000000000000e-13 - - 2 - - 3.1415926535897931e+00 - - -3435345 - - "2-502 2-029 3egegeg" - - { month:12, day:31, year:1969 } - test_map: - x: 1 - y: 2 - width: 100 - height: 200 - lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ] - \endverbatim - - and to read the file above, the following code can be used: - - \code - // open file storage for reading. - // Type of the file is determined from the content, not the extension - FileStorage fs("test.yml", FileStorage::READ); - int test_int = (int)fs["test_int"]; - double test_real = (double)fs["test_real"]; - string test_string = (string)fs["test_string"]; - - Mat M; - fs["test_mat"] >> M; - - FileNode tl = fs["test_list"]; - CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6); - double tl0 = (double)tl[0]; - int tl1 = (int)tl[1]; - double tl2 = (double)tl[2]; - int tl3 = (int)tl[3]; - string tl4 = (string)tl[4]; - CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3); - - int month = (int)tl[5]["month"]; - int day = (int)tl[5]["day"]; - int year = (int)tl[5]["year"]; - - FileNode tm = fs["test_map"]; - - int x = (int)tm["x"]; - int y = (int)tm["y"]; - int width = (int)tm["width"]; - int height = (int)tm["height"]; - - int lbp_val = 0; - FileNodeIterator it = tm["lbp"].begin(); - - for(int k = 0; k < 8; k++, ++it) - lbp_val |= ((int)*it) << k; - \endcode -*/ -class CV_EXPORTS_W FileStorage -{ -public: - //! file storage mode - enum - { - READ=0, //! read mode - WRITE=1, //! write mode - APPEND=2, //! append mode - MEMORY=4, - FORMAT_MASK=(7<<3), - FORMAT_AUTO=0, - FORMAT_XML=(1<<3), - FORMAT_YAML=(2<<3) - }; - enum - { - UNDEFINED=0, - VALUE_EXPECTED=1, - NAME_EXPECTED=2, - INSIDE_MAP=4 - }; - //! the default constructor - CV_WRAP FileStorage(); - //! the full constructor that opens file storage for reading or writing - CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string()); - //! the constructor that takes pointer to the C FileStorage structure - FileStorage(CvFileStorage* fs); - //! the destructor. calls release() - virtual ~FileStorage(); - - //! opens file storage for reading or writing. The previous storage is closed with release() - CV_WRAP virtual bool open(const string& filename, int flags, const string& encoding=string()); - //! returns true if the object is associated with currently opened file. - CV_WRAP virtual bool isOpened() const; - //! closes the file and releases all the memory buffers - CV_WRAP virtual void release(); - //! closes the file, releases all the memory buffers and returns the text string - CV_WRAP string releaseAndGetString(); - - //! returns the first element of the top-level mapping - CV_WRAP FileNode getFirstTopLevelNode() const; - //! returns the top-level mapping. YAML supports multiple streams - CV_WRAP FileNode root(int streamidx=0) const; - //! returns the specified element of the top-level mapping - FileNode operator[](const string& nodename) const; - //! returns the specified element of the top-level mapping - CV_WRAP FileNode operator[](const char* nodename) const; - - //! returns pointer to the underlying C FileStorage structure - CvFileStorage* operator *() { return fs; } - //! returns pointer to the underlying C FileStorage structure - const CvFileStorage* operator *() const { return fs; } - //! writes one or more numbers of the specified format to the currently written structure - void writeRaw( const string& fmt, const uchar* vec, size_t len ); - //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite() - void writeObj( const string& name, const void* obj ); - - //! returns the normalized object name for the specified file name - static string getDefaultObjectName(const string& filename); - - Ptr fs; //!< the underlying C FileStorage structure - string elname; //!< the currently written element - vector structs; //!< the stack of written structures - int state; //!< the writer state -}; - -class CV_EXPORTS FileNodeIterator; - -/*! - File Storage Node class - - The node is used to store each and every element of the file storage opened for reading - - from the primitive objects, such as numbers and text strings, to the complex nodes: - sequences, mappings and the registered objects. - - Note that file nodes are only used for navigating file storages opened for reading. - When a file storage is opened for writing, no data is stored in memory after it is written. -*/ -class CV_EXPORTS_W_SIMPLE FileNode -{ -public: - //! type of the file storage node - enum - { - NONE=0, //!< empty node - INT=1, //!< an integer - REAL=2, //!< floating-point number - FLOAT=REAL, //!< synonym or REAL - STR=3, //!< text string in UTF-8 encoding - STRING=STR, //!< synonym for STR - REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others - SEQ=5, //!< sequence - MAP=6, //!< mapping - TYPE_MASK=7, - FLOW=8, //!< compact representation of a sequence or mapping. Used only by YAML writer - USER=16, //!< a registered object (e.g. a matrix) - EMPTY=32, //!< empty structure (sequence or mapping) - NAMED=64 //!< the node has a name (i.e. it is element of a mapping) - }; - //! the default constructor - CV_WRAP FileNode(); - //! the full constructor wrapping CvFileNode structure. - FileNode(const CvFileStorage* fs, const CvFileNode* node); - //! the copy constructor - FileNode(const FileNode& node); - //! returns element of a mapping node - FileNode operator[](const string& nodename) const; - //! returns element of a mapping node - CV_WRAP FileNode operator[](const char* nodename) const; - //! returns element of a sequence node - CV_WRAP FileNode operator[](int i) const; - //! returns type of the node - CV_WRAP int type() const; - - //! returns true if the node is empty - CV_WRAP bool empty() const; - //! returns true if the node is a "none" object - CV_WRAP bool isNone() const; - //! returns true if the node is a sequence - CV_WRAP bool isSeq() const; - //! returns true if the node is a mapping - CV_WRAP bool isMap() const; - //! returns true if the node is an integer - CV_WRAP bool isInt() const; - //! returns true if the node is a floating-point number - CV_WRAP bool isReal() const; - //! returns true if the node is a text string - CV_WRAP bool isString() const; - //! returns true if the node has a name - CV_WRAP bool isNamed() const; - //! returns the node name or an empty string if the node is nameless - CV_WRAP string name() const; - //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. - CV_WRAP size_t size() const; - //! returns the node content as an integer. If the node stores floating-point number, it is rounded. - operator int() const; - //! returns the node content as float - operator float() const; - //! returns the node content as double - operator double() const; - //! returns the node content as text string - operator string() const; - - //! returns pointer to the underlying file node - CvFileNode* operator *(); - //! returns pointer to the underlying file node - const CvFileNode* operator* () const; - - //! returns iterator pointing to the first node element - FileNodeIterator begin() const; - //! returns iterator pointing to the element following the last node element - FileNodeIterator end() const; - - //! reads node elements to the buffer with the specified format - void readRaw( const string& fmt, uchar* vec, size_t len ) const; - //! reads the registered object and returns pointer to it - void* readObj() const; - - // do not use wrapper pointer classes for better efficiency - const CvFileStorage* fs; - const CvFileNode* node; -}; - - -/*! - File Node Iterator - - The class is used for iterating sequences (usually) and mappings. - */ -class CV_EXPORTS FileNodeIterator -{ -public: - //! the default constructor - FileNodeIterator(); - //! the full constructor set to the ofs-th element of the node - FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0); - //! the copy constructor - FileNodeIterator(const FileNodeIterator& it); - //! returns the currently observed element - FileNode operator *() const; - //! accesses the currently observed element methods - FileNode operator ->() const; - - //! moves iterator to the next node - FileNodeIterator& operator ++ (); - //! moves iterator to the next node - FileNodeIterator operator ++ (int); - //! moves iterator to the previous node - FileNodeIterator& operator -- (); - //! moves iterator to the previous node - FileNodeIterator operator -- (int); - //! moves iterator forward by the specified offset (possibly negative) - FileNodeIterator& operator += (int ofs); - //! moves iterator backward by the specified offset (possibly negative) - FileNodeIterator& operator -= (int ofs); - - //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format - FileNodeIterator& readRaw( const string& fmt, uchar* vec, - size_t maxCount=(size_t)INT_MAX ); - - const CvFileStorage* fs; - const CvFileNode* container; - CvSeqReader reader; - size_t remaining; -}; - -////////////// 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(vector<_Tp>& vec, const Range& range=Range::all()) const; - //! returns the vector containing all the sequence elements - operator 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; -}; - - -class CV_EXPORTS Algorithm; -class CV_EXPORTS AlgorithmInfo; -struct CV_EXPORTS AlgorithmInfoData; - -template struct ParamType {}; - -/*! - Base class for high-level OpenCV algorithms -*/ -class CV_EXPORTS_W Algorithm -{ -public: - Algorithm(); - virtual ~Algorithm(); - string name() const; - - template typename ParamType<_Tp>::member_type get(const string& name) const; - template typename ParamType<_Tp>::member_type get(const char* name) const; - - CV_WRAP int getInt(const string& name) const; - CV_WRAP double getDouble(const string& name) const; - CV_WRAP bool getBool(const string& name) const; - CV_WRAP string getString(const string& name) const; - CV_WRAP Mat getMat(const string& name) const; - CV_WRAP vector getMatVector(const string& name) const; - CV_WRAP Ptr getAlgorithm(const string& name) const; - - void set(const string& name, int value); - void set(const string& name, double value); - void set(const string& name, bool value); - void set(const string& name, const string& value); - void set(const string& name, const Mat& value); - void set(const string& name, const vector& value); - void set(const string& name, const Ptr& value); - template void set(const string& name, const Ptr<_Tp>& value); - - CV_WRAP void setInt(const string& name, int value); - CV_WRAP void setDouble(const string& name, double value); - CV_WRAP void setBool(const string& name, bool value); - CV_WRAP void setString(const string& name, const string& value); - CV_WRAP void setMat(const string& name, const Mat& value); - CV_WRAP void setMatVector(const string& name, const vector& value); - CV_WRAP void setAlgorithm(const string& name, const Ptr& value); - template void setAlgorithm(const string& name, const Ptr<_Tp>& value); - - void set(const char* name, int value); - void set(const char* name, double value); - void set(const char* name, bool value); - void set(const char* name, const string& value); - void set(const char* name, const Mat& value); - void set(const char* name, const vector& value); - void set(const char* name, const Ptr& value); - template void set(const char* name, const Ptr<_Tp>& value); - - void setInt(const char* name, int value); - void setDouble(const char* name, double value); - void setBool(const char* name, bool value); - void setString(const char* name, const string& value); - void setMat(const char* name, const Mat& value); - void setMatVector(const char* name, const vector& value); - void setAlgorithm(const char* name, const Ptr& value); - template void setAlgorithm(const char* name, const Ptr<_Tp>& value); - - CV_WRAP string paramHelp(const string& name) const; - int paramType(const char* name) const; - CV_WRAP int paramType(const string& name) const; - CV_WRAP void getParams(CV_OUT vector& names) const; - - - virtual void write(FileStorage& fs) const; - virtual void read(const FileNode& fn); - - typedef Algorithm* (*Constructor)(void); - typedef int (Algorithm::*Getter)() const; - typedef void (Algorithm::*Setter)(int); - - CV_WRAP static void getList(CV_OUT vector& algorithms); - CV_WRAP static Ptr _create(const string& name); - template static Ptr<_Tp> create(const string& name); - - virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; } -}; - - -class CV_EXPORTS AlgorithmInfo -{ -public: - friend class Algorithm; - AlgorithmInfo(const string& name, Algorithm::Constructor create); - ~AlgorithmInfo(); - void get(const Algorithm* algo, const char* name, int argType, void* value) const; - void addParam_(Algorithm& algo, const char* name, int argType, - void* value, bool readOnly, - Algorithm::Getter getter, Algorithm::Setter setter, - const string& help=string()); - string paramHelp(const char* name) const; - int paramType(const char* name) const; - void getParams(vector& names) const; - - void write(const Algorithm* algo, FileStorage& fs) const; - void read(Algorithm* algo, const FileNode& fn) const; - string name() const; - - void addParam(Algorithm& algo, const char* name, - int& value, bool readOnly=false, - int (Algorithm::*getter)()=0, - void (Algorithm::*setter)(int)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - short& value, bool readOnly=false, - int (Algorithm::*getter)()=0, - void (Algorithm::*setter)(int)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - bool& value, bool readOnly=false, - int (Algorithm::*getter)()=0, - void (Algorithm::*setter)(int)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - double& value, bool readOnly=false, - double (Algorithm::*getter)()=0, - void (Algorithm::*setter)(double)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - string& value, bool readOnly=false, - string (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const string&)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - Mat& value, bool readOnly=false, - Mat (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const Mat&)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - vector& value, bool readOnly=false, - vector (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const vector&)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - Ptr& value, bool readOnly=false, - Ptr (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const Ptr&)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - float& value, bool readOnly=false, - float (Algorithm::*getter)()=0, - void (Algorithm::*setter)(float)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - unsigned int& value, bool readOnly=false, - unsigned int (Algorithm::*getter)()=0, - void (Algorithm::*setter)(unsigned int)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - uint64& value, bool readOnly=false, - uint64 (Algorithm::*getter)()=0, - void (Algorithm::*setter)(uint64)=0, - const string& help=string()); - void addParam(Algorithm& algo, const char* name, - uchar& value, bool readOnly=false, - uchar (Algorithm::*getter)()=0, - void (Algorithm::*setter)(uchar)=0, - const string& help=string()); - template void addParam(Algorithm& algo, const char* name, - Ptr<_Tp>& value, bool readOnly=false, - Ptr<_Tp> (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const Ptr<_Tp>&)=0, - const string& help=string()); - template void addParam(Algorithm& algo, const char* name, - Ptr<_Tp>& value, bool readOnly=false, - Ptr<_Tp> (Algorithm::*getter)()=0, - void (Algorithm::*setter)(const Ptr<_Tp>&)=0, - const string& help=string()); -protected: - AlgorithmInfoData* data; - void set(Algorithm* algo, const char* name, int argType, - const void* value, bool force=false) const; -}; - - -struct CV_EXPORTS Param -{ - enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, UNSIGNED_INT=8, UINT64=9, SHORT=10, UCHAR=11 }; - - Param(); - Param(int _type, bool _readonly, int _offset, - Algorithm::Getter _getter=0, - Algorithm::Setter _setter=0, - const string& _help=string()); - int type; - int offset; - bool readonly; - Algorithm::Getter getter; - Algorithm::Setter setter; - string help; -}; - -template<> struct ParamType -{ - typedef bool const_param_type; - typedef bool member_type; - - enum { type = Param::BOOLEAN }; -}; - -template<> struct ParamType -{ - typedef int const_param_type; - typedef int member_type; - - enum { type = Param::INT }; -}; - -template<> struct ParamType -{ - typedef int const_param_type; - typedef int member_type; - - enum { type = Param::SHORT }; -}; - -template<> struct ParamType -{ - typedef double const_param_type; - typedef double member_type; - - enum { type = Param::REAL }; -}; - -template<> struct ParamType -{ - typedef const string& const_param_type; - typedef string member_type; - - enum { type = Param::STRING }; -}; - -template<> struct ParamType -{ - typedef const Mat& const_param_type; - typedef Mat member_type; - - enum { type = Param::MAT }; -}; - -template<> struct ParamType > -{ - typedef const vector& const_param_type; - typedef vector member_type; - - enum { type = Param::MAT_VECTOR }; -}; - -template<> struct ParamType -{ - typedef const Ptr& const_param_type; - typedef Ptr member_type; - - enum { type = Param::ALGORITHM }; -}; - -template<> struct ParamType -{ - typedef float const_param_type; - typedef float member_type; - - enum { type = Param::FLOAT }; -}; - -template<> struct ParamType -{ - typedef unsigned const_param_type; - typedef unsigned member_type; - - enum { type = Param::UNSIGNED_INT }; -}; - -template<> struct ParamType -{ - typedef uint64 const_param_type; - typedef uint64 member_type; - - enum { type = Param::UINT64 }; -}; - -template<> struct ParamType -{ - typedef uchar const_param_type; - typedef uchar member_type; - - enum { type = Param::UCHAR }; -}; - -/*! -"\nThe CommandLineParser class is designed for command line arguments parsing\n" - "Keys map: \n" - "Before you start to work with CommandLineParser you have to create a map for keys.\n" - " It will look like this\n" - " const char* keys =\n" - " {\n" - " { s| string| 123asd |string parameter}\n" - " { d| digit | 100 |digit parameter }\n" - " { c|noCamera|false |without camera }\n" - " { 1| |some text|help }\n" - " { 2| |333 |another help }\n" - " };\n" - "Usage syntax: \n" - " \"{\" - start of parameter string.\n" - " \"}\" - end of parameter string\n" - " \"|\" - separator between short name, full name, default value and help\n" - "Supported syntax: \n" - " --key1=arg1 \n" - " -key2=arg2 \n" - "Usage: \n" - " Imagine that the input parameters are next:\n" - " -s=string_value --digit=250 --noCamera lena.jpg 10000\n" - " CommandLineParser parser(argc, argv, keys) - create a parser object\n" - " parser.get(\"s\" or \"string\") will return you first parameter value\n" - " parser.get(\"s\", false or \"string\", false) will return you first parameter value\n" - " without spaces in end and begin\n" - " parser.get(\"d\" or \"digit\") will return you second parameter value.\n" - " It also works with 'unsigned int', 'double', and 'float' types>\n" - " parser.get(\"c\" or \"noCamera\") will return you true .\n" - " If you enter this key in commandline>\n" - " It return you false otherwise.\n" - " parser.get(\"1\") will return you the first argument without parameter (lena.jpg) \n" - " parser.get(\"2\") will return you the second argument without parameter (10000)\n" - " It also works with 'unsigned int', 'double', and 'float' types \n" -*/ -class CV_EXPORTS CommandLineParser -{ - public: - - //! the default constructor - CommandLineParser(int argc, const char* const argv[], const char* key_map); - - //! get parameter, you can choose: delete spaces in end and begin or not - template - _Tp get(const std::string& name, bool space_delete=true) - { - if (!has(name)) - { - return _Tp(); - } - std::string str = getString(name); - return analyzeValue<_Tp>(str, space_delete); - } - - //! print short name, full name, current value and help for all params - void printParams(); - - protected: - std::map > data; - std::string getString(const std::string& name); - - bool has(const std::string& keys); - - template - _Tp analyzeValue(const std::string& str, bool space_delete=false); - - template - static _Tp getData(const std::string& str) - { - _Tp res = _Tp(); - std::stringstream s1(str); - s1 >> res; - return res; - } - - template - _Tp fromStringNumber(const std::string& str);//the default conversion function for numbers - - }; - -template<> CV_EXPORTS -bool CommandLineParser::get(const std::string& name, bool space_delete); - -template<> CV_EXPORTS -std::string CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - -template<> CV_EXPORTS -int CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - -template<> CV_EXPORTS -unsigned int CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - -template<> CV_EXPORTS -uint64 CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - -template<> CV_EXPORTS -float CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - -template<> CV_EXPORTS -double CommandLineParser::analyzeValue(const std::string& str, bool space_delete); - - -/////////////////////////////// Parallel Primitives ////////////////////////////////// - -// a base body class -class CV_EXPORTS ParallelLoopBody -{ -public: - virtual ~ParallelLoopBody(); - virtual void operator() (const Range& range) const = 0; -}; - -CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); - -/////////////////////////// Synchronization Primitives /////////////////////////////// - -class CV_EXPORTS Mutex -{ -public: - Mutex(); - ~Mutex(); - Mutex(const Mutex& m); - Mutex& operator = (const Mutex& m); - - void lock(); - bool trylock(); - void unlock(); - - struct Impl; -protected: - Impl* impl; -}; - -class CV_EXPORTS AutoLock -{ -public: - AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); } - ~AutoLock() { mutex->unlock(); } -protected: - Mutex* mutex; -private: - AutoLock(const AutoLock&); - AutoLock& operator = (const AutoLock&); -}; - -class TLSDataContainer -{ -private: - int key_; -protected: - CV_EXPORTS TLSDataContainer(); - CV_EXPORTS ~TLSDataContainer(); // virtual is not required -public: - virtual void* createDataInstance() const = 0; - virtual void deleteDataInstance(void* data) const = 0; - - CV_EXPORTS void* getData() const; -}; - -template -class TLSData : protected TLSDataContainer -{ -public: - inline TLSData() {} - inline ~TLSData() {} - inline T* get() const { return (T*)getData(); } -private: - virtual void* createDataInstance() const { return new T; } - virtual void deleteDataInstance(void* data) const { delete (T*)data; } -}; - -} - -#endif // __cplusplus - -#include "opencv2/core/operations.hpp" -#include "opencv2/core/mat.hpp" - -#endif /*__OPENCV_CORE_HPP__*/ +#include "opencv2/core.hpp" diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/core_c.h b/HuaGoCorrect/pub/opencv/include/opencv2/core/core_c.h index b9f1090..e5fe516 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/core_c.h +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/core_c.h @@ -7,11 +7,12 @@ // copy or use the software. // // -// License Agreement +// 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, @@ -41,26 +42,44 @@ //M*/ -#ifndef __OPENCV_CORE_C_H__ -#define __OPENCV_CORE_C_H__ +#ifndef OPENCV_CORE_C_H +#define OPENCV_CORE_C_H #include "opencv2/core/types_c.h" +#ifdef __cplusplus +# ifdef _MSC_VER +/* disable warning C4190: '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++ construrtors for simpler interoperability with C++ API of the library +*/ +# pragma warning(disable:4190) +# elif defined __clang__ && __clang_major__ >= 3 +# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" +# endif +#endif + #ifdef __cplusplus extern "C" { #endif +/** @addtogroup core_c + @{ +*/ + /****************************************************************************************\ * Array allocation, deallocation, initialization and access to elements * \****************************************************************************************/ -/* wrapper. +/** `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 ); -/* wrapper. +/** `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. @@ -69,61 +88,213 @@ CVAPI(void*) cvAlloc( size_t size ); CVAPI(void) cvFree_( void* ptr ); #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) -/* Allocates and initializes IplImage header */ +/** @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 ); -/* Inializes IplImage header */ +/** @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)); -/* Creates IPL image (header and data) */ +/** @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 ); -/* Releases (i.e. deallocates) IPL image header */ +/** @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 ); -/* Releases IPL image header and data */ +/** @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) */ +/** Creates a copy of IPL image (widthStep may differ) */ CVAPI(IplImage*) cvCloneImage( const IplImage* image ); -/* Sets a Channel Of Interest (only a few functions support COI) - - use cvCopy to extract the selected channel and/or put it back */ +/** @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 ); -/* Retrieves image Channel Of Interest */ +/** @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 ); -/* Sets image ROI (region of interest) (COI is not changed) */ +/** @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 ); -/* Resets image ROI and COI */ +/** @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 ); -/* Retrieves image ROI */ +/** @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 ); -/* Allocates and initializes CvMat header */ +/** @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 ); #define CV_AUTOSTEP 0x7fffffff -/* Initializes CvMat header */ +/** @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) ); -/* Allocates and initializes CvMat header and allocates data */ +/** @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 ); -/* Releases CvMat header and deallocates matrix data - (reference counting is used for data) */ +/** @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 ); -/* Decrements CvMat data reference counter and deallocates the data if - it reaches 0 */ +/** @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 )) @@ -144,7 +315,12 @@ CV_INLINE void cvDecRefData( CvArr* arr ) } } -/* Increments CvMat data reference counter */ +/** @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; @@ -164,84 +340,205 @@ CV_INLINE int cvIncRefData( CvArr* arr ) } -/* Creates an exact copy of the input matrix (except, may be, step value) */ +/** Creates an exact copy of the input matrix (except, may be, step value) */ CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); -/* Makes a new matrix from subrectangle of input array. - No data is copied */ +/** @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 -/* Selects row span of the input array: arr(start_row:delta_row:end_row,:) - (end_row is not included into the span). */ +/** @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 ); } -/* Selects column span of the input array: arr(:,start_col:end_col) - (end_col is not included into the span) */ +/** @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 ); } -/* Select a diagonal of the input array. - (diag = 0 means the main diagonal, >0 means a diagonal above the main one, - <0 - below the main one). - The diagonal will be represented as a column (nx1 matrix). */ +/** @brief Returns one of array diagonals. + +The function returns the header, corresponding to a specified diagonal of the input array. +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 +corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so +forth. + */ CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, int diag CV_DEFAULT(0)); -/* low-level scalar <-> raw data conversion functions */ +/** 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 ); -/* Allocates and initializes CvMatND header */ +/** @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 ); -/* Allocates and initializes CvMatND header and allocates data */ +/** @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 ); -/* Initializes preallocated CvMatND header */ +/** @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) ); -/* Releases CvMatND */ +/** @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) */ +/** Creates a copy of CvMatND (except, may be, steps) */ CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); -/* Allocates and initializes CvSparseMat header and allocates data */ +/** @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 ); -/* Releases CvSparseMat */ +/** @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) */ +/** Creates a copy of CvSparseMat (except, may be, zero items) */ CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); -/* Initializes sparse array iterator - (returns the first node or NULL if the array is empty) */ +/** @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 ); -// returns next sparse array node (or NULL if there is no more nodes) +/** @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 ) @@ -262,18 +559,18 @@ CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) } } -/**************** matrix iterator: used for n-ary operations on dense arrays *********/ #define CV_MAX_ARR 10 +/** matrix iterator: used for n-ary operations on dense arrays */ typedef struct CvNArrayIterator { - int count; /* number of arrays */ - int dims; /* number of dimensions to iterate */ - CvSize size; /* maximal common linear size: { width = size, height = 1 } */ - uchar* ptr[CV_MAX_ARR]; /* pointers to the array slices */ - int stack[CV_MAX_DIM]; /* for internal use */ - CvMatND* hdr[CV_MAX_ARR]; /* pointers to the headers of the + int count; /**< number of arrays */ + int dims; /**< number of dimensions to iterate */ + CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ + uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ + int stack[CV_MAX_DIM]; /**< for internal use */ + CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the matrices that are processed */ } CvNArrayIterator; @@ -282,7 +579,7 @@ CvNArrayIterator; #define CV_NO_CN_CHECK 2 #define CV_NO_SIZE_CHECK 4 -/* initializes iterator that traverses through several arrays simulteneously +/** initializes iterator that traverses through several arrays simulteneously (the function together with cvNextArraySlice is used for N-ari element-wise operations) */ CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, @@ -290,92 +587,248 @@ CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, CvNArrayIterator* array_iterator, int flags CV_DEFAULT(0) ); -/* returns zero value if iteration is finished, non-zero (slice length) otherwise */ +/** returns zero value if iteration is finished, non-zero (slice length) otherwise */ CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); -/* Returns type of array elements: - CV_8UC1 ... CV_64FC4 ... */ +/** @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 ); -/* Retrieves number of an array dimensions and - optionally sizes of the dimensions */ +/** @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) ); -/* Retrieves size of a particular array dimension. - For 2d arrays cvGetDimSize(arr,0) returns number of rows (image height) - and cvGetDimSize(arr,1) returns number of columns (image width) */ +/** @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 ); -/* ptr = &arr(idx0,idx1,...). All indexes are zero-based, - the major dimensions go first (e.g. (y,x) for 2D, (z,y,x) for 3D */ +/** @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)); - -/* For CvMat or IplImage number of indices should be 2 - (row index (y) goes first, column index (x) goes next). - For CvMatND or CvSparseMat number of infices should match number of and - indices order should match the array dimension order. */ +/** @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)); -/* value = arr(idx0,idx1,...) */ +/** @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 ); -/* for 1-channel arrays */ +/** @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 ); -/* arr(idx0,idx1,...) = value */ +/** @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 ); -/* for 1-channel arrays */ +/** @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, +/** clears element of ND dense array, in case of sparse arrays it deletes the specified node */ CVAPI(void) cvClearND( CvArr* arr, const int* idx ); -/* Converts CvArr (IplImage or CvMat,...) to CvMat. - If the last parameter is non-zero, function can - convert multi(>2)-dimensional array to CvMat as long as - the last array's dimension is continous. The resultant - matrix will be have appropriate (a huge) number of rows */ +/** @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)); -/* Converts CvArr (IplImage or CvMat) to IplImage */ +/** @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 ); -/* Changes a shape of multi-dimensional array. - new_cn == 0 means that number of channels remains unchanged. - new_dims == 0 means that number and sizes of dimensions remain the same - (unless they need to be changed to set the new number of channels) - if new_dims == 1, there is no need to specify new dimension sizes - The resultant configuration should be achievable w/o data copying. - If the resultant array is sparse, CvSparseMat header should be passed - to the function else if the result is 1 or 2 dimensional, - CvMat header should be passed to the function - else CvMatND header should be passed */ +/** @brief Changes the shape of a multi-dimensional array without copying the data. + +The function is an advanced version of cvReshape that can work with multi-dimensional arrays as +well (though it can work with ordinary images and matrices) and change the number of dimensions. + +Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: +@code + IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); + IplImage gray_img_hdr, *gray_img; + gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); + ... + int size[] = { 2, 2, 2 }; + CvMatND* mat = cvCreateMatND(3, size, CV_32F); + CvMat row_header, *row; + row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); +@endcode +In C, the header file for this function includes a convenient macro cvReshapeND that does away with +the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples +may be replaced as follow: +@code + gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); + ... + row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); +@endcode +@param arr Input array +@param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND +output headers +@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_dims New number of dimensions. new_dims = 0 means that the number of dimensions +remains the same. +@param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the +total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not +used. + */ CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, int sizeof_header, CvArr* header, int new_cn, int new_dims, int* new_sizes ); @@ -384,70 +837,184 @@ CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, 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) ); -/* Repeats source 2d array several times in both horizontal and +/** Repeats source 2d array several times in both horizontal and vertical direction to fill destination array */ CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); -/* Allocates array data */ +/** @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 ); -/* Releases array data */ +/** @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 ); -/* Attaches user data to the array header. The step is reffered to - the pre-last dimension. That is, all the planes of the array - must be joint (w/o gaps) */ +/** @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 ); -/* Retrieves raw data of CvMat, IplImage or CvMatND. - In the latter case the function raises an error if - the array can not be represented as a matrix */ +/** @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)); -/* Returns width and height of array in elements */ +/** @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 ); -/* Copies source array to destination array */ +/** @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) ); -/* Sets all or "masked" elements of input array - to the same value*/ +/** @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) ); -/* Clears all the array elements (sets them to 0) */ +/** @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 +/** 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 +/** 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 +/** 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 ); -/* Performs linear transformation on every source array element: - dst(x,y,c) = scale*src(x,y,c)+shift. - Arbitrary combination of input and output array depths are allowed - (number of channels must be the same), thus the function can be used - for type conversion */ +/** @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) ); @@ -456,7 +1023,7 @@ CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) -/* Performs linear transformation on every source array element, +/** 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. @@ -467,7 +1034,7 @@ CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, #define cvCvtScaleAbs cvConvertScaleAbs -/* checks termination criteria validity and +/** 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) */ @@ -479,19 +1046,19 @@ CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, * Arithmetic, logic and comparison operations * \****************************************************************************************/ -/* dst(mask) = src1(mask) + src2(mask) */ +/** 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 */ +/** 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) */ +/** 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) */ +/** 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)) { @@ -499,66 +1066,77 @@ CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, dst, mask ); } -/* dst(mask) = value - src(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 +/** 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: +/** 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 */ +/** dst = src1 * scale + src2 */ CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst ); #define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) -/* dst = src1 * alpha + src2 * beta + gamma */ +/** dst = src1 * alpha + src2 * beta + gamma */ CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst ); -/* result = sum_i(src1(i) * src2(i)) (results for all channels are accumulated together) */ +/** @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) */ +/** 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 */ +/** 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) */ +/** 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 */ +/** 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) */ +/** 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 */ +/** 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) */ +/** dst(idx) = ~src(idx) */ CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); -/* dst(idx) = lower(idx) <= src(idx) < upper(idx) */ +/** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst ); -/* dst(idx) = lower <= src(idx) < upper */ +/** dst(idx) = lower <= src(idx) < upper */ CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst ); @@ -569,31 +1147,31 @@ CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, #define CV_CMP_LE 4 #define CV_CMP_NE 5 -/* The comparison operation support single-channel arrays only. +/** The comparison operation support single-channel arrays only. Destination image should be 8uC1 or 8sC1 */ -/* dst(idx) = src1(idx) _cmp_op_ src2(idx) */ +/** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); -/* dst(idx) = src1(idx) _cmp_op_ value */ +/** dst(idx) = src1(idx) _cmp_op_ value */ CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); -/* dst(idx) = min(src1(idx),src2(idx)) */ +/** dst(idx) = min(src1(idx),src2(idx)) */ CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); -/* dst(idx) = max(src1(idx),src2(idx)) */ +/** dst(idx) = max(src1(idx),src2(idx)) */ CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); -/* dst(idx) = min(src(idx),value) */ +/** dst(idx) = min(src(idx),value) */ CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); -/* dst(idx) = max(src(idx),value) */ +/** dst(idx) = max(src(idx),value) */ CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); -/* dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ +/** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); -/* dst(x,y,c) = abs(src(x,y,c) - value(c)) */ +/** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); #define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) @@ -601,51 +1179,68 @@ CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); * Math operations * \****************************************************************************************/ -/* Does cartesian->polar coordinates conversion. +/** Does cartesian->polar coordinates conversion. Either of output components (magnitude or angle) is optional */ CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), int angle_in_degrees CV_DEFAULT(0)); -/* Does polar->cartesian coordinates conversion. +/** Does polar->cartesian coordinates conversion. Either of output components (magnitude or angle) is optional. If magnitude is missing it is assumed to be all 1's */ CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angle_in_degrees CV_DEFAULT(0)); -/* Does powering: dst(idx) = src(idx)^power */ +/** Does powering: dst(idx) = src(idx)^power */ CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); -/* Does exponention: dst(idx) = exp(src(idx)). +/** 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 ); -/* Calculates natural logarithms: dst(idx) = log(abs(src(idx))). +/** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). Logarithm of 0 gives large negative number(~-700) Maximal relative error is ~3e-7 for single-precision output */ CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); -/* Fast arctangent calculation */ +/** Fast arctangent calculation */ CVAPI(float) cvFastArctan( float y, float x ); -/* Fast cubic root calculation */ +/** Fast cubic root calculation */ CVAPI(float) cvCbrt( float value ); -/* Checks array values for NaNs, Infs or simply for too large numbers +#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). Otherwise cvError is called */ -#define CV_CHECK_RANGE 1 -#define CV_CHECK_QUIET 2 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 + +/** @brief Fills an array with random numbers and updates the RNG state. + +The function fills the destination array with uniformly or normally distributed random numbers. +@param rng CvRNG state initialized by cvRNG +@param arr The destination array +@param dist_type Distribution type +> - **CV_RAND_UNI** uniform distribution +> - **CV_RAND_NORMAL** normal or Gaussian distribution +@param param1 The first parameter of the distribution. In the case of a uniform distribution it is +the inclusive lower boundary of the random numbers range. In the case of a normal distribution it +is the mean value of the random numbers. +@param param2 The second parameter of the distribution. In the case of a uniform distribution it +is the exclusive upper boundary of the random numbers range. In the case of a normal distribution +it is the standard deviation of the random numbers. +@sa randu, randn, RNG::fill. + */ CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, CvScalar param1, CvScalar param2 ); @@ -661,10 +1256,10 @@ CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), CvArr* idxmat CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); -/* Finds real roots of a cubic equation */ +/** Finds real roots of a cubic equation */ CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); -/* Finds all real and complex roots of a polynomial equation */ +/** 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)); @@ -672,47 +1267,56 @@ CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, * Matrix operations * \****************************************************************************************/ -/* Calculates cross product of two 3d vectors */ +/** @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 */ +/** 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: +/** 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 +/** 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 */ +/** 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) */ +/** 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.) ); -/* Tranposes matrix. Square matrices can be transposed in-place */ +/** Tranposes 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 */ +/** 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), +/** 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), @@ -724,11 +1328,11 @@ CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), #define CV_SVD_U_T 2 #define CV_SVD_V_T 4 -/* Performs Singular Value Decomposition of a matrix */ +/** 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): +/** 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, @@ -741,23 +1345,23 @@ CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, #define CV_QR 4 #define CV_NORMAL 16 -/* Inverts matrix */ +/** 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) +/** 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 */ +/** Calculates determinant of input matrix */ CVAPI(double) cvDet( const CvArr* mat ); -/* Calculates trace of the matrix (sum of elements on the main diagonal) */ +/** 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 */ +/** 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), @@ -767,32 +1371,42 @@ CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, //CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, // int lowindex, int highindex ); -/* Makes an identity matrix (mat_ij = i == j) */ +/** 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 */ +/** Fills matrix with given range of numbers */ CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); -/* Calculates covariation matrix for a set of vectors */ -/* transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ +/** @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 -/* [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ +/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ #define CV_COVAR_NORMAL 1 -/* do not calc average (i.e. mean vector) - use the input vector instead +/** 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 -/* scale the covariance matrix coefficients by number of the vectors */ +/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ #define CV_COVAR_SCALE 4 -/* all the input vectors are stored in a single matrix, as its rows */ +/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ #define CV_COVAR_ROWS 8 -/* all the input vectors are stored in a single matrix, as its columns */ +/** 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 ); @@ -808,7 +1422,7 @@ CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, const CvArr* eigenvects, CvArr* result ); -/* Calculates Mahalanobis(weighted) distance */ +/** Calculates Mahalanobis(weighted) distance */ CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); #define cvMahalonobis cvMahalanobis @@ -816,26 +1430,29 @@ CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* * Array Statistics * \****************************************************************************************/ -/* Finds sum of array elements */ +/** Finds sum of array elements */ CVAPI(CvScalar) cvSum( const CvArr* arr ); -/* Calculates number of non-zero pixels */ +/** Calculates number of non-zero pixels */ CVAPI(int) cvCountNonZero( const CvArr* arr ); -/* Calculates mean value of array elements */ +/** 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 */ +/** 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 */ +/** 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) ); -/* types of array norm */ +/** @anchor core_c_NormFlags + @name Flags for cvNorm and cvNormalize + @{ +*/ #define CV_C 1 #define CV_L1 2 #define CV_L2 4 @@ -850,23 +1467,32 @@ CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, #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) */ +/** 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) ); @@ -874,182 +1500,193 @@ CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), * 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_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 */ +#define CV_DXT_ROWS 4 /**< transform each row individually */ +#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ +/** @} */ -/* Discrete Fourier Transform: +/** Discrete Fourier Transform: complex->complex, real->ccs (forward), - ccs->real (inverse) */ + 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)) */ +/** 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 */ +/** Finds optimal DFT vector size >= size0 */ CVAPI(int) cvGetOptimalDFTSize( int size0 ); -/* Discrete Cosine Transform */ +/** 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). */ +/** Calculates length of sequence slice (with support of negative indices). */ CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); -/* Creates new memory storage. +/** 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 */ +/** 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 +/** 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) +/** 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 */ +/** Remember a storage "free memory" position */ CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); -/* Restore a storage "free memory" position */ +/** Restore a storage "free memory" position */ CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); -/* Allocates continuous buffer of the specified size in the storage */ +/** Allocates continuous buffer of the specified size in the storage */ CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); -/* Allocates string in memory storage */ +/** 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 */ +/** 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. +/** 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 */ +/** 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 */ +/** 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 */ +/** 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 */ +/** 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 */ +/** 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 */ +/** 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. +/** 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 */ +/** Removes specified sequence element */ CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); -/* Removes all the elements from the sequence. The freed memory +/** 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. +/** 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. +/** 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 */ +/** 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 */ +/** 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 +/** 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 +/** 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. +/** 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) */ +/** 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 +/** 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 */ +/** 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. +/** 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) */ +/** 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)); @@ -1059,27 +1696,27 @@ CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT( return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); } -/* Removes sequence slice */ +/** Removes sequence slice */ CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); -/* Inserts a sequence or array into another sequence */ +/** 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 */ +/** 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 */ +/** 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 */ +/** 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 */ +/** Reverses order of sequence elements in-place */ CVAPI(void) cvSeqInvert( CvSeq* seq ); -/* Splits sequence into one or more equivalence classes using the specified criteria */ +/** 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 ); @@ -1088,15 +1725,15 @@ CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); -/* Creates a new set */ +/** 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 */ +/** 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 */ +/** Fast variant of cvSetAdd */ CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) { CvSetElem* elem = set_header->free_elems; @@ -1111,7 +1748,7 @@ CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) return elem; } -/* Removes set element given its pointer */ +/** Removes set element given its pointer */ CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) { CvSetElem* _elem = (CvSetElem*)elem; @@ -1122,10 +1759,10 @@ CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) set_header->active_count--; } -/* Removes element from the set by its index */ +/** 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, +/** 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 ) { @@ -1133,25 +1770,25 @@ CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; } -/* Removes all the elements from the set */ +/** Removes all the elements from the set */ CVAPI(void) cvClearSet( CvSet* set_header ); -/* Creates new graph */ +/** 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 */ +/** 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 */ +/** 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 specifed by indices or pointers if they +/** 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 */ @@ -1165,12 +1802,12 @@ CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, const CvGraphEdge* edge CV_DEFAULT(NULL), CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); -/* Remove edge connecting two vertices */ +/** 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 */ +/** 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, @@ -1178,22 +1815,22 @@ CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, #define cvGraphFindEdge cvFindGraphEdge #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr -/* Remove all vertices and edges from the graph */ +/** Remove all vertices and edges from the graph */ CVAPI(void) cvClearGraph( CvGraph* graph ); -/* Count number of edges incident to the vertex */ +/** 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 */ +/** Retrieves graph vertex by given index */ #define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) -/* Retrieves index of a graph vertex given its pointer */ +/** 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 */ +/** 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) @@ -1211,7 +1848,7 @@ CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ) #define CV_GRAPH_ALL_ITEMS -1 -/* flags for graph vertices and edges */ +/** 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) @@ -1233,208 +1870,22 @@ typedef struct CvGraphScanner } CvGraphScanner; -/* Creates new graph scanner. */ +/** 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. */ +/** Releases graph scanner. */ CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); -/* Get next graph element */ +/** Get next graph element */ CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); -/* Creates a copy of graph */ +/** Creates a copy of graph */ CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); -/****************************************************************************************\ -* Drawing * -\****************************************************************************************/ -/****************************************************************************************\ -* Drawing functions work with images/matrices of arbitrary type. * -* For color images the channel order is BGR[A] * -* Antialiasing is supported only for 8-bit image now. * -* All the functions include parameter color that means rgb value (that may be * -* constructed with CV_RGB macro) for color images and brightness * -* for grayscale images. * -* If a drawn figure is partially or completely outside of the image, it is clipped.* -\****************************************************************************************/ - -#define CV_RGB( r, g, b ) cvScalar( (b), (g), (r), 0 ) -#define CV_FILLED -1 - -#define CV_AA 16 - -/* Draws 4-connected, 8-connected or antialiased line segment connecting two points */ -CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/* Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2), - if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn */ -CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - -/* Draws a rectangle specified by a CvRect structure */ -CVAPI(void) cvRectangleR( CvArr* img, CvRect r, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - - -/* Draws a circle with specified center and radius. - Thickness works in the same way as with cvRectangle */ -CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/* Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector, - depending on , and parameters. The resultant figure - is rotated by . All the angles are in degrees */ -CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, - double angle, double start_angle, double end_angle, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) -{ - CvSize axes; - axes.width = cvRound(box.size.width*0.5); - axes.height = cvRound(box.size.height*0.5); - - cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, - 0, 360, color, thickness, line_type, shift ); -} - -/* Fills convex or monotonous polygon. */ -CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/* Fills an area bounded by one or more arbitrary polygons */ -CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, - int contours, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/* Draws one or more polygonal curves */ -CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, - int is_closed, CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -#define cvDrawRect cvRectangle -#define cvDrawLine cvLine -#define cvDrawCircle cvCircle -#define cvDrawEllipse cvEllipse -#define cvDrawPolyLine cvPolyLine - -/* Clips the line segment connecting *pt1 and *pt2 - by the rectangular window - (0<=xptr will point - to pt1 (or pt2, see left_to_right description) location in the image. - Returns the number of pixels on the line between the ending points. */ -CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, - CvLineIterator* line_iterator, - int connectivity CV_DEFAULT(8), - int left_to_right CV_DEFAULT(0)); - -/* Moves iterator to the next line point */ -#define CV_NEXT_LINE_POINT( line_iterator ) \ -{ \ - int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ - (line_iterator).err += (line_iterator).minus_delta + \ - ((line_iterator).plus_delta & _line_iterator_mask); \ - (line_iterator).ptr += (line_iterator).minus_step + \ - ((line_iterator).plus_step & _line_iterator_mask); \ -} - - -/* basic font types */ -#define CV_FONT_HERSHEY_SIMPLEX 0 -#define CV_FONT_HERSHEY_PLAIN 1 -#define CV_FONT_HERSHEY_DUPLEX 2 -#define CV_FONT_HERSHEY_COMPLEX 3 -#define CV_FONT_HERSHEY_TRIPLEX 4 -#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 -#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 -#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 - -/* font flags */ -#define CV_FONT_ITALIC 16 - -#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX - - -/* Font structure */ -typedef struct CvFont -{ - const char* nameFont; //Qt:nameFont - CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red\_component[, alpha_component]) - int font_face; //Qt: bool italic /* =CV_FONT_* */ - const int* ascii; /* font data and metrics */ - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; /* slope coefficient: 0 - normal, >0 - italic */ - int thickness; //Qt: weight /* letters thickness */ - float dx; /* horizontal interval between letters */ - int line_type; //Qt: PointSize -} -CvFont; - -/* Initializes font structure used further in cvPutText */ -CVAPI(void) cvInitFont( CvFont* font, int font_face, - double hscale, double vscale, - double shear CV_DEFAULT(0), - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8)); - -CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) -{ - CvFont font; - cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); - return font; -} - -/* Renders text stroke with specified font and color at specified location. - CvFont should be initialized with cvInitFont */ -CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, - const CvFont* font, CvScalar color ); - -/* Calculates bounding box of text stroke (useful for alignment) */ -CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, - CvSize* text_size, int* baseline ); - - - -/* Unpacks color value, if arrtype is CV_8UC?, is treated as - packed color value, otherwise the first channels (depending on arrtype) - of destination scalar are set to the same value = */ -CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); - -/* Returns the polygon points which make up the given ellipse. The ellipse is define by - the box of size 'axes' rotated 'angle' around the 'center'. A partial sweep - of the ellipse arc can be done by spcifying arc_start and arc_end to be something - other than 0 and 360, respectively. The input array 'pts' must be large enough to - hold the result. The total number of points stored into 'pts' is returned by this - function. */ -CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, - int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); - -/* Draws contour outlines or filled interiors on the image */ -CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, - CvScalar external_color, CvScalar hole_color, - int max_level, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - CvPoint offset CV_DEFAULT(cvPoint(0,0))); - -/* Does look-up transformation. Elements of the source array +/** 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 ); @@ -1453,20 +1904,20 @@ CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); -/* Inserts sequence into tree with specified "parent" sequence. +/** 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). */ +/** 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 , to the single sequence */ +/** 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 ); -/* The function implements the K-means algorithm for clustering an array of sample +/** The function implements the K-means algorithm for clustering an array of sample vectors in a specified number of classes */ #define CV_KMEANS_USE_INITIAL_LABELS 1 CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, @@ -1478,27 +1929,9 @@ CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, * System functions * \****************************************************************************************/ -/* Add the function pointers table with associated information to the IPP primitives list */ -CVAPI(int) cvRegisterModule( const CvModuleInfo* module_info ); - -/* Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ +/** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ CVAPI(int) cvUseOptimized( int on_off ); -/* Retrieves information about the registered modules and loaded optimized plugins */ -CVAPI(void) cvGetModuleInfo( const char* module_name, - const char** version, - const char** loaded_addon_plugins ); - -typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata); -typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata); - -/* Set user-defined memory managment functions (substitutors for malloc and free) that - will be called by cvAlloc, cvFree and higher-level functions (e.g. cvCreateImage) */ -CVAPI(void) cvSetMemoryManager( CvAllocFunc alloc_func CV_DEFAULT(NULL), - CvFreeFunc free_func CV_DEFAULT(NULL), - void* userdata CV_DEFAULT(NULL)); - - typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) (int,int,int,char*,char*,int,int,int,int,int, IplROI*,IplImage*,void*,IplTileInfo*); @@ -1507,7 +1940,22 @@ 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*); -/* Makes OpenCV use IPL functions for IplImage allocation/deallocation */ +/** @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, @@ -1524,72 +1972,370 @@ CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, /********************************** High-level functions ********************************/ -/* opens existing or creates new file storage */ +/** @brief Opens file storage for reading or writing data. + +The function opens file storage for reading or writing data. In the latter case, a new file is +created or an existing file is rewritten. The type of the read or written file is determined by the +filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. + +At the same time, it also supports adding parameters like "example.xml?base64". + +The function returns a pointer to the CvFileStorage structure. +If the file cannot be opened then the function returns NULL. +@param filename Name of the file associated with the storage +@param memstorage Memory storage used for temporary data and for +: storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory + storage is created and used. +@param flags Can be one of the following: +> - **CV_STORAGE_READ** the storage is open for reading +> - **CV_STORAGE_WRITE** the storage is open for writing + (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) +@param encoding + */ CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags, const char* encoding CV_DEFAULT(NULL) ); -/* closes file storage and deallocates buffers */ +/** @brief Releases file storage. + +The function closes the file associated with the storage and releases all the temporary structures. +It must be called after all I/O operations with the storage are finished. +@param fs Double pointer to the released file storage + */ CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); -/* returns attribute value or 0 (NULL) if there is no such attribute */ +/** returns attribute value or 0 (NULL) if there is no such attribute */ CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); -/* starts writing compound structure (map or sequence) */ +/** @brief Starts writing a new structure. + +The function starts writing a compound structure (collection) that can be a sequence or a map. After +all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should +be called. The function can be used to group some objects or to implement the write function for a +some user object (see CvTypeInfo). +@param fs File storage +@param name Name of the written structure. The structure can be accessed by this name when the +storage is read. +@param struct_flags A combination one of the following values: +- **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), + that is, its elements do not have a name. +- **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that + is, all its elements have names. +One and only one of the two above flags must be specified +- **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that + the structure is written as a flow (not as a block), which is more compact. It is + recommended to use this flag for structures or arrays whose elements are all scalars. +@param type_name Optional parameter - the object type name. In + case of XML it is written as a type_id attribute of the structure opening tag. In the case of + YAML it is written after a colon following the structure name (see the example in + CvFileStorage description). In case of JSON it is written as a name/value pair. + Mainly it is used with user objects. When the storage is read, the + encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). +@param attributes This parameter is not used in the current implementation + */ CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* type_name CV_DEFAULT(NULL), CvAttrList attributes CV_DEFAULT(cvAttrList())); -/* finishes writing compound structure */ +/** @brief Finishes writing to a file node collection. +@param fs File storage +@sa cvStartWriteStruct. + */ CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); -/* writes an integer */ +/** @brief Writes an integer value. + +The function writes a single integer value (with or without a name) to the file storage. +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value + */ CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); -/* writes a floating-point number */ +/** @brief Writes a floating-point value. + +The function writes a single floating-point value (with or without a name) to file storage. Special +values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. + +The following example shows how to use the low-level writing functions to store custom structures, +such as termination criteria, without registering a new type. : +@code + void write_termcriteria( CvFileStorage* fs, const char* struct_name, + CvTermCriteria* termcrit ) + { + cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); + cvWriteComment( fs, "termination criteria", 1 ); // just a description + if( termcrit->type & CV_TERMCRIT_ITER ) + cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); + if( termcrit->type & CV_TERMCRIT_EPS ) + cvWriteReal( fs, "accuracy", termcrit->epsilon ); + cvEndWriteStruct( fs ); + } +@endcode +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value +*/ CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); -/* writes a string */ +/** @brief Writes a text string. + +The function writes a text string to file storage. +@param fs File storage +@param name Name of the written string . Should be NULL if and only if the parent structure is a +sequence. +@param str The written text string +@param quote If non-zero, the written string is put in quotes, regardless of whether they are +required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when +the string starts with a digit or contains spaces). + */ CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote CV_DEFAULT(0) ); -/* writes a comment */ +/** @brief Writes a comment. + +The function writes a comment into file storage. The comments are skipped when the storage is read. +@param fs File storage +@param comment The written comment, single-line or multi-line +@param eol_comment If non-zero, the function tries to put the comment at the end of current line. +If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current +line, the comment starts a new line. + */ CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment ); -/* writes instance of a standard type (matrix, image, sequence, graph etc.) - or user-defined type */ +/** @brief Writes an object to file storage. + +The function writes an object to file storage. First, the appropriate type info is found using +cvTypeOf. Then, the write method associated with the type info is called. + +Attributes are used to customize the writing procedure. The standard types support the following +attributes (all the dt attributes have the same format as in cvWriteRawData): + +-# CvSeq + - **header_dt** description of user fields of the sequence header that follow CvSeq, or + CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or + point sequence) + - **dt** description of the sequence elements. + - **recursive** if the attribute is present and is not equal to "0" or "false", the whole + tree of sequences (contours) is stored. +-# CvGraph + - **header_dt** description of user fields of the graph header that follows CvGraph; + - **vertex_dt** description of user fields of graph vertices + - **edge_dt** description of user fields of graph edges (note that the edge weight is + always written, so there is no need to specify it explicitly) + +Below is the code that creates the YAML file shown in the CvFileStorage description: +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvMat* mat = cvCreateMat( 3, 3, CV_32F ); + CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); + + cvSetIdentity( mat ); + cvWrite( fs, "A", mat, cvAttrList(0,0) ); + + cvReleaseFileStorage( &fs ); + cvReleaseMat( &mat ); + return 0; + } +@endcode +@param fs File storage +@param name Name of the written object. Should be NULL if and only if the parent structure is a +sequence. +@param ptr Pointer to the object +@param attributes The attributes of the object. They are specific for each particular type (see +the discussion below). + */ CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes CV_DEFAULT(cvAttrList())); -/* starts the next stream */ +/** @brief Starts the next stream. + +The function finishes the currently written stream and starts the next stream. In the case of XML +the file with multiple streams looks like this: +@code{.xml} + + + + + + + ... +@endcode +The YAML file will look like this: +@code{.yaml} + %YAML 1.0 + # stream #1 data + ... + --- + # stream #2 data +@endcode +This is useful for concatenating files or for resuming the writing process. +@param fs File storage + */ CVAPI(void) cvStartNextStream( CvFileStorage* fs ); -/* helper function: writes multiple integer or floating-point numbers */ +/** @brief Writes multiple numbers. + +The function writes an array, whose elements consist of single or multiple numbers. The function +call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single +call is more efficient. Note that because none of the elements have a name, they should be written +to a sequence rather than a map. +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" + */ CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt ); -/* returns the hash entry corresponding to the specified literal key string or 0 - if there is no such a key in the storage */ +/** @brief Writes multiple numbers in Base64. + +If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, +this function will be the same as cvWriteRawData. If neither, the main +difference is that it outputs a sequence in Base64 encoding rather than +in plain text. + +This function can only be used to write a sequence with a type "binary". + +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" +*/ +CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, + int len, const char* dt ); + +/** @brief Returns a unique pointer for a given name. + +The function returns a unique pointer for each particular file node name. This pointer can be then +passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares +text strings by comparing pointers rather than the strings' content. + +Consider the following example where an array of points is encoded as a sequence of 2-entry maps: +@code + points: + - { x: 10, y: 10 } + - { x: 20, y: 20 } + - { x: 30, y: 30 } + # ... +@endcode +Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); + CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); + CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); + CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); + + if( CV_NODE_IS_SEQ(points->tag) ) + { + CvSeq* seq = points->data.seq; + int i, total = seq->total; + CvSeqReader reader; + cvStartReadSeq( seq, &reader, 0 ); + for( i = 0; i < total; i++ ) + { + CvFileNode* pt = (CvFileNode*)reader.ptr; + #if 1 // faster variant + CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); + CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #elif 1 // slower variant; does not use x_key & y_key + CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); + CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #else // the slowest yet the easiest to use variant + int x = cvReadIntByName( fs, pt, "x", 0 ); + int y = cvReadIntByName( fs, pt, "y", 0 ); + #endif + CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); + printf(" + } + } + cvReleaseFileStorage( &fs ); + return 0; + } +@endcode +Please note that whatever method of accessing a map you are using, it is still much slower than +using plain sequences; for example, in the above example, it is more efficient to encode the points +as pairs of integers in a single numeric sequence. +@param fs File storage +@param name Literal node name +@param len Length of the name (if it is known apriori), or -1 if it needs to be calculated +@param create_missing Flag that specifies, whether an absent key should be added into the hash table +*/ CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, int len CV_DEFAULT(-1), int create_missing CV_DEFAULT(0)); -/* returns file node with the specified key within the specified map - (collection of named nodes) */ +/** @brief Retrieves one of the top-level nodes of the file storage. + +The function returns one of the top-level file nodes. The top-level nodes do not have a name, they +correspond to the streams that are stored one after another in the file storage. If the index is out +of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by +subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. +This function can be used as a base for recursive traversal of the file storage. +@param fs File storage +@param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, +there is only one stream in the file; however, there can be several. + */ CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, int stream_index CV_DEFAULT(0) ); -/* returns file node with the specified key within the specified map - (collection of named nodes) */ +/** @brief Finds a node in a map or file storage. + +The function finds a file node. It is a faster version of cvGetFileNodeByName (see +cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. If both map and +key are NULLs, the function returns the root file node - a map that contains top-level nodes. +@param key Unique pointer to the node name, retrieved with cvGetHashedKey +@param create_missing Flag that specifies whether an absent node should be added to the map + */ CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int create_missing CV_DEFAULT(0) ); -/* this is a slower version of cvGetFileNode that takes the key as a literal string */ +/** @brief Finds a node in a map or file storage. + +The function finds a file node by name. The node is searched either in map or, if the pointer is +NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or +sequence reader) for sequences, it is possible to navigate through the file storage. To speed up +multiple queries for a certain key (e.g., in the case of an array of structures) one may use a +combination of cvGetHashedKey and cvGetFileNode. +@param fs File storage +@param map The parent map. If it is NULL, the function searches in all the top-level nodes +(streams), starting with the first one. +@param name The file node name + */ CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name ); +/** @brief Retrieves an integer value from a file node. + +The function returns an integer that is represented by the file node. If the file node is NULL, the +default_value is returned (thus, it is convenient to call the function right after cvGetFileNode +without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is +returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer +and returned. Otherwise the error is reported. +@param node File node +@param default_value The value that is returned if node is NULL + */ CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) { return !node ? default_value : @@ -1597,14 +2343,30 @@ CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; } +/** @brief Finds a file node and returns its value. +The function is a simple superposition of cvGetFileNodeByName and cvReadInt. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int default_value CV_DEFAULT(0) ) { return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); } +/** @brief Retrieves a floating-point value from a file node. +The function returns a floating-point value that is represented by the file node. If the file node +is NULL, the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , +then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f +is converted to floating-point and returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) { return !node ? default_value : @@ -1612,21 +2374,43 @@ CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEF CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; } +/** @brief Finds a file node and returns its value. +The function is a simple superposition of cvGetFileNodeByName and cvReadReal . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double default_value CV_DEFAULT(0.) ) { return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); } +/** @brief Retrieves a text string from a file node. +The function returns a text string that is represented by the file node. If the file node is NULL, +the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then +node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ CV_INLINE const char* cvReadString( const CvFileNode* node, const char* default_value CV_DEFAULT(NULL) ) { return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; } +/** @brief Finds a file node by its name and returns its value. +The function is a simple superposition of cvGetFileNodeByName and cvReadString . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* default_value CV_DEFAULT(NULL) ) { @@ -1634,11 +2418,31 @@ CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileN } -/* decodes standard or user-defined object and returns it */ +/** @brief Decodes an object and returns a pointer to it. + +The function decodes a user object (creates an object in a native representation from the file +storage subtree) and returns it. The object to be decoded must be an instance of a registered type +that supports the read method (see CvTypeInfo). The type of the object is determined by the type +name that is encoded in the file. If the object is a dynamic structure, it is created either in +memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary +memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is +not a dynamic structure, it is created in a heap and should be released with a specialized function +or by using the generic cvRelease. +@param fs File storage +@param node The root object node +@param attributes Unused parameter + */ CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes CV_DEFAULT(NULL)); -/* decodes standard or user-defined object and returns it */ +/** @brief Finds an object by name and decodes it. + +The function is a simple superposition of cvGetFileNodeByName and cvRead. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param attributes Unused parameter + */ CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) { @@ -1646,42 +2450,158 @@ CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, } -/* starts reading data from sequence or scalar numeric node */ +/** @brief Initializes the file node sequence reader. + +The function initializes the sequence reader to read data from a file node. The initialized reader +can be then passed to cvReadRawDataSlice. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param reader Pointer to the sequence reader + */ CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader ); -/* reads multiple numbers and stores them to array */ +/** @brief Initializes file node sequence reader. + +The function reads one or more elements from the file node, representing a sequence, to a +user-specified array. The total number of read sequence elements is a product of total and the +number of components in each array element. For example, if dt=2if, the function will read total\*3 +sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read +repeatedly by repositioning the reader using cvSetSeqReaderPos. +@param fs File storage +@param reader The sequence reader. Initialize it with cvStartReadRawData . +@param count The number of elements to read +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt ); -/* combination of two previous functions for easier reading of whole sequences */ +/** @brief Reads multiple numbers. + +The function reads elements from a file node that represents a sequence of scalars. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt ); -/* writes a copy of file node to file storage */ +/** @brief Writes a file node to another file storage. + +The function writes a copy of a file node to file storage. Possible applications of the function are +merging several file storages into one and conversion between XML, YAML and JSON formats. +@param fs Destination file storage +@param new_node_name New name of the file node in the destination file storage. To keep the +existing name, use cvcvGetFileNodeName +@param node The written node +@param embed If the written node is a collection and this parameter is not zero, no extra level of +hierarchy is created. Instead, all the elements of node are written into the currently written +structure. Of course, map elements can only be embedded into another map, and sequence elements +can only be embedded into another sequence. + */ CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed ); -/* returns name of file node */ +/** @brief Returns the name of a file node. + +The function returns the name of a file node or NULL, if the file node does not have a name or if +node is NULL. +@param node File node + */ CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); /*********************************** Adding own types ***********************************/ +/** @brief Registers a new type. + +The function registers a new type, which is described by info . The function creates a copy of the +structure, so the user should delete it after calling the function. +@param info Type info structure + */ CVAPI(void) cvRegisterType( const CvTypeInfo* info ); + +/** @brief Unregisters the type. + +The function unregisters a type with a specified name. If the name is unknown, it is possible to +locate the type info by an instance of the type using cvTypeOf or by iterating the type list, +starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). +@param type_name Name of an unregistered type + */ CVAPI(void) cvUnregisterType( const char* type_name ); + +/** @brief Returns the beginning of a type list. + +The function returns the first type in the list of registered types. Navigation through the list can +be done via the prev and next fields of the CvTypeInfo structure. + */ CVAPI(CvTypeInfo*) cvFirstType(void); + +/** @brief Finds a type by its name. + +The function finds a registered type by its name. It returns NULL if there is no type with the +specified name. +@param type_name Type name + */ CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); + +/** @brief Returns the type of an object. + +The function finds the type of a given object. It iterates through the list of registered types and +calls the is_instance function/method for every type info structure with that object until one of +them returns non-zero or until the whole list has been traversed. In the latter case, the function +returns NULL. +@param struct_ptr The object pointer + */ CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); -/* universal functions */ +/** @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 ); + +/** @brief Makes a clone of an object. + +The function finds the type of a given object and calls clone with the passed object. Of course, if +you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific +function, like cvCloneMat. +@param struct_ptr The object to clone + */ CVAPI(void*) cvClone( const void* struct_ptr ); -/* simple API for reading/writing data */ +/** @brief Saves an object to a file. + +The function saves an object to a file. It provides a simple interface to cvWrite . +@param filename File name +@param struct_ptr Object to save +@param name Optional object name. If it is NULL, the name will be formed from filename . +@param comment Optional comment to put in the beginning of the file +@param attributes Optional attributes passed to cvWrite + */ CVAPI(void) cvSave( const char* filename, const void* struct_ptr, const char* name CV_DEFAULT(NULL), const char* comment CV_DEFAULT(NULL), CvAttrList attributes CV_DEFAULT(cvAttrList())); + +/** @brief Loads an object from a file. + +The function loads an object from a file. It basically reads the specified file, find the first +top-level node and calls cvRead for that node. If the file node does not have type information or +the type information can not be found by the type name, the function returns NULL. After the object +is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a +dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage +destination to the function. +@param filename File name +@param memstorage Memory storage for dynamic structures, such as CvSeq or CvGraph . It is not used +for matrices or images. +@param name Optional object name. If it is NULL, the first top-level object in the storage will be +loaded. +@param real_name Optional output parameter that will contain the name of the loaded object +(useful if name=NULL ) + */ CVAPI(void*) cvLoad( const char* filename, CvMemStorage* memstorage CV_DEFAULT(NULL), const char* name CV_DEFAULT(NULL), @@ -1689,114 +2609,92 @@ CVAPI(void*) cvLoad( const char* filename, /*********************************** Measuring Execution Time ***************************/ -/* helper functions for RNG initialization and accurate time measurement: +/** helper functions for RNG initialization and accurate time measurement: uses internal clock counter on x86 */ CVAPI(int64) cvGetTickCount( void ); CVAPI(double) cvGetTickFrequency( void ); /*********************************** CPU capabilities ***********************************/ -#define CV_CPU_NONE 0 -#define CV_CPU_MMX 1 -#define CV_CPU_SSE 2 -#define CV_CPU_SSE2 3 -#define CV_CPU_SSE3 4 -#define CV_CPU_SSSE3 5 -#define CV_CPU_SSE4_1 6 -#define CV_CPU_SSE4_2 7 -#define CV_CPU_POPCNT 8 -#define CV_CPU_AVX 10 -#define CV_CPU_AVX2 11 -#define CV_HARDWARE_MAX_FEATURE 255 - CVAPI(int) cvCheckHardwareSupport(int feature); /*********************************** Multi-Threading ************************************/ -/* retrieve/set the number of threads used in OpenMP implementations */ +/** retrieve/set the number of threads used in OpenMP implementations */ CVAPI(int) cvGetNumThreads( void ); CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); -/* get index of the thread being executed */ +/** get index of the thread being executed */ CVAPI(int) cvGetThreadNum( void ); /********************************** Error Handling **************************************/ -/* Get current OpenCV error status */ +/** Get current OpenCV error status */ CVAPI(int) cvGetErrStatus( void ); -/* Sets error status silently */ +/** 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 */ -/* Retrives current error processing mode */ +/** Retrieves current error processing mode */ CVAPI(int) cvGetErrMode( void ); -/* Sets error processing mode, returns previously used mode */ +/** Sets error processing mode, returns previously used mode */ CVAPI(int) cvSetErrMode( int mode ); -/* Sets error status and performs some additonal actions (displaying message box, +/** Sets error status and performs some additional actions (displaying message box, writing message to stderr, terminating application etc.) depending on the current error mode */ CVAPI(void) cvError( int status, const char* func_name, const char* err_msg, const char* file_name, int line ); -/* Retrieves textual description of the error given its code */ +/** Retrieves textual description of the error given its code */ CVAPI(const char*) cvErrorStr( int status ); -/* Retrieves detailed information about the last error occured */ +/** 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 */ +/** Maps IPP error codes to the counterparts from OpenCV */ CVAPI(int) cvErrorFromIppStatus( int ipp_status ); typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); -/* Assigns a new error-handling function */ +/** Assigns a new error-handling function */ CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, void* userdata CV_DEFAULT(NULL), void** prev_userdata CV_DEFAULT(NULL) ); -/* - Output to: - cvNulDevReport - nothing - cvStdErrReport - console(fprintf(stderr,...)) - cvGuiBoxReport - MessageBox(WIN32) - */ +/** Output nothing */ CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); +/** Output to console(fprintf(stderr,...)) */ CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); +/** Output to MessageBox(WIN32) */ CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); #define OPENCV_ERROR(status,func,context) \ cvError((status),(func),(context),__FILE__,__LINE__) -#define OPENCV_ERRCHK(func,context) \ -{if (cvGetErrStatus() >= 0) \ -{OPENCV_ERROR(CV_StsBackTrace,(func),(context));}} - #define OPENCV_ASSERT(expr,func,context) \ {if (! (expr)) \ {OPENCV_ERROR(CV_StsInternal,(func),(context));}} -#define OPENCV_RSTERR() (cvSetErrStatus(CV_StsOk)) - #define OPENCV_CALL( Func ) \ { \ Func; \ } -/* CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ +/** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ #ifdef CV_NO_FUNC_NAMES #define CV_FUNCNAME( Name ) #define cvFuncName "" @@ -1806,7 +2704,7 @@ static char cvFuncName[] = Name #endif -/* +/** CV_ERROR macro unconditionally raises error with passed code and message. After raising error, control will be transferred to the exit label. */ @@ -1816,11 +2714,7 @@ static char cvFuncName[] = Name __CV_EXIT__; \ } -/* Simplified form of CV_ERROR */ -#define CV_ERROR_FROM_CODE( code ) \ - CV_ERROR( code, "" ) - -/* +/** CV_CHECK macro checks error status after CV (or IPL) function call. If error detected, control will be transferred to the exit label. @@ -1832,10 +2726,10 @@ static char cvFuncName[] = Name } -/* +/** CV_CALL macro calls CV (or IPL) function, checks error status and signals a error if the function failed. Useful in "parent node" - error procesing mode + error processing mode */ #define CV_CALL( Func ) \ { \ @@ -1844,7 +2738,7 @@ static char cvFuncName[] = Name } -/* Runtime assertion macro */ +/** Runtime assertion macro */ #define CV_ASSERT( Condition ) \ { \ if( !(Condition) ) \ @@ -1855,20 +2749,18 @@ static char cvFuncName[] = Name #define __CV_END__ goto exit; exit: ; } #define __CV_EXIT__ goto exit +/** @} core_c */ + #ifdef __cplusplus -} +} // extern "C" +#endif -// classes for automatic module/RTTI data registration/unregistration -struct CV_EXPORTS CvModule -{ - CvModule( CvModuleInfo* _info ); - ~CvModule(); - CvModuleInfo* info; +#ifdef __cplusplus - static CvModuleInfo* first; - static CvModuleInfo* last; -}; +//! @addtogroup core_c_glue +//! @{ +//! class for automatic module/RTTI data registration/unregistration struct CV_EXPORTS CvType { CvType( const char* type_name, @@ -1881,6 +2773,403 @@ struct CV_EXPORTS CvType static CvTypeInfo* last; }; +//! @} + +#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); + +static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) +{ + return cvarrToMat(arr, copyData, true, coiMode); +} + + +//! 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); +//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage +CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); + + + +////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// + +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMat* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(IplImage* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMatND* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvSparseMat* obj) const; +template<> CV_EXPORTS void DefaultDeleter::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/HuaGoCorrect/pub/opencv/include/opencv2/core/eigen.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/core/eigen.hpp index a7b237f..741648e 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/eigen.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/eigen.hpp @@ -12,6 +12,7 @@ // // 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, @@ -40,13 +41,11 @@ // //M*/ -#ifndef __OPENCV_CORE_EIGEN_HPP__ -#define __OPENCV_CORE_EIGEN_HPP__ -#ifdef __cplusplus +#ifndef OPENCV_CORE_EIGEN_HPP +#define OPENCV_CORE_EIGEN_HPP -#include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" +#include "opencv2/core.hpp" #if defined _MSC_VER && _MSC_VER >= 1200 #pragma warning( disable: 4714 ) //__forceinline is not inlined @@ -57,32 +56,50 @@ namespace cv { -template -void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst ) +//! @addtogroup core_eigen +//! @{ + +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { - Mat _src(src.cols(), src.rows(), DataType<_Tp>::type, - (void*)src.data(), src.stride()*sizeof(_Tp)); + Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); transpose(_src, dst); } else { - Mat _src(src.rows(), src.cols(), DataType<_Tp>::type, - (void*)src.data(), src.stride()*sizeof(_Tp)); + Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); _src.copyTo(dst); } } -template +// Matx case +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, + Matx<_Tp, _rows, _cols>& dst ) +{ + if( !(src.Flags & Eigen::RowMajorBit) ) + { + dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); + } + else + { + dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); + } +} + +template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { CV_DbgAssert(src.rows == _rows && src.cols == _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(src.cols, src.rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) @@ -92,47 +109,43 @@ void cv2eigen( const Mat& src, } else Mat(src.t()).convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(src.rows, src.cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case -template +template static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(_cols, _rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(_rows, _cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } -template +template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(src.rows, src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(src.cols, src.rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) @@ -142,40 +155,36 @@ void cv2eigen( const Mat& src, } else Mat(src.t()).convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(src.rows, src.cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case -template +template static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(_rows, _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(_cols, _rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(_rows, _cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } -template +template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { @@ -184,25 +193,23 @@ void cv2eigen( const Mat& src, if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(src.cols, src.rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(src.rows, src.cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case -template +template static inline void cv2eigen( const Matx<_Tp, _rows, 1>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { @@ -210,22 +217,20 @@ void cv2eigen( const Matx<_Tp, _rows, 1>& src, if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(1, _rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(1, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(_rows, 1, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_rows, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.copyTo(_dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } -template +template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { @@ -233,48 +238,43 @@ void cv2eigen( const Mat& src, dst.resize(src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(src.cols, src.rows, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(src.rows, src.cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } //Matx -template +template static inline void cv2eigen( const Matx<_Tp, 1, _cols>& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { dst.resize(_cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { - Mat _dst(_cols, 1, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(_cols, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { - Mat _dst(1, _cols, DataType<_Tp>::type, - dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + const Mat _dst(1, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); - CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } +//! @} -} - -#endif +} // cv #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/mat.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/core/mat.hpp index e10cd95..2c23a2a 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/mat.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/mat.hpp @@ -7,11 +7,12 @@ // copy or use the software. // // -// License Agreement +// 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, @@ -40,1142 +41,3431 @@ // //M*/ -#ifndef __OPENCV_CORE_MATRIX_OPERATIONS_HPP__ -#define __OPENCV_CORE_MATRIX_OPERATIONS_HPP__ +#ifndef OPENCV_CORE_MAT_HPP +#define OPENCV_CORE_MAT_HPP -#ifndef SKIP_INCLUDES -#include -#include -#endif // SKIP_INCLUDES +#ifndef __cplusplus +# error mat.hpp header must be compiled as C++ +#endif -#ifdef __cplusplus +#include "opencv2/core/matx.hpp" +#include "opencv2/core/types.hpp" + +#include "opencv2/core/bufferpool.hpp" + +#ifdef CV_CXX11 +#include +#endif namespace cv { -//////////////////////////////// Mat //////////////////////////////// +//! @addtogroup core_basic +//! @{ -inline void Mat::initEmpty() -{ - flags = MAGIC_VAL; - dims = rows = cols = 0; - data = datastart = dataend = datalimit = 0; - refcount = 0; - allocator = 0; -} +enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, + ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; -inline Mat::Mat() : size(&rows) -{ - initEmpty(); -} +CV__DEBUG_NS_BEGIN -inline Mat::Mat(int _rows, int _cols, int _type) : size(&rows) -{ - initEmpty(); - create(_rows, _cols, _type); -} +class CV_EXPORTS _OutputArray; -inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s) : size(&rows) -{ - initEmpty(); - create(_rows, _cols, _type); - *this = _s; -} +//////////////////////// Input/Output Array Arguments ///////////////////////////////// -inline Mat::Mat(Size _sz, int _type) : size(&rows) -{ - initEmpty(); - create( _sz.height, _sz.width, _type ); -} +/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. -inline Mat::Mat(Size _sz, int _type, const Scalar& _s) : size(&rows) -{ - initEmpty(); - create(_sz.height, _sz.width, _type); - *this = _s; -} +It is defined as: +@code + typedef const _InputArray& InputArray; +@endcode +where _InputArray is a class that can be constructed from `Mat`, `Mat_`, `Matx`, +`std::vector`, `std::vector >`, `std::vector`, `std::vector >`, +`UMat`, `std::vector` or `double`. It can also be constructed from a matrix expression. -inline Mat::Mat(int _dims, const int* _sz, int _type) : size(&rows) -{ - initEmpty(); - create(_dims, _sz, _type); -} +Since this is mostly implementation-level class, and its interface may change in future versions, we +do not describe it in details. There are a few key things, though, that should be kept in mind: -inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s) : size(&rows) -{ - initEmpty(); - create(_dims, _sz, _type); - *this = _s; -} +- When you see in the reference manual or in OpenCV source code a function that takes + InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the + complete list). +- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or + simply cv::Mat() as you probably did before). +- The class is designed solely for passing parameters. That is, normally you *should not* + declare class members, local and global variables of this type. +- If you want to design your own function or a class method that can operate of arrays of + multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside + a function you should use _InputArray::getMat() method to construct a matrix header for the + array (without copying data). _InputArray::kind() can be used to distinguish Mat from + `vector<>` etc., but normally it is not needed. -inline Mat::Mat(const Mat& m) - : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data), - refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), - datalimit(m.datalimit), allocator(m.allocator), size(&rows) -{ - if( refcount ) - CV_XADD(refcount, 1); - if( m.dims <= 2 ) +Here is how you can use a function that takes InputArray : +@code + std::vector vec; + // points or a circle + for( int i = 0; i < 30; i++ ) + vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), + (float)(100 - 30*sin(i*CV_PI*2/5)))); + cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); +@endcode +That is, we form an STL vector containing points, and apply in-place affine transformation to the +vector using the 2x3 matrix created inline as `Matx` instance. + +Here is how such a function can be implemented (for simplicity, we implement a very specific case of +it, according to the assertion statement inside) : +@code + void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) { - step[0] = m.step[0]; step[1] = m.step[1]; + // get Mat headers for input arrays. This is O(1) operation, + // unless _src and/or _m are matrix expressions. + Mat src = _src.getMat(), m = _m.getMat(); + CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); + + // [re]create the output array so that it has the proper size and type. + // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. + _dst.create(src.size(), src.type()); + Mat dst = _dst.getMat(); + + for( int i = 0; i < src.rows; i++ ) + for( int j = 0; j < src.cols; j++ ) + { + Point2f pt = src.at(i, j); + dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + + m.at(0, 1)*pt.y + + m.at(0, 2), + m.at(1, 0)*pt.x + + m.at(1, 1)*pt.y + + m.at(1, 2)); + } } - else - { - dims = 0; - copySize(m); - } -} +@endcode +There is another related type, InputArrayOfArrays, which is currently defined as a synonym for +InputArray: +@code + typedef InputArray InputArrayOfArrays; +@endcode +It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate +synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation +level their use is similar, but _InputArray::getMat(idx) should be used to get header for the +idx-th component of the outer vector and _InputArray::size().area() should be used to find the +number of components (vectors/matrices) of the outer vector. -inline Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step) - : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_rows), cols(_cols), - data((uchar*)_data), refcount(0), datastart((uchar*)_data), dataend(0), - datalimit(0), allocator(0), size(&rows) +In general, type support is limited to cv::Mat types. Other types are forbidden. +But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. +This data is not intented to be interpreted as an image data, or processed somehow like regular cv::Mat. +To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. +Custom type is wrapped as Mat-compatible `CV_8UC` values (N = sizeof(T), N <= CV_CN_MAX). + */ +class CV_EXPORTS _InputArray { - size_t esz = CV_ELEM_SIZE(_type), minstep = cols*esz; - if( _step == AUTO_STEP ) - { - _step = minstep; - flags |= CONTINUOUS_FLAG; - } - else - { - if( rows == 1 ) _step = minstep; - CV_DbgAssert( _step >= minstep ); - flags |= _step == minstep ? CONTINUOUS_FLAG : 0; - } - step[0] = _step; step[1] = esz; - datalimit = datastart + _step*rows; - dataend = datalimit - _step + minstep; -} +public: + enum { + KIND_SHIFT = 16, + FIXED_TYPE = 0x8000 << KIND_SHIFT, + FIXED_SIZE = 0x4000 << KIND_SHIFT, + KIND_MASK = 31 << KIND_SHIFT, -inline Mat::Mat(Size _sz, int _type, void* _data, size_t _step) - : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_sz.height), cols(_sz.width), - data((uchar*)_data), refcount(0), datastart((uchar*)_data), dataend(0), - datalimit(0), allocator(0), size(&rows) + NONE = 0 << KIND_SHIFT, + MAT = 1 << KIND_SHIFT, + MATX = 2 << KIND_SHIFT, + STD_VECTOR = 3 << KIND_SHIFT, + STD_VECTOR_VECTOR = 4 << KIND_SHIFT, + STD_VECTOR_MAT = 5 << KIND_SHIFT, + EXPR = 6 << KIND_SHIFT, + OPENGL_BUFFER = 7 << KIND_SHIFT, + CUDA_HOST_MEM = 8 << KIND_SHIFT, + CUDA_GPU_MAT = 9 << KIND_SHIFT, + UMAT =10 << KIND_SHIFT, + STD_VECTOR_UMAT =11 << KIND_SHIFT, + STD_BOOL_VECTOR =12 << KIND_SHIFT, + STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, + STD_ARRAY =14 << KIND_SHIFT, + STD_ARRAY_MAT =15 << KIND_SHIFT + }; + + _InputArray(); + _InputArray(int _flags, void* _obj); + _InputArray(const Mat& m); + _InputArray(const MatExpr& expr); + _InputArray(const std::vector& vec); + template _InputArray(const Mat_<_Tp>& m); + template _InputArray(const std::vector<_Tp>& vec); + _InputArray(const std::vector& vec); + template _InputArray(const std::vector >& vec); + _InputArray(const std::vector >&); + template _InputArray(const std::vector >& vec); + template _InputArray(const _Tp* vec, int n); + template _InputArray(const Matx<_Tp, m, n>& matx); + _InputArray(const double& val); + _InputArray(const cuda::GpuMat& d_mat); + _InputArray(const std::vector& d_mat_array); + _InputArray(const ogl::Buffer& buf); + _InputArray(const cuda::HostMem& cuda_mem); + template _InputArray(const cudev::GpuMat_<_Tp>& m); + _InputArray(const UMat& um); + _InputArray(const std::vector& umv); + +#ifdef CV_CXX_STD_ARRAY + template _InputArray(const std::array<_Tp, _Nm>& arr); + template _InputArray(const std::array& arr); +#endif + + template static _InputArray rawIn(const std::vector<_Tp>& vec); +#ifdef CV_CXX_STD_ARRAY + template static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); +#endif + + Mat getMat(int idx=-1) const; + Mat getMat_(int idx=-1) const; + UMat getUMat(int idx=-1) const; + void getMatVector(std::vector& mv) const; + void getUMatVector(std::vector& umv) const; + void getGpuMatVector(std::vector& gpumv) const; + cuda::GpuMat getGpuMat() const; + ogl::Buffer getOGlBuffer() const; + + int getFlags() const; + void* getObj() const; + Size getSz() const; + + int kind() const; + int dims(int i=-1) const; + int cols(int i=-1) const; + int rows(int i=-1) const; + Size size(int i=-1) const; + int sizend(int* sz, int i=-1) const; + bool sameSize(const _InputArray& arr) const; + size_t total(int i=-1) const; + int type(int i=-1) const; + int depth(int i=-1) const; + int channels(int i=-1) const; + bool isContinuous(int i=-1) const; + bool isSubmatrix(int i=-1) const; + bool empty() const; + void copyTo(const _OutputArray& arr) const; + void copyTo(const _OutputArray& arr, const _InputArray & mask) const; + size_t offset(int i=-1) const; + size_t step(int i=-1) const; + bool isMat() const; + bool isUMat() const; + bool isMatVector() const; + bool isUMatVector() const; + bool isMatx() const; + bool isVector() const; + bool isGpuMat() const; + bool isGpuMatVector() const; + ~_InputArray(); + +protected: + int flags; + void* obj; + Size sz; + + void init(int _flags, const void* _obj); + void init(int _flags, const void* _obj, Size _sz); +}; + + +/** @brief This type is very similar to InputArray except that it is used for input/output and output function +parameters. + +Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, +`vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly +create OutputArray instances* applies here too. + +If you want to make your function polymorphic (i.e. accept different arrays as output parameters), +it is also not very difficult. Take the sample above as the reference. Note that +_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee +that the output array is properly allocated. + +Optional output parameters. If you do not need certain output array to be computed and returned to +you, pass cv::noArray(), just like you would in the case of optional input array. At the +implementation level, use _OutputArray::needed() to check if certain output array needs to be +computed or not. + +There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper +generators: +@code + typedef OutputArray OutputArrayOfArrays; + typedef OutputArray InputOutputArray; + typedef OutputArray InputOutputArrayOfArrays; +@endcode + */ +class CV_EXPORTS _OutputArray : public _InputArray { - size_t esz = CV_ELEM_SIZE(_type), minstep = cols*esz; - if( _step == AUTO_STEP ) +public: + enum { - _step = minstep; - flags |= CONTINUOUS_FLAG; - } - else - { - if( rows == 1 ) _step = minstep; - CV_DbgAssert( _step >= minstep ); - flags |= _step == minstep ? CONTINUOUS_FLAG : 0; - } - step[0] = _step; step[1] = esz; - datalimit = datastart + _step*rows; - dataend = datalimit - _step + minstep; -} + DEPTH_MASK_8U = 1 << CV_8U, + DEPTH_MASK_8S = 1 << CV_8S, + DEPTH_MASK_16U = 1 << CV_16U, + DEPTH_MASK_16S = 1 << CV_16S, + DEPTH_MASK_32S = 1 << CV_32S, + DEPTH_MASK_32F = 1 << CV_32F, + DEPTH_MASK_64F = 1 << CV_64F, + DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, + DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, + DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F + }; + + _OutputArray(); + _OutputArray(int _flags, void* _obj); + _OutputArray(Mat& m); + _OutputArray(std::vector& vec); + _OutputArray(cuda::GpuMat& d_mat); + _OutputArray(std::vector& d_mat); + _OutputArray(ogl::Buffer& buf); + _OutputArray(cuda::HostMem& cuda_mem); + template _OutputArray(cudev::GpuMat_<_Tp>& m); + template _OutputArray(std::vector<_Tp>& vec); + _OutputArray(std::vector& vec); + template _OutputArray(std::vector >& vec); + _OutputArray(std::vector >&); + template _OutputArray(std::vector >& vec); + template _OutputArray(Mat_<_Tp>& m); + template _OutputArray(_Tp* vec, int n); + template _OutputArray(Matx<_Tp, m, n>& matx); + _OutputArray(UMat& m); + _OutputArray(std::vector& vec); + + _OutputArray(const Mat& m); + _OutputArray(const std::vector& vec); + _OutputArray(const cuda::GpuMat& d_mat); + _OutputArray(const std::vector& d_mat); + _OutputArray(const ogl::Buffer& buf); + _OutputArray(const cuda::HostMem& cuda_mem); + template _OutputArray(const cudev::GpuMat_<_Tp>& m); + template _OutputArray(const std::vector<_Tp>& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const Mat_<_Tp>& m); + template _OutputArray(const _Tp* vec, int n); + template _OutputArray(const Matx<_Tp, m, n>& matx); + _OutputArray(const UMat& m); + _OutputArray(const std::vector& vec); + +#ifdef CV_CXX_STD_ARRAY + template _OutputArray(std::array<_Tp, _Nm>& arr); + template _OutputArray(const std::array<_Tp, _Nm>& arr); + template _OutputArray(std::array& arr); + template _OutputArray(const std::array& arr); +#endif + + template static _OutputArray rawOut(std::vector<_Tp>& vec); +#ifdef CV_CXX_STD_ARRAY + template static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); +#endif + + bool fixedSize() const; + bool fixedType() const; + bool needed() const; + Mat& getMatRef(int i=-1) const; + UMat& getUMatRef(int i=-1) const; + cuda::GpuMat& getGpuMatRef() const; + std::vector& getGpuMatVecRef() const; + ogl::Buffer& getOGlBufferRef() const; + cuda::HostMem& getHostMemRef() const; + void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; + void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; + void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; + void createSameSize(const _InputArray& arr, int mtype) const; + void release() const; + void clear() const; + void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; + + void assign(const UMat& u) const; + void assign(const Mat& m) const; + + void assign(const std::vector& v) const; + void assign(const std::vector& v) const; +}; -template inline Mat::Mat(const vector<_Tp>& vec, bool copyData) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(2), rows((int)vec.size()), cols(1), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) +class CV_EXPORTS _InputOutputArray : public _OutputArray { - if(vec.empty()) - return; - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - data = datastart = (uchar*)&vec[0]; - datalimit = dataend = datastart + rows*step[0]; - } - else - Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this); -} +public: + _InputOutputArray(); + _InputOutputArray(int _flags, void* _obj); + _InputOutputArray(Mat& m); + _InputOutputArray(std::vector& vec); + _InputOutputArray(cuda::GpuMat& d_mat); + _InputOutputArray(ogl::Buffer& buf); + _InputOutputArray(cuda::HostMem& cuda_mem); + template _InputOutputArray(cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(std::vector<_Tp>& vec); + _InputOutputArray(std::vector& vec); + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(Mat_<_Tp>& m); + template _InputOutputArray(_Tp* vec, int n); + template _InputOutputArray(Matx<_Tp, m, n>& matx); + _InputOutputArray(UMat& m); + _InputOutputArray(std::vector& vec); + _InputOutputArray(const Mat& m); + _InputOutputArray(const std::vector& vec); + _InputOutputArray(const cuda::GpuMat& d_mat); + _InputOutputArray(const std::vector& d_mat); + _InputOutputArray(const ogl::Buffer& buf); + _InputOutputArray(const cuda::HostMem& cuda_mem); + template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(const std::vector<_Tp>& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const Mat_<_Tp>& m); + template _InputOutputArray(const _Tp* vec, int n); + template _InputOutputArray(const Matx<_Tp, m, n>& matx); + _InputOutputArray(const UMat& m); + _InputOutputArray(const std::vector& vec); -template inline Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(2), rows(n), cols(1), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) +#ifdef CV_CXX_STD_ARRAY + template _InputOutputArray(std::array<_Tp, _Nm>& arr); + template _InputOutputArray(const std::array<_Tp, _Nm>& arr); + template _InputOutputArray(std::array& arr); + template _InputOutputArray(const std::array& arr); +#endif + + template static _InputOutputArray rawInOut(std::vector<_Tp>& vec); +#ifdef CV_CXX_STD_ARRAY + template _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); +#endif + +}; + +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputArray rawIn(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _OutputArray rawOut(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputOutputArray rawInOut(_Tp& v); + +CV__DEBUG_NS_END + +typedef const _InputArray& InputArray; +typedef InputArray InputArrayOfArrays; +typedef const _OutputArray& OutputArray; +typedef OutputArray OutputArrayOfArrays; +typedef const _InputOutputArray& InputOutputArray; +typedef InputOutputArray InputOutputArrayOfArrays; + +CV_EXPORTS InputOutputArray noArray(); + +/////////////////////////////////// MatAllocator ////////////////////////////////////// + +//! Usage flags for allocator +enum UMatUsageFlags { - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - data = datastart = (uchar*)vec.val; - datalimit = dataend = datastart + rows*step[0]; - } - else - Mat(n, 1, DataType<_Tp>::type, (void*)vec.val).copyTo(*this); -} + USAGE_DEFAULT = 0, + // buffer allocation policy is platform and usage specific + USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, + USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, + USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY -template inline Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(2), rows(m), cols(n), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) + __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint +}; + +struct CV_EXPORTS UMatData; + +/** @brief Custom array allocator +*/ +class CV_EXPORTS MatAllocator { - if( !copyData ) - { - step[0] = cols*sizeof(_Tp); - step[1] = sizeof(_Tp); - data = datastart = (uchar*)M.val; - datalimit = dataend = datastart + rows*step[0]; - } - else - Mat(m, n, DataType<_Tp>::type, (uchar*)M.val).copyTo(*this); -} +public: + MatAllocator() {} + virtual ~MatAllocator() {} + + // let's comment it off for now to detect and fix all the uses of allocator + //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, + // uchar*& datastart, uchar*& data, size_t* step) = 0; + //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; + virtual UMatData* allocate(int dims, const int* sizes, int type, + void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0; + virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0; + virtual void deallocate(UMatData* data) const = 0; + virtual void map(UMatData* data, int accessflags) const; + virtual void unmap(UMatData* data) const; + virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dststep[]) const; + virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], + const size_t dstofs[], const size_t dststep[], + const size_t srcstep[]) const; + virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dstofs[], const size_t dststep[], bool sync) const; + + // default implementation returns DummyBufferPoolController + virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; +}; -template inline Mat::Mat(const Point_<_Tp>& pt, bool copyData) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(2), rows(2), cols(1), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) +//////////////////////////////// MatCommaInitializer ////////////////////////////////// + +/** @brief Comma-separated Matrix Initializer + + The class instances are usually not created explicitly. + Instead, they are created on "matrix << firstValue" operator. + + The sample below initializes 2x2 rotation matrix: + + \code + double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); + Mat R = (Mat_(2,2) << a, -b, b, a); + \endcode +*/ +template class MatCommaInitializer_ { - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - data = datastart = (uchar*)&pt.x; - datalimit = dataend = datastart + rows*step[0]; - } - else - { - create(2, 1, DataType<_Tp>::type); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - } -} +public: + //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat + MatCommaInitializer_(Mat_<_Tp>* _m); + //! the operator that takes the next value and put it to the matrix + template MatCommaInitializer_<_Tp>& operator , (T2 v); + //! another form of conversion operator + operator Mat_<_Tp>() const; +protected: + MatIterator_<_Tp> it; +}; -template inline Mat::Mat(const Point3_<_Tp>& pt, bool copyData) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(2), rows(3), cols(1), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) +/////////////////////////////////////// Mat /////////////////////////////////////////// + +// note that umatdata might be allocated together +// with the matrix data, not as a separate object. +// therefore, it does not have constructor or destructor; +// it should be explicitly initialized using init(). +struct CV_EXPORTS UMatData { - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - data = datastart = (uchar*)&pt.x; - datalimit = dataend = datastart + rows*step[0]; - } - else - { - create(3, 1, DataType<_Tp>::type); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - ((_Tp*)data)[2] = pt.z; - } -} + enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, + DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, + USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, + ASYNC_CLEANUP=128 + }; + UMatData(const MatAllocator* allocator); + ~UMatData(); + + // provide atomic access to the structure + void lock(); + void unlock(); + + bool hostCopyObsolete() const; + bool deviceCopyObsolete() const; + bool deviceMemMapped() const; + bool copyOnMap() const; + bool tempUMat() const; + bool tempCopiedUMat() const; + void markHostCopyObsolete(bool flag); + void markDeviceCopyObsolete(bool flag); + void markDeviceMemMapped(bool flag); + + const MatAllocator* prevAllocator; + const MatAllocator* currAllocator; + int urefcount; + int refcount; + uchar* data; + uchar* origdata; + size_t size; + + int flags; + void* handle; + void* userdata; + int allocatorFlags_; + int mapcount; + UMatData* originalUMatData; +}; -template inline Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) - : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), - dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), allocator(0), size(&rows) +struct CV_EXPORTS MatSize { - *this = *commaInitializer; -} + explicit MatSize(int* _p); + int dims() const; + Size operator()() const; + const int& operator[](int i) const; + int& operator[](int i); + operator const int*() const; // TODO OpenCV 4.0: drop this + bool operator == (const MatSize& sz) const; + bool operator != (const MatSize& sz) const; -inline Mat::~Mat() -{ - release(); - if( step.p != step.buf ) - fastFree(step.p); -} + int* p; +}; -inline Mat& Mat::operator = (const Mat& m) +struct CV_EXPORTS MatStep { - if( this != &m ) - { - if( m.refcount ) - CV_XADD(m.refcount, 1); - release(); - flags = m.flags; - if( dims <= 2 && m.dims <= 2 ) + MatStep(); + explicit MatStep(size_t s); + const size_t& operator[](int i) const; + size_t& operator[](int i); + operator size_t() const; + MatStep& operator = (size_t s); + + size_t* p; + size_t buf[2]; +protected: + MatStep& operator = (const MatStep&); +}; + +/** @example samples/cpp/cout_mat.cpp +An example demonstrating the serial out capabilities of cv::Mat +*/ + + /** @brief n-dimensional dense array class \anchor CVMat_Details + +The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It +can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel +volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms +may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array +`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means +that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, +and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . + +So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV +1.x. It is also compatible with the majority of dense array types from the standard toolkits and +SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any +array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this +compatibility, it is possible to make a Mat header for user-allocated data and process it in-place +using OpenCV functions. + +There are many different ways to create a Mat object. The most popular options are listed below: + +- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) +constructor. A new array of the specified size and type is allocated. type has the same meaning as +in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 +means a 2-channel (complex) floating-point array, and so on. +@code + // make a 7x7 complex matrix filled with 1+3j. + Mat M(7,7,CV_32FC2,Scalar(1,3)); + // and now turn M to a 100x60 15-channel 8-bit matrix. + // The old content will be deallocated + M.create(100,60,CV_8UC(15)); +@endcode +As noted in the introduction to this chapter, create() allocates only a new array when the shape +or type of the current array are different from the specified ones. + +- Create a multi-dimensional array: +@code + // create a 100x100x100 8-bit array + int sz[] = {100, 100, 100}; + Mat bigCube(3, sz, CV_8U, Scalar::all(0)); +@endcode +It passes the number of dimensions =1 to the Mat constructor but the created array will be +2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 +when the array is empty). + +- Use a copy constructor or assignment operator where there can be an array or expression on the +right side (see below). As noted in the introduction, the array assignment is an O(1) operation +because it only copies the header and increases the reference counter. The Mat::clone() method can +be used to get a full (deep) copy of the array when you need it. + +- Construct a header for a part of another array. It can be a single row, single column, several +rows, several columns, rectangular region in the array (called a *minor* in algebra) or a +diagonal. Such operations are also O(1) because the new header references the same data. You can +actually modify a part of the array using this feature, for example: +@code + // add the 5-th row, multiplied by 3 to the 3rd row + M.row(3) = M.row(3) + M.row(5)*3; + // now copy the 7-th column to the 1-st column + // M.col(1) = M.col(7); // this will not work + Mat M1 = M.col(1); + M.col(7).copyTo(M1); + // create a new 320x240 image + Mat img(Size(320,240),CV_8UC3); + // select a ROI + Mat roi(img, Rect(10,10,100,100)); + // fill the ROI with (0,255,0) (which is green in RGB space); + // the original 320x240 image will be modified + roi = Scalar(0,255,0); +@endcode +Due to the additional datastart and dataend members, it is possible to compute a relative +sub-array position in the main *container* array using locateROI(): +@code + Mat A = Mat::eye(10, 10, CV_32S); + // extracts A columns, 1 (inclusive) to 3 (exclusive). + Mat B = A(Range::all(), Range(1, 3)); + // extracts B rows, 5 (inclusive) to 9 (exclusive). + // that is, C \~ A(Range(5, 9), Range(1, 3)) + Mat C = B(Range(5, 9), Range::all()); + Size size; Point ofs; + C.locateROI(size, ofs); + // size will be (width=10,height=10) and the ofs will be (x=1, y=5) +@endcode +As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted +sub-matrices. + +- Make a header for user-allocated data. It can be useful to do the following: + -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or + a processing module for gstreamer, and so on). For example: + @code + void process_video_frame(const unsigned char* pixels, + int width, int height, int step) { - dims = m.dims; - rows = m.rows; - cols = m.cols; - step[0] = m.step[0]; - step[1] = m.step[1]; + Mat img(height, width, CV_8UC3, pixels, step); + GaussianBlur(img, img, Size(7,7), 1.5, 1.5); } - else - copySize(m); - data = m.data; - datastart = m.datastart; - dataend = m.dataend; - datalimit = m.datalimit; - refcount = m.refcount; - allocator = m.allocator; - } - return *this; -} + @endcode + -# Quickly initialize small matrices and/or get a super-fast element access. + @code + double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; + Mat M = Mat(3, 3, CV_64F, m).inv(); + @endcode + . + Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and + IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or + IplImage and the optional flag indicating whether to copy the data or not. + @snippet samples/cpp/image.cpp iplimage -inline Mat Mat::row(int y) const { return Mat(*this, Range(y, y+1), Range::all()); } -inline Mat Mat::col(int x) const { return Mat(*this, Range::all(), Range(x, x+1)); } -inline Mat Mat::rowRange(int startrow, int endrow) const - { return Mat(*this, Range(startrow, endrow), Range::all()); } -inline Mat Mat::rowRange(const Range& r) const - { return Mat(*this, r, Range::all()); } -inline Mat Mat::colRange(int startcol, int endcol) const - { return Mat(*this, Range::all(), Range(startcol, endcol)); } -inline Mat Mat::colRange(const Range& r) const - { return Mat(*this, Range::all(), r); } +- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: +@code + // create a double-precision identity matrix and add it to M. + M += Mat::eye(M.rows, M.cols, CV_64F); +@endcode -inline Mat Mat::diag(const Mat& d) -{ - CV_Assert( d.cols == 1 || d.rows == 1 ); - int len = d.rows + d.cols - 1; - Mat m(len, len, d.type(), Scalar(0)), md = m.diag(); - if( d.cols == 1 ) - d.copyTo(md); - else - transpose(d, md); - return m; -} +- Use a comma-separated initializer: +@code + // create a 3x3 double-precision identity matrix + Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); +@endcode +With this approach, you first call a constructor of the Mat class with the proper parameters, and +then you just put `<< operator` followed by comma-separated values that can be constants, +variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation +errors. -inline Mat Mat::clone() const -{ - Mat m; - copyTo(m); - return m; -} +Once the array is created, it is automatically managed via a reference-counting mechanism. If the +array header is built on top of user-allocated data, you should handle the data by yourself. The +array data is deallocated when no one points to it. If you want to release the data pointed by a +array header before the array destructor is called, use Mat::release(). -inline void Mat::assignTo( Mat& m, int _type ) const -{ - if( _type < 0 ) - m = *this; - else - convertTo(m, _type); -} +The next important thing to learn about the array class is element access. This manual already +described how to compute an address of each array element. Normally, you are not required to use the +formula directly in the code. If you know the array element type (which can be retrieved using the +method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: +@code + M.at(i,j) += 1.f; +@endcode +assuming that `M` is a double-precision floating-point array. There are several variants of the method +at for a different number of dimensions. -inline void Mat::create(int _rows, int _cols, int _type) -{ - _type &= TYPE_MASK; - if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data ) - return; - int sz[] = {_rows, _cols}; - create(2, sz, _type); -} - -inline void Mat::create(Size _sz, int _type) -{ - create(_sz.height, _sz.width, _type); -} - -inline void Mat::addref() -{ if( refcount ) CV_XADD(refcount, 1); } - -inline void Mat::release() -{ - if( refcount && CV_XADD(refcount, -1) == 1 ) - deallocate(); - data = datastart = dataend = datalimit = 0; - for(int i = 0; i < dims; i++) - size.p[i] = 0; - refcount = 0; -} - -inline Mat Mat::operator()( Range _rowRange, Range _colRange ) const -{ - return Mat(*this, _rowRange, _colRange); -} - -inline Mat Mat::operator()( const Rect& roi ) const -{ return Mat(*this, roi); } - -inline Mat Mat::operator()(const Range* ranges) const -{ - return Mat(*this, ranges); -} - -inline Mat::operator CvMat() const -{ - CV_DbgAssert(dims <= 2); - CvMat m = cvMat(rows, dims == 1 ? 1 : cols, type(), data); - m.step = (int)step[0]; - m.type = (m.type & ~CONTINUOUS_FLAG) | (flags & CONTINUOUS_FLAG); - return m; -} - -inline bool Mat::isContinuous() const { return (flags & CONTINUOUS_FLAG) != 0; } -inline bool Mat::isSubmatrix() const { return (flags & SUBMATRIX_FLAG) != 0; } -inline size_t Mat::elemSize() const { return dims > 0 ? step.p[dims-1] : 0; } -inline size_t Mat::elemSize1() const { return CV_ELEM_SIZE1(flags); } -inline int Mat::type() const { return CV_MAT_TYPE(flags); } -inline int Mat::depth() const { return CV_MAT_DEPTH(flags); } -inline int Mat::channels() const { return CV_MAT_CN(flags); } -inline size_t Mat::step1(int i) const { return step.p[i]/elemSize1(); } -inline bool Mat::empty() const { return data == 0 || total() == 0; } -inline size_t Mat::total() const -{ - if( dims <= 2 ) - return (size_t)rows*cols; - size_t p = 1; - for( int i = 0; i < dims; i++ ) - p *= size[i]; - return p; -} - -inline uchar* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0]*y; -} - -inline const uchar* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0]*y; -} - -template inline _Tp* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (_Tp*)(data + step.p[0]*y); -} - -template inline const _Tp* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (const _Tp*)(data + step.p[0]*y); -} - - -inline uchar* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert( dims >= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] ); - return data + i0*step.p[0] + i1*step.p[1]; -} - -inline const uchar* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert( dims >= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] ); - return data + i0*step.p[0] + i1*step.p[1]; -} - -template inline _Tp* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert( dims >= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] ); - return (_Tp*)(data + i0*step.p[0] + i1*step.p[1]); -} - -template inline const _Tp* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert( dims >= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] ); - return (const _Tp*)(data + i0*step.p[0] + i1*step.p[1]); -} - -inline uchar* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert( dims >= 3 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - (unsigned)i2 < (unsigned)size.p[2] ); - return data + i0*step.p[0] + i1*step.p[1] + i2*step.p[2]; -} - -inline const uchar* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert( dims >= 3 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - (unsigned)i2 < (unsigned)size.p[2] ); - return data + i0*step.p[0] + i1*step.p[1] + i2*step.p[2]; -} - -template inline _Tp* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert( dims >= 3 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - (unsigned)i2 < (unsigned)size.p[2] ); - return (_Tp*)(data + i0*step.p[0] + i1*step.p[1] + i2*step.p[2]); -} - -template inline const _Tp* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert( dims >= 3 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - (unsigned)i2 < (unsigned)size.p[2] ); - return (const _Tp*)(data + i0*step.p[0] + i1*step.p[1] + i2*step.p[2]); -} - -inline uchar* Mat::ptr(const int* idx) -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) +If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to +the row first, and then just use the plain C operator [] : +@code + // compute sum of positive matrix elements + // (assuming that M is a double-precision matrix) + double sum=0; + for(int i = 0; i < M.rows; i++) { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i]*step.p[i]; + const double* Mi = M.ptr(i); + for(int j = 0; j < M.cols; j++) + sum += std::max(Mi[j], 0.); } - return p; -} - -inline const uchar* Mat::ptr(const int* idx) const -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) +@endcode +Some operations, like the one above, do not actually depend on the array shape. They just process +elements of an array one by one (or elements from multiple arrays that have the same coordinates, +for example, array addition). Such operations are called *element-wise*. It makes sense to check +whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If +yes, process them as a long single row: +@code + // compute the sum of positive matrix elements, optimized variant + double sum=0; + int cols = M.cols, rows = M.rows; + if(M.isContinuous()) { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i]*step.p[i]; + cols *= rows; + rows = 1; } - return p; -} - -template inline _Tp& Mat::at(int i0, int i1) -{ - CV_DbgAssert( dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)(i1*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && - CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); - return ((_Tp*)(data + step.p[0]*i0))[i1]; -} - -template inline const _Tp& Mat::at(int i0, int i1) const -{ - CV_DbgAssert( dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)(i1*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && - CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); - return ((const _Tp*)(data + step.p[0]*i0))[i1]; -} - -template inline _Tp& Mat::at(Point pt) -{ - CV_DbgAssert( dims <= 2 && data && (unsigned)pt.y < (unsigned)size.p[0] && - (unsigned)(pt.x*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && - CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); - return ((_Tp*)(data + step.p[0]*pt.y))[pt.x]; -} - -template inline const _Tp& Mat::at(Point pt) const -{ - CV_DbgAssert( dims <= 2 && data && (unsigned)pt.y < (unsigned)size.p[0] && - (unsigned)(pt.x*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && - CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); - return ((const _Tp*)(data + step.p[0]*pt.y))[pt.x]; -} - -template inline _Tp& Mat::at(int i0) -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) && - elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - if( isContinuous() || size.p[0] == 1 ) - return ((_Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(_Tp*)(data + step.p[0]*i0); - int i = i0/cols, j = i0 - i*cols; - return ((_Tp*)(data + step.p[0]*i))[j]; -} - -template inline const _Tp& Mat::at(int i0) const -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) && - elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - if( isContinuous() || size.p[0] == 1 ) - return ((const _Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(const _Tp*)(data + step.p[0]*i0); - int i = i0/cols, j = i0 - i*cols; - return ((const _Tp*)(data + step.p[0]*i))[j]; -} - -template inline _Tp& Mat::at(int i0, int i1, int i2) -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(_Tp*)ptr(i0, i1, i2); -} -template inline const _Tp& Mat::at(int i0, int i1, int i2) const -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(const _Tp*)ptr(i0, i1, i2); -} -template inline _Tp& Mat::at(const int* idx) -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(_Tp*)ptr(idx); -} -template inline const _Tp& Mat::at(const int* idx) const -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(const _Tp*)ptr(idx); -} -template _Tp& Mat::at(const Vec& idx) -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(_Tp*)ptr(idx.val); -} -template inline const _Tp& Mat::at(const Vec& idx) const -{ - CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(const _Tp*)ptr(idx.val); -} - - -template inline MatConstIterator_<_Tp> Mat::begin() const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); -} - -template inline MatConstIterator_<_Tp> Mat::end() const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline MatIterator_<_Tp> Mat::begin() -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatIterator_<_Tp>((Mat_<_Tp>*)this); -} - -template inline MatIterator_<_Tp> Mat::end() -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatIterator_<_Tp> it((Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline Mat::operator vector<_Tp>() const -{ - vector<_Tp> v; - copyTo(v); - return v; -} - -template inline Mat::operator Vec<_Tp, n>() const -{ - CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && - rows + cols - 1 == n && channels() == 1 ); - - if( isContinuous() && type() == DataType<_Tp>::type ) - return Vec<_Tp, n>((_Tp*)data); - Vec<_Tp, n> v; Mat tmp(rows, cols, DataType<_Tp>::type, v.val); - convertTo(tmp, tmp.type()); - return v; -} - -template inline Mat::operator Matx<_Tp, m, n>() const -{ - CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); - - if( isContinuous() && type() == DataType<_Tp>::type ) - return Matx<_Tp, m, n>((_Tp*)data); - Matx<_Tp, m, n> mtx; Mat tmp(rows, cols, DataType<_Tp>::type, mtx.val); - convertTo(tmp, tmp.type()); - return mtx; -} - - -template inline void Mat::push_back(const _Tp& elem) -{ - if( !data ) + for(int i = 0; i < rows; i++) { - CV_Assert((type()==0) || (DataType<_Tp>::type == type())); - - *this = Mat(1, 1, DataType<_Tp>::type, (void*)&elem).clone(); - return; + const double* Mi = M.ptr(i); + for(int j = 0; j < cols; j++) + sum += std::max(Mi[j], 0.); } - CV_Assert(DataType<_Tp>::type == type() && cols == 1 - /* && dims == 2 (cols == 1 implies dims == 2) */); - uchar* tmp = dataend + step[0]; - if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) - { - *(_Tp*)(data + (size.p[0]++)*step.p[0]) = elem; - dataend = tmp; - } - else - push_back_(&elem); -} +@endcode +In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is +smaller, which is especially noticeable in case of small matrices. -template inline void Mat::push_back(const Mat_<_Tp>& m) +Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: +@code + // compute sum of positive matrix elements, iterator-based variant + double sum=0; + MatConstIterator_ it = M.begin(), it_end = M.end(); + for(; it != it_end; ++it) + sum += std::max(*it, 0.); +@endcode +The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, +including std::sort(). + +@note Matrix Expressions and arithmetic see MatExpr +*/ +class CV_EXPORTS Mat { - push_back((const Mat&)m); -} +public: + /** + These are various constructors that form a matrix. As noted in the AutomaticAllocation, often + the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. + The constructed matrix can further be assigned to another matrix or matrix expression or can be + allocated with Mat::create . In the former case, the old content is de-referenced. + */ + Mat(); -inline Mat::MSize::MSize(int* _p) : p(_p) {} -inline Size Mat::MSize::operator()() const -{ - CV_DbgAssert(p[-1] <= 2); - return Size(p[1], p[0]); -} -inline const int& Mat::MSize::operator[](int i) const { return p[i]; } -inline int& Mat::MSize::operator[](int i) { return p[i]; } -inline Mat::MSize::operator const int*() const { return p; } + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int rows, int cols, int type); -inline bool Mat::MSize::operator == (const MSize& sz) const -{ - int d = p[-1], dsz = sz.p[-1]; - if( d != dsz ) - return false; - if( d == 2 ) - return p[0] == sz.p[0] && p[1] == sz.p[1]; + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(Size size, int type); - for( int i = 0; i < d; i++ ) - if( p[i] != sz.p[i] ) - return false; - return true; -} + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int rows, int cols, int type, const Scalar& s); -inline bool Mat::MSize::operator != (const MSize& sz) const -{ - return !(*this == sz); -} + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(Size size, int type, const Scalar& s); -inline Mat::MStep::MStep() { p = buf; p[0] = p[1] = 0; } -inline Mat::MStep::MStep(size_t s) { p = buf; p[0] = s; p[1] = 0; } -inline const size_t& Mat::MStep::operator[](int i) const { return p[i]; } -inline size_t& Mat::MStep::operator[](int i) { return p[i]; } -inline Mat::MStep::operator size_t() const -{ - CV_DbgAssert( p == buf ); - return buf[0]; -} -inline Mat::MStep& Mat::MStep::operator = (size_t s) -{ - CV_DbgAssert( p == buf ); - buf[0] = s; - return *this; -} + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int ndims, const int* sizes, int type); -static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) -{ - return cvarrToMat(arr, copyData, true, coiMode); -} + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(const std::vector& sizes, int type); -///////////////////////////////////////////// SVD ////////////////////////////////////////////////////// + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int ndims, const int* sizes, int type, const Scalar& s); -inline SVD::SVD() {} -inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } -inline void SVD::solveZ( InputArray m, OutputArray _dst ) -{ - Mat mtx = m.getMat(); - SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); - _dst.create(svd.vt.cols, 1, svd.vt.type()); - Mat dst = _dst.getMat(); - svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); -} + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(const std::vector& sizes, int type, const Scalar& s); -template inline void - SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) -{ - assert( nm == MIN(m, n)); - Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); - SVD::compute(_a, _w, _u, _vt); - CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); -} -template inline void -SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) -{ - assert( nm == MIN(m, n)); - Mat _a(a, false), _w(w, false); - SVD::compute(_a, _w); - CV_Assert(_w.data == (uchar*)&w.val[0]); -} + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + */ + Mat(const Mat& m); + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(Size size, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(const std::vector& sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range + end is exclusive. Use Range::all() to take all the rows. + @param colRange Range of the m columns to take. Use Range::all() to take all the columns. + */ + Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param roi Region of interest. + */ + Mat(const Mat& m, const Rect& roi); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const Range* ranges); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const std::vector& ranges); + + /** @overload + @param vec STL vector whose elements form the matrix. The matrix has a single column and the number + of rows equal to the number of vector elements. Type of the matrix matches the type of vector + elements. The constructor can handle arbitrary types, for which there is a properly declared + DataType . This means that the vector elements must be primitive numbers or uni-type numerical + tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is + explicit. Since STL vectors are not automatically converted to Mat instances, you should write + Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements + will be added to the vector because it can potentially yield vector data reallocation, and, thus, + the matrix data pointer will be invalid. + @param copyData Flag to specify whether the underlying data of the STL vector should be copied + to (true) or shared with (false) the newly constructed matrix. When the data is copied, the + allocated buffer is managed using Mat reference counting mechanism. While the data is shared, + the reference counter is NULL, and you should not deallocate the data until the matrix is not + destructed. + */ + template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); + +#ifdef CV_CXX11 + /** @overload + */ + template::value>::type> + explicit Mat(const std::initializer_list<_Tp> list); + + /** @overload + */ + template explicit Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list); +#endif + +#ifdef CV_CXX_STD_ARRAY + /** @overload + */ + template explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); +#endif + + /** @overload + */ + template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); + + //! download data from GpuMat + explicit Mat(const cuda::GpuMat& m); + + //! destructor - calls release() + ~Mat(); + + /** @brief assignment operators + + These are available assignment operators. Since they all are very different, make sure to read the + operator parameters description. + @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that + no data is copied but the data is shared and the reference counter, if any, is incremented. Before + assigning new data, the old data is de-referenced via Mat::release . + */ + Mat& operator = (const Mat& m); + + /** @overload + @param expr Assigned matrix expression object. As opposite to the first form of the assignment + operation, the second form can reuse already allocated matrix if it has the right size and type to + fit the matrix expression result. It is automatically handled by the real function that the matrix + expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of + automatic C reallocation. + */ + Mat& operator = (const MatExpr& expr); + + //! retrieve UMat from Mat + UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; + + /** @brief Creates a matrix header for the specified matrix row. + + The method makes a new header for the specified matrix row and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. Here is the example of one of the classical basic matrix processing operations, + axpy, used by LU and many other algorithms: + @code + inline void matrix_axpy(Mat& A, int i, int j, double alpha) + { + A.row(i) += A.row(j)*alpha; + } + @endcode + @note In the current implementation, the following code does not work as expected: + @code + Mat A; + ... + A.row(i) = A.row(j); // will not work + @endcode + This happens because A.row(i) forms a temporary header that is further assigned to another header. + Remember that each of these operations is O(1), that is, no data is copied. Thus, the above + assignment is not true if you may have expected the j-th row to be copied to the i-th row. To + achieve that, you should either turn this simple assignment into an expression or use the + Mat::copyTo method: + @code + Mat A; + ... + // works, but looks a bit obscure. + A.row(i) = A.row(j) + 0; + // this is a bit longer, but the recommended method. + A.row(j).copyTo(A.row(i)); + @endcode + @param y A 0-based row index. + */ + Mat row(int y) const; + + /** @brief Creates a matrix header for the specified matrix column. + + The method makes a new header for the specified matrix column and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. See also the Mat::row description. + @param x A 0-based column index. + */ + Mat col(int x) const; + + /** @brief Creates a matrix header for the specified row span. + + The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startrow An inclusive 0-based start index of the row span. + @param endrow An exclusive 0-based ending index of the row span. + */ + Mat rowRange(int startrow, int endrow) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat rowRange(const Range& r) const; + + /** @brief Creates a matrix header for the specified column span. + + The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startcol An inclusive 0-based start index of the column span. + @param endcol An exclusive 0-based ending index of the column span. + */ + Mat colRange(int startcol, int endcol) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat colRange(const Range& r) const; + + /** @brief Extracts a diagonal from a matrix + + The method makes a new header for the specified matrix diagonal. The new matrix is represented as a + single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. + @param d index of the diagonal, with the following values: + - `d=0` is the main diagonal. + - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set + immediately below the main one. + - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set + immediately above the main one. + For example: + @code + Mat m = (Mat_(3,3) << + 1,2,3, + 4,5,6, + 7,8,9); + Mat d0 = m.diag(0); + Mat d1 = m.diag(1); + Mat d_1 = m.diag(-1); + @endcode + The resulting matrices are + @code + d0 = + [1; + 5; + 9] + d1 = + [2; + 6] + d_1 = + [4; + 8] + @endcode + */ + Mat diag(int d=0) const; + + /** @brief creates a diagonal matrix + + The method creates a square diagonal matrix from specified main diagonal. + @param d One-dimensional matrix that represents the main diagonal. + */ + static Mat diag(const Mat& d); + + /** @brief Creates a full copy of the array and the underlying data. + + The method creates a full copy of the array. The original step[] is not taken into account. So, the + array copy is a continuous array occupying total()*elemSize() bytes. + */ + Mat clone() const CV_NODISCARD; + + /** @brief Copies the matrix to another one. + + The method copies the matrix data to another matrix. Before copying the data, the method invokes : + @code + m.create(this->size(), this->type()); + @endcode + so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the + function does not handle the case of a partial overlap between the source and the destination + matrices. + + When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, + the newly allocated matrix is initialized with all zeros before copying the data. + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + */ + void copyTo( OutputArray m ) const; + + /** @overload + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. + */ + void copyTo( OutputArray m, InputArray mask ) const; + + /** @brief Converts an array to another data type with optional scaling. + + The method converts source pixel values to the target data type. saturate_cast\<\> is applied at + the end to avoid possible overflows: + + \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] + @param m output matrix; if it does not have a proper size or type before the operation, it is + reallocated. + @param rtype desired output matrix type or, rather, the depth since the number of channels are the + same as the input has; if rtype is negative, the output matrix will have the same type as the input. + @param alpha optional scale factor. + @param beta optional delta added to the scaled values. + */ + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + /** @brief Provides a functional form of convertTo. + + This is an internally used method called by the @ref MatrixExpressions engine. + @param m Destination array. + @param type Desired destination array depth (or -1 if it should be the same as the source type). + */ + void assignTo( Mat& m, int type=-1 ) const; + + /** @brief Sets all or some of the array elements to the specified value. + @param s Assigned scalar converted to the actual array type. + */ + Mat& operator = (const Scalar& s); + + /** @brief Sets all or some of the array elements to the specified value. + + This is an advanced variant of the Mat::operator=(const Scalar& s) operator. + @param value Assigned scalar converted to the actual array type. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels + */ + Mat& setTo(InputArray value, InputArray mask=noArray()); + + /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. + + The method makes a new matrix header for \*this elements. The new matrix may have a different size + and/or different number of channels. Any combination is possible if: + - No extra elements are included into the new matrix and no elements are excluded. Consequently, + the product rows\*cols\*channels() must stay the same after the transformation. + - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of + rows, or the operation changes the indices of elements row in some other way, the matrix must be + continuous. See Mat::isContinuous . + + For example, if there is a set of 3D points stored as an STL vector, and you want to represent the + points as a 3xN matrix, do the following: + @code + std::vector vec; + ... + Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation + reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. + // Also, an O(1) operation + t(); // finally, transpose the Nx3 matrix. + // This involves copying all the elements + @endcode + @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + @param rows New number of rows. If the parameter is 0, the number of rows remains the same. + */ + Mat reshape(int cn, int rows=0) const; + + /** @overload */ + Mat reshape(int cn, int newndims, const int* newsz) const; + + /** @overload */ + Mat reshape(int cn, const std::vector& newshape) const; + + /** @brief Transposes a matrix. + + The method performs matrix transposition by means of matrix expressions. It does not perform the + actual transposition but returns a temporary matrix transposition object that can be further used as + a part of more complex matrix expressions or can be assigned to a matrix: + @code + Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; + Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) + @endcode + */ + MatExpr t() const; + + /** @brief Inverses a matrix. + + The method performs a matrix inversion by means of matrix expressions. This means that a temporary + matrix inversion object is returned by the method and can be used further as a part of more complex + matrix expressions or can be assigned to a matrix. + @param method Matrix inversion method. One of cv::DecompTypes + */ + MatExpr inv(int method=DECOMP_LU) const; + + /** @brief Performs an element-wise multiplication or division of the two matrices. + + The method returns a temporary object encoding per-element array multiplication, with optional + scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. + + Example: + @code + Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) + @endcode + @param m Another array of the same type and the same size as \*this, or a matrix expression. + @param scale Optional scale factor. + */ + MatExpr mul(InputArray m, double scale=1) const; + + /** @brief Computes a cross-product of two 3-element vectors. + + The method computes a cross-product of two 3-element vectors. The vectors must be 3-element + floating-point vectors of the same shape and size. The result is another 3-element vector of the + same shape and type as operands. + @param m Another cross-product operand. + */ + Mat cross(InputArray m) const; + + /** @brief Computes a dot-product of two vectors. + + The method computes a dot-product of two matrices. If the matrices are not single-column or + single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D + vectors. The vectors must have the same size and type. If the matrices have more than one channel, + the dot products from all the channels are summed together. + @param m another dot-product operand. + */ + double dot(InputArray m) const; + + /** @brief Returns a zero array of the specified size and type. + + The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant + array as a function parameter, part of a matrix expression, or as a matrix initializer: + @code + Mat A; + A = Mat::zeros(3, 3, CV_32F); + @endcode + In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. + Otherwise, the existing matrix A is filled with zeros. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + static MatExpr zeros(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + static MatExpr zeros(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + static MatExpr zeros(int ndims, const int* sz, int type); + + /** @brief Returns an array of all 1's of the specified size and type. + + The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using + this method you can initialize an array with an arbitrary value, using the following Matlab idiom: + @code + Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. + @endcode + The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it + just remembers the scale factor (3 in this case) and use it when actually invoking the matrix + initializer. + @note In case of multi-channels type, only the first channel will be initialized with 1's, the + others will be set to 0's. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + static MatExpr ones(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + static MatExpr ones(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + static MatExpr ones(int ndims, const int* sz, int type); + + /** @brief Returns an identity matrix of the specified size and type. + + The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to + Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: + @code + // make a 4x4 diagonal matrix with 0.1's on the diagonal. + Mat A = Mat::eye(4, 4, CV_32F)*0.1; + @endcode + @note In case of multi-channels type, identity matrix will be initialized only for the first channel, + the others will be set to 0's + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + static MatExpr eye(int rows, int cols, int type); + + /** @overload + @param size Alternative matrix size specification as Size(cols, rows) . + @param type Created matrix type. + */ + static MatExpr eye(Size size, int type); + + /** @brief Allocates new array data if needed. + + This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays + call this method for each output array. The method uses the following algorithm: + + -# If the current array shape and the type match the new ones, return immediately. Otherwise, + de-reference the previous data by calling Mat::release. + -# Initialize the new header. + -# Allocate the new data of total()\*elemSize() bytes. + -# Allocate the new, associated with the data, reference counter and set it to 1. + + Such a scheme makes the memory management robust and efficient at the same time and helps avoid + extra typing for you. This means that usually there is no need to explicitly allocate output arrays. + That is, instead of writing: + @code + Mat color; + ... + Mat gray(color.rows, color.cols, color.depth()); + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + you can simply write: + @code + Mat color; + ... + Mat gray; + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array + internally. + @param rows New number of rows. + @param cols New number of columns. + @param type New matrix type. + */ + void create(int rows, int cols, int type); + + /** @overload + @param size Alternative new matrix size specification: Size(cols, rows) + @param type New matrix type. + */ + void create(Size size, int type); + + /** @overload + @param ndims New array dimensionality. + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(int ndims, const int* sizes, int type); + + /** @overload + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(const std::vector& sizes, int type); + + /** @brief Increments the reference counter. + + The method increments the reference counter associated with the matrix data. If the matrix header + points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no + effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It + is called implicitly by the matrix assignment operator. The reference counter increment is an atomic + operation on the platforms that support it. Thus, it is safe to operate on the same matrices + asynchronously in different threads. + */ + void addref(); + + /** @brief Decrements the reference counter and deallocates the matrix if needed. + + The method decrements the reference counter associated with the matrix data. When the reference + counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers + are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the + reference counter is NULL, and the method has no effect in this case. + + This method can be called manually to force the matrix data deallocation. But since this method is + automatically called in the destructor, or by any other method that changes the data pointer, it is + usually not needed. The reference counter decrement and check for 0 is an atomic operation on the + platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in + different threads. + */ + void release(); + + //! internal use function, consider to use 'release' method instead; deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const Mat& m); + + /** @brief Reserves space for the certain number of rows. + + The method reserves space for sz rows. If the matrix already has enough space to store sz rows, + nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method + emulates the corresponding method of the STL vector class. + @param sz Number of rows. + */ + void reserve(size_t sz); + + /** @brief Reserves space for the certain number of bytes. + + The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, + nothing happens. If matrix has to be reallocated its previous content could be lost. + @param sz Number of bytes. + */ + void reserveBuffer(size_t sz); + + /** @brief Changes the number of matrix rows. + + The methods change the number of matrix rows. If the matrix is reallocated, the first + min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL + vector class. + @param sz New number of rows. + */ + void resize(size_t sz); + + /** @overload + @param sz New number of rows. + @param s Value assigned to the newly added elements. + */ + void resize(size_t sz, const Scalar& s); + + //! internal function + void push_back_(const void* elem); + + /** @brief Adds elements to the bottom of the matrix. + + The methods add one or more elements to the bottom of the matrix. They emulate the corresponding + method of the STL vector class. When elem is Mat , its type and the number of columns must be the + same as in the container matrix. + @param elem Added element(s). + */ + template void push_back(const _Tp& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const Mat_<_Tp>& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const std::vector<_Tp>& elem); + + /** @overload + @param m Added line(s). + */ + void push_back(const Mat& m); + + /** @brief Removes elements from the bottom of the matrix. + + The method removes one or more rows from the bottom of the matrix. + @param nelems Number of removed rows. If it is greater than the total number of rows, an exception + is thrown. + */ + void pop_back(size_t nelems=1); + + /** @brief Locates the matrix header within a parent matrix. + + After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, + Mat::colRange, and others, the resultant submatrix points just to the part of the original big + matrix. However, each submatrix contains information (represented by datastart and dataend + fields) that helps reconstruct the original matrix size and the position of the extracted + submatrix within the original matrix. The method locateROI does exactly that. + @param wholeSize Output parameter that contains the size of the whole matrix containing *this* + as a part. + @param ofs Output parameter that contains an offset of *this* inside the whole matrix. + */ + void locateROI( Size& wholeSize, Point& ofs ) const; + + /** @brief Adjusts a submatrix size and position within the parent matrix. + + The method is complimentary to Mat::locateROI . The typical use of these functions is to determine + the submatrix position within the parent matrix and then shift the position somehow. Typically, it + can be required for filtering operations when pixels outside of the ROI should be taken into + account. When all the method parameters are positive, the ROI needs to grow in all directions by the + specified amount, for example: + @code + A.adjustROI(2, 2, 2, 2); + @endcode + In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted + by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the + filtering with the 5x5 kernel. + + adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the + adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is + located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not + be increased in the upward direction. + + The function is used internally by the OpenCV filtering functions, like filter2D , morphological + operations, and so on. + @param dtop Shift of the top submatrix boundary upwards. + @param dbottom Shift of the bottom submatrix boundary downwards. + @param dleft Shift of the left submatrix boundary to the left. + @param dright Shift of the right submatrix boundary to the right. + @sa copyMakeBorder + */ + Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + + /** @brief Extracts a rectangular submatrix. + + The operators make a new header for the specified sub-array of \*this . They are the most + generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, + `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, + the operators are O(1) operations, that is, no matrix data is copied. + @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To + select all the rows, use Range::all(). + @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. + To select all the columns, use Range::all(). + */ + Mat operator()( Range rowRange, Range colRange ) const; + + /** @overload + @param roi Extracted submatrix specified as a rectangle. + */ + Mat operator()( const Rect& roi ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()( const Range* ranges ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()(const std::vector& ranges) const; + + // //! converts header to CvMat; no data is copied + // operator CvMat() const; + // //! converts header to CvMatND; no data is copied + // operator CvMatND() const; + // //! converts header to IplImage; no data is copied + // operator IplImage() const; + + template operator std::vector<_Tp>() const; + template operator Vec<_Tp, n>() const; + template operator Matx<_Tp, m, n>() const; + +#ifdef CV_CXX_STD_ARRAY + template operator std::array<_Tp, _Nm>() const; +#endif + + /** @brief Reports whether the matrix is continuous or not. + + The method returns true if the matrix elements are stored continuously without gaps at the end of + each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. + Matrices created with Mat::create are always continuous. But if you extract a part of the matrix + using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, + such matrices may no longer have this property. + + The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when + you construct a matrix header. Thus, the continuity check is a very fast operation, though + theoretically it could be done as follows: + @code + // alternative implementation of Mat::isContinuous() + bool myCheckMatContinuity(const Mat& m) + { + //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; + return m.rows == 1 || m.step == m.cols*m.elemSize(); + } + @endcode + The method is used in quite a few of OpenCV functions. The point is that element-wise operations + (such as arithmetic and logical operations, math functions, alpha blending, color space + transformations, and others) do not depend on the image geometry. Thus, if all the input and output + arrays are continuous, the functions can process them as very long single-row vectors. The example + below illustrates how an alpha-blending function can be implemented: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == CV_MAKETYPE(traits::Depth::value, 4) && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + // here is the idiom: check the arrays for continuity and, + // if this is the case, + // treat the arrays as 1D vectors + if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) + { + size.width *= size.height; + size.height = 1; + } + size.width *= 4; + + for( int i = 0; i < size.height; i++ ) + { + // when the arrays are continuous, + // the outer loop is executed only once + const T* ptr1 = src1.ptr(i); + const T* ptr2 = src2.ptr(i); + T* dptr = dst.ptr(i); + + for( int j = 0; j < size.width; j += 4 ) + { + float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; + dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); + dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); + dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); + dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); + } + } + } + @endcode + This approach, while being very simple, can boost the performance of a simple element-operation by + 10-20 percents, especially if the image is rather small and the operation is quite simple. + + Another OpenCV idiom in this function, a call of Mat::create for the destination array, that + allocates the destination array unless it already has the proper size and type. And while the newly + allocated arrays are always continuous, you still need to check the destination array because + Mat::create does not always allocate a new matrix. + */ + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + /** @brief Returns the matrix element size in bytes. + + The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , + the method returns 3\*sizeof(short) or 6. + */ + size_t elemSize() const; + + /** @brief Returns the size of each matrix element channel in bytes. + + The method returns the matrix element channel size in bytes, that is, it ignores the number of + channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. + */ + size_t elemSize1() const; + + /** @brief Returns the type of a matrix element. + + The method returns a matrix element type. This is an identifier compatible with the CvMat type + system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. + */ + int type() const; + + /** @brief Returns the depth of a matrix element. + + The method returns the identifier of the matrix element depth (the type of each individual channel). + For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of + matrix types contains the following values: + - CV_8U - 8-bit unsigned integers ( 0..255 ) + - CV_8S - 8-bit signed integers ( -128..127 ) + - CV_16U - 16-bit unsigned integers ( 0..65535 ) + - CV_16S - 16-bit signed integers ( -32768..32767 ) + - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) + - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) + - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) + */ + int depth() const; + + /** @brief Returns the number of matrix channels. + + The method returns the number of matrix channels. + */ + int channels() const; + + /** @brief Returns a normalized step. + + The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an + arbitrary matrix element. + */ + size_t step1(int i=0) const; + + /** @brief Returns true if the array has no elements. + + The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and + resize() methods `M.total() == 0` does not imply that `M.data == NULL`. + */ + bool empty() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of array elements (a number of pixels if the array represents an + image). + */ + size_t total() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim + */ + size_t total(int startDim, int endDim=INT_MAX) const; + + /** + * @param elemChannels Number of channels or number of columns the matrix should have. + * For a 2-D matrix, when the matrix has only 1 column, then it should have + * elemChannels channels; When the matrix has only 1 channel, + * then it should have elemChannels columns. + * For a 3-D matrix, it should have only one channel. Furthermore, + * if the number of planes is not one, then the number of rows + * within every plane has to be 1; if the number of rows within + * every plane is not 1, then the number of planes has to be 1. + * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. + * @param requireContinuous Set it to true to require the matrix to be continuous + * @return -1 if the requirement is not satisfied. + * Otherwise, it returns the number of elements in the matrix. Note + * that an element may have multiple channels. + * + * The following code demonstrates its usage for a 2-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-2d + * + * The following code demonstrates its usage for a 3-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-3d + */ + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + + /** @brief Returns a pointer to the specified matrix row. + + The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in + Mat::isContinuous to know how to use these methods. + @param i0 A 0-based row index. + */ + uchar* ptr(int i0=0); + /** @overload */ + const uchar* ptr(int i0=0) const; + + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + uchar* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + const uchar* ptr(int row, int col) const; + + /** @overload */ + uchar* ptr(int i0, int i1, int i2); + /** @overload */ + const uchar* ptr(int i0, int i1, int i2) const; + + /** @overload */ + uchar* ptr(const int* idx); + /** @overload */ + const uchar* ptr(const int* idx) const; + /** @overload */ + template uchar* ptr(const Vec& idx); + /** @overload */ + template const uchar* ptr(const Vec& idx) const; + + /** @overload */ + template _Tp* ptr(int i0=0); + /** @overload */ + template const _Tp* ptr(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp* ptr(int row, int col) const; + /** @overload */ + template _Tp* ptr(int i0, int i1, int i2); + /** @overload */ + template const _Tp* ptr(int i0, int i1, int i2) const; + /** @overload */ + template _Tp* ptr(const int* idx); + /** @overload */ + template const _Tp* ptr(const int* idx) const; + /** @overload */ + template _Tp* ptr(const Vec& idx); + /** @overload */ + template const _Tp* ptr(const Vec& idx) const; + + /** @brief Returns a reference to the specified array element. + + The template methods return a reference to the specified array element. For the sake of higher + performance, the index range checks are only performed in the Debug configuration. + + Note that the variants with a single index (i) can be used to access elements of single-row or + single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and + B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` + instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. + + The example below initializes a Hilbert matrix: + @code + Mat H(100, 100, CV_64F); + for(int i = 0; i < H.rows; i++) + for(int j = 0; j < H.cols; j++) + H.at(i,j)=1./(i+j+1); + @endcode + + Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends + on the image from which you are trying to retrieve the data. The table below gives a better insight in this: + - If matrix is of type `CV_8U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_8S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32F` then use `Mat.at(y,x)`. + - If matrix is of type `CV_64F` then use `Mat.at(y,x)`. + + @param i0 Index along the dimension 0 + */ + template _Tp& at(int i0=0); + /** @overload + @param i0 Index along the dimension 0 + */ + template const _Tp& at(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp& at(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp& at(int row, int col) const; + + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template _Tp& at(int i0, int i1, int i2); + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template const _Tp& at(int i0, int i1, int i2) const; + + /** @overload + @param idx Array of Mat::dims indices. + */ + template _Tp& at(const int* idx); + /** @overload + @param idx Array of Mat::dims indices. + */ + template const _Tp& at(const int* idx) const; + + /** @overload */ + template _Tp& at(const Vec& idx); + /** @overload */ + template const _Tp& at(const Vec& idx) const; + + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template _Tp& at(Point pt); + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template const _Tp& at(Point pt) const; + + /** @brief Returns the matrix iterator and sets it to the first matrix element. + + The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very + similar to the use of bi-directional STL iterators. In the example below, the alpha blending + function is rewritten using the matrix iterators: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + typedef Vec VT; + + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == traits::Type::value && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); + MatConstIterator_ it2 = src2.begin(); + MatIterator_ dst_it = dst.begin(); + + for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) + { + VT pix1 = *it1, pix2 = *it2; + float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; + *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), + saturate_cast(pix1[1]*alpha + pix2[1]*beta), + saturate_cast(pix1[2]*alpha + pix2[2]*beta), + saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); + } + } + @endcode + */ + template MatIterator_<_Tp> begin(); + template MatConstIterator_<_Tp> begin() const; + + /** @brief Returns the matrix iterator and sets it to the after-last matrix element. + + The methods return the matrix read-only or read-write iterators, set to the point following the last + matrix element. + */ + template MatIterator_<_Tp> end(); + template MatConstIterator_<_Tp> end() const; + + /** @brief Runs the given functor over all matrix elements in parallel. + + The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). + + Example 1. All of the operations below put 0xFF the first channel of all matrix elements: + @code + Mat image(1920, 1080, CV_8UC3); + typedef cv::Point3_ Pixel; + + // first. raw pointer access. + for (int r = 0; r < image.rows; ++r) { + Pixel* ptr = image.ptr(r, 0); + const Pixel* ptr_end = ptr + image.cols; + for (; ptr != ptr_end; ++ptr) { + ptr->x = 255; + } + } + + // Using MatIterator. (Simple but there are a Iterator's overhead) + for (Pixel &p : cv::Mat_(image)) { + p.x = 255; + } + + // Parallel execution with function object. + struct Operator { + void operator ()(Pixel &pixel, const int * position) { + pixel.x = 255; + } + }; + image.forEach(Operator()); + + // Parallel execution using C++11 lambda. + image.forEach([](Pixel &p, const int * position) -> void { + p.x = 255; + }); + @endcode + Example 2. Using the pixel's position: + @code + // Creating 3D matrix (255 x 255 x 255) typed uint8_t + // and initialize all elements by the value which equals elements position. + // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). + + int sizes[] = { 255, 255, 255 }; + typedef cv::Point3_ Pixel; + + Mat_ image = Mat::zeros(3, sizes, CV_8UC3); + + image.forEach([&](Pixel& pixel, const int position[]) -> void { + pixel.x = position[0]; + pixel.y = position[1]; + pixel.z = position[2]; + }); + @endcode + */ + template void forEach(const Functor& operation); + /** @overload */ + template void forEach(const Functor& operation) const; + +#ifdef CV_CXX_MOVE_SEMANTICS + Mat(Mat&& m); + Mat& operator = (Mat&& m); +#endif + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + //! the matrix dimensionality, >= 2 + int dims; + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows, cols; + //! pointer to the data + uchar* data; + + //! helper fields used in locateROI and adjustROI + const uchar* datastart; + const uchar* dataend; + const uchar* datalimit; + + //! custom allocator + MatAllocator* allocator; + //! and the standard allocator + static MatAllocator* getStdAllocator(); + static MatAllocator* getDefaultAllocator(); + static void setDefaultAllocator(MatAllocator* allocator); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + //! interaction with UMat + UMatData* u; + + MatSize size; + MatStep step; + +protected: + template void forEach_impl(const Functor& operation); +}; -template inline void -SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, - const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, - Matx<_Tp, n, nb>& dst ) -{ - assert( nm == MIN(m, n)); - Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); - SVD::backSubst(_w, _u, _vt, _rhs, _dst); - CV_Assert(_dst.data == (uchar*)&dst.val[0]); -} ///////////////////////////////// Mat_<_Tp> //////////////////////////////////// -template inline Mat_<_Tp>::Mat_() - : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; } +/** @brief Template matrix class derived from Mat -template inline Mat_<_Tp>::Mat_(int _rows, int _cols) - : Mat(_rows, _cols, DataType<_Tp>::type) {} - -template inline Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) - : Mat(_rows, _cols, DataType<_Tp>::type) { *this = value; } - -template inline Mat_<_Tp>::Mat_(Size _sz) - : Mat(_sz.height, _sz.width, DataType<_Tp>::type) {} - -template inline Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) - : Mat(_sz.height, _sz.width, DataType<_Tp>::type) { *this = value; } - -template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz) - : Mat(_dims, _sz, DataType<_Tp>::type) {} - -template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) - : Mat(_dims, _sz, DataType<_Tp>::type, Scalar(_s)) {} - -template inline Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) - : Mat(m, ranges) {} - -template inline Mat_<_Tp>::Mat_(const Mat& m) - : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; *this = m; } - -template inline Mat_<_Tp>::Mat_(const Mat_& m) - : Mat(m) {} - -template inline Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) - : Mat(_rows, _cols, DataType<_Tp>::type, _data, steps) {} - -template inline Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) - : Mat(m, _rowRange, _colRange) {} - -template inline Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) - : Mat(m, roi) {} - -template template inline - Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) - : Mat(n/DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&vec) -{ - CV_Assert(n%DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template template inline - Mat_<_Tp>::Mat_(const Matx::channel_type,m,n>& M, bool copyData) - : Mat(m, n/DataType<_Tp>::channels, DataType<_Tp>::type, (void*)&M) -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) - : Mat(2/DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt) -{ - CV_Assert(2 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) - : Mat(3/DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt) -{ - CV_Assert(3 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) - : Mat(commaInitializer) {} - -template inline Mat_<_Tp>::Mat_(const vector<_Tp>& vec, bool copyData) - : Mat(vec, copyData) {} - -template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) -{ - if( DataType<_Tp>::type == m.type() ) +@code{.cpp} + template class Mat_ : public Mat { - Mat::operator = (m); - return *this; - } - if( DataType<_Tp>::depth == m.depth() ) + public: + // ... some specific methods + // and + // no new extra fields + }; +@endcode +The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any +extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to +these two classes can be freely but carefully converted one to another. For example: +@code{.cpp} + // create a 100x100 8-bit matrix + Mat M(100,100,CV_8U); + // this will be compiled fine. no any data conversion will be done. + Mat_& M1 = (Mat_&)M; + // the program is likely to crash at the statement below + M1(99,99) = 1.f; +@endcode +While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element +access operations and if you know matrix type at the compilation time. Note that +`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same +and run at the same speed, but the latter is certainly shorter: +@code{.cpp} + Mat_ M(20,20); + for(int i = 0; i < M.rows; i++) + for(int j = 0; j < M.cols; j++) + M(i,j) = 1./(i+j+1); + Mat E, V; + eigen(M,E,V); + cout << E.at(0,0)/E.at(M.rows-1,0); +@endcode +To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: +@code{.cpp} + // allocate a 320x240 color image and fill it with green (in RGB space) + Mat_ img(240, 320, Vec3b(0,255,0)); + // now draw a diagonal white line + for(int i = 0; i < 100; i++) + img(i,i)=Vec3b(255,255,255); + // and now scramble the 2nd (red) channel of each pixel + for(int i = 0; i < img.rows; i++) + for(int j = 0; j < img.cols; j++) + img(i,j)[2] ^= (uchar)(i ^ j); +@endcode +Mat_ is fully compatible with C++11 range-based for loop. For example such loop +can be used to safely apply look-up table: +@code{.cpp} +void applyTable(Mat_& I, const uchar* const table) +{ + for(auto& pixel : I) { - return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); - } - CV_DbgAssert(DataType<_Tp>::channels == m.channels()); - m.convertTo(*this, type()); - return *this; -} - -template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) -{ - Mat::operator=(m); - return *this; -} - -template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) -{ - typedef typename DataType<_Tp>::vec_type VT; - Mat::operator=(Scalar((const VT&)s)); - return *this; -} - -template inline void Mat_<_Tp>::create(int _rows, int _cols) -{ - Mat::create(_rows, _cols, DataType<_Tp>::type); -} - -template inline void Mat_<_Tp>::create(Size _sz) -{ - Mat::create(_sz, DataType<_Tp>::type); -} - -template inline void Mat_<_Tp>::create(int _dims, const int* _sz) -{ - Mat::create(_dims, _sz, DataType<_Tp>::type); -} - - -template inline Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const -{ return Mat_<_Tp>(Mat::cross(m)); } - -template template inline Mat_<_Tp>::operator Mat_() const -{ return Mat_(*this); } - -template inline Mat_<_Tp> Mat_<_Tp>::row(int y) const -{ return Mat_(*this, Range(y, y+1), Range::all()); } -template inline Mat_<_Tp> Mat_<_Tp>::col(int x) const -{ return Mat_(*this, Range::all(), Range(x, x+1)); } -template inline Mat_<_Tp> Mat_<_Tp>::diag(int d) const -{ return Mat_(Mat::diag(d)); } -template inline Mat_<_Tp> Mat_<_Tp>::clone() const -{ return Mat_(Mat::clone()); } - -template inline size_t Mat_<_Tp>::elemSize() const -{ - CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); - return sizeof(_Tp); -} - -template inline size_t Mat_<_Tp>::elemSize1() const -{ - CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp)/DataType<_Tp>::channels ); - return sizeof(_Tp)/DataType<_Tp>::channels; -} -template inline int Mat_<_Tp>::type() const -{ - CV_DbgAssert( Mat::type() == DataType<_Tp>::type ); - return DataType<_Tp>::type; -} -template inline int Mat_<_Tp>::depth() const -{ - CV_DbgAssert( Mat::depth() == DataType<_Tp>::depth ); - return DataType<_Tp>::depth; -} -template inline int Mat_<_Tp>::channels() const -{ - CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); - return DataType<_Tp>::channels; -} -template inline size_t Mat_<_Tp>::stepT(int i) const { return step.p[i]/elemSize(); } -template inline size_t Mat_<_Tp>::step1(int i) const { return step.p[i]/elemSize1(); } - -template inline Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) -{ return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); } - -template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const -{ return Mat_<_Tp>(*this, _rowRange, _colRange); } - -template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const -{ return Mat_<_Tp>(*this, roi); } - -template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const -{ return Mat_<_Tp>(*this, ranges); } - -template inline _Tp* Mat_<_Tp>::operator [](int y) -{ return (_Tp*)ptr(y); } -template inline const _Tp* Mat_<_Tp>::operator [](int y) const -{ return (const _Tp*)ptr(y); } - -template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1) -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - type() == DataType<_Tp>::type ); - return ((_Tp*)(data + step.p[0]*i0))[i1]; -} - -template inline const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)i0 < (unsigned)size.p[0] && - (unsigned)i1 < (unsigned)size.p[1] && - type() == DataType<_Tp>::type ); - return ((const _Tp*)(data + step.p[0]*i0))[i1]; -} - -template inline _Tp& Mat_<_Tp>::operator ()(Point pt) -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)pt.y < (unsigned)size.p[0] && - (unsigned)pt.x < (unsigned)size.p[1] && - type() == DataType<_Tp>::type ); - return ((_Tp*)(data + step.p[0]*pt.y))[pt.x]; -} - -template inline const _Tp& Mat_<_Tp>::operator ()(Point pt) const -{ - CV_DbgAssert( dims <= 2 && data && - (unsigned)pt.y < (unsigned)size.p[0] && - (unsigned)pt.x < (unsigned)size.p[1] && - type() == DataType<_Tp>::type ); - return ((const _Tp*)(data + step.p[0]*pt.y))[pt.x]; -} - -template inline _Tp& Mat_<_Tp>::operator ()(const int* idx) -{ - return Mat::at<_Tp>(idx); -} - -template inline const _Tp& Mat_<_Tp>::operator ()(const int* idx) const -{ - return Mat::at<_Tp>(idx); -} - -template template inline _Tp& Mat_<_Tp>::operator ()(const Vec& idx) -{ - return Mat::at<_Tp>(idx); -} - -template template inline const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const -{ - return Mat::at<_Tp>(idx); -} - -template inline _Tp& Mat_<_Tp>::operator ()(int i0) -{ - return this->at<_Tp>(i0); -} - -template inline const _Tp& Mat_<_Tp>::operator ()(int i0) const -{ - return this->at<_Tp>(i0); -} - -template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) -{ - return this->at<_Tp>(i0, i1, i2); -} - -template inline const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const -{ - return this->at<_Tp>(i0, i1, i2); -} - - -template inline Mat_<_Tp>::operator vector<_Tp>() const -{ - vector<_Tp> v; - copyTo(v); - return v; -} - -template template inline Mat_<_Tp>::operator Vec::channel_type, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - return this->Mat::operator Vec::channel_type, n>(); -} - -template template inline Mat_<_Tp>::operator Matx::channel_type, m, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - - Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); - return res; -} - -template inline void -process( const Mat_& m1, Mat_& m2, Op op ) -{ - int y, x, rows = m1.rows, cols = m1.cols; - - CV_DbgAssert( m1.size() == m2.size() ); - - for( y = 0; y < rows; y++ ) - { - const T1* src = m1[y]; - T2* dst = m2[y]; - - for( x = 0; x < cols; x++ ) - dst[x] = op(src[x]); + pixel = table[pixel]; } } - -template inline void -process( const Mat_& m1, const Mat_& m2, Mat_& m3, Op op ) +@endcode + */ +template class Mat_ : public Mat { - int y, x, rows = m1.rows, cols = m1.cols; +public: + typedef _Tp value_type; + typedef typename DataType<_Tp>::channel_type channel_type; + typedef MatIterator_<_Tp> iterator; + typedef MatConstIterator_<_Tp> const_iterator; - CV_DbgAssert( m1.size() == m2.size() ); + //! default constructor + Mat_(); + //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) + Mat_(int _rows, int _cols); + //! constructor that sets each matrix element to specified value + Mat_(int _rows, int _cols, const _Tp& value); + //! equivalent to Mat(_size, DataType<_Tp>::type) + explicit Mat_(Size _size); + //! constructor that sets each matrix element to specified value + Mat_(Size _size, const _Tp& value); + //! n-dim array constructor + Mat_(int _ndims, const int* _sizes); + //! n-dim array constructor that sets each matrix element to specified value + Mat_(int _ndims, const int* _sizes, const _Tp& value); + //! copy/conversion constructor. If m is of different type, it's converted + Mat_(const Mat& m); + //! copy constructor + Mat_(const Mat_& m); + //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type + Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); + //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type + Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); + //! selects a submatrix + Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); + //! selects a submatrix + Mat_(const Mat_& m, const Rect& roi); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const Range* ranges); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const std::vector& ranges); + //! from a matrix expression + explicit Mat_(const MatExpr& e); + //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column + explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); + template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); + template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); + explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); + explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); + explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); - for( y = 0; y < rows; y++ ) +#ifdef CV_CXX11 + Mat_(std::initializer_list<_Tp> values); + explicit Mat_(const std::initializer_list sizes, const std::initializer_list<_Tp> values); +#endif + +#ifdef CV_CXX_STD_ARRAY + template explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); +#endif + + Mat_& operator = (const Mat& m); + Mat_& operator = (const Mat_& m); + //! set all the elements to s. + Mat_& operator = (const _Tp& s); + //! assign a matrix expression + Mat_& operator = (const MatExpr& e); + + //! iterators; they are smart enough to skip gaps in the end of rows + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + //! template methods for for operation over all matrix elements. + // the operations take care of skipping gaps in the end of rows (if any) + template void forEach(const Functor& operation); + template void forEach(const Functor& operation) const; + + //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) + void create(int _rows, int _cols); + //! equivalent to Mat::create(_size, DataType<_Tp>::type) + void create(Size _size); + //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) + void create(int _ndims, const int* _sizes); + //! equivalent to Mat::release() + void release(); + //! cross-product + Mat_ cross(const Mat_& m) const; + //! data type conversion + template operator Mat_() const; + //! overridden forms of Mat::row() etc. + Mat_ row(int y) const; + Mat_ col(int x) const; + Mat_ diag(int d=0) const; + Mat_ clone() const CV_NODISCARD; + + //! overridden forms of Mat::elemSize() etc. + size_t elemSize() const; + size_t elemSize1() const; + int type() const; + int depth() const; + int channels() const; + size_t step1(int i=0) const; + //! returns step()/sizeof(_Tp) + size_t stepT(int i=0) const; + + //! overridden forms of Mat::zeros() etc. Data type is omitted, of course + static MatExpr zeros(int rows, int cols); + static MatExpr zeros(Size size); + static MatExpr zeros(int _ndims, const int* _sizes); + static MatExpr ones(int rows, int cols); + static MatExpr ones(Size size); + static MatExpr ones(int _ndims, const int* _sizes); + static MatExpr eye(int rows, int cols); + static MatExpr eye(Size size); + + //! some more overridden methods + Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); + Mat_ operator()( const Range& rowRange, const Range& colRange ) const; + Mat_ operator()( const Rect& roi ) const; + Mat_ operator()( const Range* ranges ) const; + Mat_ operator()(const std::vector& ranges) const; + + //! more convenient forms of row and element access operators + _Tp* operator [](int y); + const _Tp* operator [](int y) const; + + //! returns reference to the specified element + _Tp& operator ()(const int* idx); + //! returns read-only reference to the specified element + const _Tp& operator ()(const int* idx) const; + + //! returns reference to the specified element + template _Tp& operator ()(const Vec& idx); + //! returns read-only reference to the specified element + template const _Tp& operator ()(const Vec& idx) const; + + //! returns reference to the specified element (1D case) + _Tp& operator ()(int idx0); + //! returns read-only reference to the specified element (1D case) + const _Tp& operator ()(int idx0) const; + //! returns reference to the specified element (2D case) + _Tp& operator ()(int row, int col); + //! returns read-only reference to the specified element (2D case) + const _Tp& operator ()(int row, int col) const; + //! returns reference to the specified element (3D case) + _Tp& operator ()(int idx0, int idx1, int idx2); + //! returns read-only reference to the specified element (3D case) + const _Tp& operator ()(int idx0, int idx1, int idx2) const; + + _Tp& operator ()(Point pt); + const _Tp& operator ()(Point pt) const; + + //! conversion to vector. + operator std::vector<_Tp>() const; + +#ifdef CV_CXX_STD_ARRAY + //! conversion to array. + template operator std::array<_Tp, _Nm>() const; +#endif + + //! conversion to Vec + template operator Vec::channel_type, n>() const; + //! conversion to Matx + template operator Matx::channel_type, m, n>() const; + +#ifdef CV_CXX_MOVE_SEMANTICS + Mat_(Mat_&& m); + Mat_& operator = (Mat_&& m); + + Mat_(Mat&& m); + Mat_& operator = (Mat&& m); + + Mat_(MatExpr&& e); +#endif +}; + +typedef Mat_ Mat1b; +typedef Mat_ Mat2b; +typedef Mat_ Mat3b; +typedef Mat_ Mat4b; + +typedef Mat_ Mat1s; +typedef Mat_ Mat2s; +typedef Mat_ Mat3s; +typedef Mat_ Mat4s; + +typedef Mat_ Mat1w; +typedef Mat_ Mat2w; +typedef Mat_ Mat3w; +typedef Mat_ Mat4w; + +typedef Mat_ Mat1i; +typedef Mat_ Mat2i; +typedef Mat_ Mat3i; +typedef Mat_ Mat4i; + +typedef Mat_ Mat1f; +typedef Mat_ Mat2f; +typedef Mat_ Mat3f; +typedef Mat_ Mat4f; + +typedef Mat_ Mat1d; +typedef Mat_ Mat2d; +typedef Mat_ Mat3d; +typedef Mat_ Mat4d; + +/** @todo document */ +class CV_EXPORTS UMat +{ +public: + //! default constructor + UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT); + //! constructs 2D matrix of the specified size and type + // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) + UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + //! constucts 2D matrix and fills it with the specified value _s. + UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! constructs n-dimensional matrix + UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! copy constructor + UMat(const UMat& m); + + //! creates a matrix header for a part of the bigger matrix + UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); + UMat(const UMat& m, const Rect& roi); + UMat(const UMat& m, const Range* ranges); + UMat(const UMat& m, const std::vector& ranges); + //! builds matrix from std::vector with or without copying the data + template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); + + //! builds matrix from cv::Vec; the data is copied by default + template explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true); + //! builds matrix from cv::Matx; the data is copied by default + template explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true); + //! builds matrix from a 2D point + template explicit UMat(const Point_<_Tp>& pt, bool copyData=true); + //! builds matrix from a 3D point + template explicit UMat(const Point3_<_Tp>& pt, bool copyData=true); + //! builds matrix from comma initializer + template explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer); + + //! destructor - calls release() + ~UMat(); + //! assignment operators + UMat& operator = (const UMat& m); + + Mat getMat(int flags) const; + + //! returns a new matrix header for the specified row + UMat row(int y) const; + //! returns a new matrix header for the specified column + UMat col(int x) const; + //! ... for the specified row span + UMat rowRange(int startrow, int endrow) const; + UMat rowRange(const Range& r) const; + //! ... for the specified column span + UMat colRange(int startcol, int endcol) const; + UMat colRange(const Range& r) const; + //! ... for the specified diagonal + //! (d=0 - the main diagonal, + //! >0 - a diagonal from the upper half, + //! <0 - a diagonal from the lower half) + UMat diag(int d=0) const; + //! constructs a square diagonal matrix which main diagonal is vector "d" + static UMat diag(const UMat& d); + + //! returns deep copy of the matrix, i.e. the data is copied + UMat clone() const CV_NODISCARD; + //! copies the matrix content to "m". + // It calls m.create(this->size(), this->type()). + void copyTo( OutputArray m ) const; + //! copies those matrix elements to "m" that are marked with non-zero mask elements. + void copyTo( OutputArray m, InputArray mask ) const; + //! converts matrix to another datatype with optional scaling. See cvConvertScale. + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + void assignTo( UMat& m, int type=-1 ) const; + + //! sets every matrix element to s + UMat& operator = (const Scalar& s); + //! sets some of the matrix elements to s, according to the mask + UMat& setTo(InputArray value, InputArray mask=noArray()); + //! creates alternative matrix header for the same data, with different + // number of channels and/or different number of rows. see cvReshape. + UMat reshape(int cn, int rows=0) const; + UMat reshape(int cn, int newndims, const int* newsz) const; + + //! matrix transposition by means of matrix expressions + UMat t() const; + //! matrix inversion by means of matrix expressions + UMat inv(int method=DECOMP_LU) const; + //! per-element matrix multiplication by means of matrix expressions + UMat mul(InputArray m, double scale=1) const; + + //! computes dot-product + double dot(InputArray m) const; + + //! Matlab-style matrix initialization + static UMat zeros(int rows, int cols, int type); + static UMat zeros(Size size, int type); + static UMat zeros(int ndims, const int* sz, int type); + static UMat ones(int rows, int cols, int type); + static UMat ones(Size size, int type); + static UMat ones(int ndims, const int* sz, int type); + static UMat eye(int rows, int cols, int type); + static UMat eye(Size size, int type); + + //! allocates new matrix data unless the matrix already has specified size and type. + // previous data is unreferenced if needed. + void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(const std::vector& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! increases the reference counter; use with care to avoid memleaks + void addref(); + //! decreases reference counter; + // deallocates the data when reference counter reaches 0. + void release(); + + //! deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const UMat& m); + + //! locates matrix header within a parent matrix. See below + void locateROI( Size& wholeSize, Point& ofs ) const; + //! moves/resizes the current matrix ROI inside the parent matrix. + UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + //! extracts a rectangular sub-matrix + // (this is a generalized form of row, rowRange etc.) + UMat operator()( Range rowRange, Range colRange ) const; + UMat operator()( const Rect& roi ) const; + UMat operator()( const Range* ranges ) const; + UMat operator()(const std::vector& ranges) const; + + //! returns true iff the matrix data is continuous + // (i.e. when there are no gaps between successive rows). + // similar to CV_IS_MAT_CONT(cvmat->type) + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + //! returns element size in bytes, + // similar to CV_ELEM_SIZE(cvmat->type) + size_t elemSize() const; + //! returns the size of element channel in bytes. + size_t elemSize1() const; + //! returns element type, similar to CV_MAT_TYPE(cvmat->type) + int type() const; + //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) + int depth() const; + //! returns element type, similar to CV_MAT_CN(cvmat->type) + int channels() const; + //! returns step/elemSize1() + size_t step1(int i=0) const; + //! returns true if matrix data is NULL + bool empty() const; + //! returns the total number of matrix elements + size_t total() const; + + //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + +#ifdef CV_CXX_MOVE_SEMANTICS + UMat(UMat&& m); + UMat& operator = (UMat&& m); +#endif + + /*! Returns the OpenCL buffer handle on which UMat operates on. + The UMat instance should be kept alive during the use of the handle to prevent the buffer to be + returned to the OpenCV buffer pool. + */ + void* handle(int accessFlags) const; + void ndoffset(size_t* ofs) const; + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + //! the matrix dimensionality, >= 2 + int dims; + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows, cols; + + //! custom allocator + MatAllocator* allocator; + UMatUsageFlags usageFlags; // usage flags for allocator + //! and the standard allocator + static MatAllocator* getStdAllocator(); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + // black-box container of UMat data + UMatData* u; + + // offset of the submatrix (or 0) + size_t offset; + + MatSize size; + MatStep step; + +protected: +}; + + +/////////////////////////// multi-dimensional sparse matrix ////////////////////////// + +/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. + +Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only +non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its +stored elements can actually become 0. It is up to you to detect such elements and delete them +using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is +filled so that the search time is O(1) in average (regardless of whether element is there or not). +Elements can be accessed using the following methods: +- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and + SparseMat::find), for example: + @code + const int dims = 5; + int size[5] = {10, 10, 10, 10, 10}; + SparseMat sparse_mat(dims, size, CV_32F); + for(int i = 0; i < 1000; i++) + { + int idx[dims]; + for(int k = 0; k < dims; k++) + idx[k] = rand() % size[k]; + sparse_mat.ref(idx) += 1.f; + } + cout << "nnz = " << sparse_mat.nzcount() << endl; + @endcode +- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. + That is, the iteration loop is familiar to STL users: + @code + // prints elements of a sparse floating-point matrix + // and the sum of elements. + SparseMatConstIterator_ + it = sparse_mat.begin(), + it_end = sparse_mat.end(); + double s = 0; + int dims = sparse_mat.dims(); + for(; it != it_end; ++it) + { + // print element indices and the element value + const SparseMat::Node* n = it.node(); + printf("("); + for(int i = 0; i < dims; i++) + printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); + printf(": %g\n", it.value()); + s += *it; + } + printf("Element sum is %g\n", s); + @endcode + If you run this loop, you will notice that elements are not enumerated in a logical order + (lexicographical, and so on). They come in the same order as they are stored in the hash table + (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. + Note, however, that pointers to the nodes may become invalid when you add more elements to the + matrix. This may happen due to possible buffer reallocation. +- Combination of the above 2 methods when you need to process 2 or more sparse matrices + simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 + floating-point sparse matrices: + @code + double cross_corr(const SparseMat& a, const SparseMat& b) + { + const SparseMat *_a = &a, *_b = &b; + // if b contains less elements than a, + // it is faster to iterate through b + if(_a->nzcount() > _b->nzcount()) + std::swap(_a, _b); + SparseMatConstIterator_ it = _a->begin(), + it_end = _a->end(); + double ccorr = 0; + for(; it != it_end; ++it) + { + // take the next element from the first matrix + float avalue = *it; + const Node* anode = it.node(); + // and try to find an element with the same index in the second matrix. + // since the hash value depends only on the element index, + // reuse the hash value stored in the node + float bvalue = _b->value(anode->idx,&anode->hashval); + ccorr += avalue*bvalue; + } + return ccorr; + } + @endcode + */ +class CV_EXPORTS SparseMat +{ +public: + typedef SparseMatIterator iterator; + typedef SparseMatConstIterator const_iterator; + + enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; + + //! the sparse matrix header + struct CV_EXPORTS Hdr { - const T1* src1 = m1[y]; - const T2* src2 = m2[y]; - T3* dst = m3[y]; + Hdr(int _dims, const int* _sizes, int _type); + void clear(); + int refcount; + int dims; + int valueOffset; + size_t nodeSize; + size_t nodeCount; + size_t freeList; + std::vector pool; + std::vector hashtab; + int size[MAX_DIM]; + }; - for( x = 0; x < cols; x++ ) - dst[x] = op( src1[x], src2[x] ); + //! sparse matrix node - element of a hash table + struct CV_EXPORTS Node + { + //! hash value + size_t hashval; + //! index of the next node in the same hash table entry + size_t next; + //! index of the matrix element + int idx[MAX_DIM]; + }; + + /** @brief Various SparseMat constructors. + */ + SparseMat(); + + /** @overload + @param dims Array dimensionality. + @param _sizes Sparce matrix size on all dementions. + @param _type Sparse matrix data type. + */ + SparseMat(int dims, const int* _sizes, int _type); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + SparseMat(const SparseMat& m); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + explicit SparseMat(const Mat& m); + + //! the destructor + ~SparseMat(); + + //! assignment operator. This is O(1) operation, i.e. no data is copied + SparseMat& operator = (const SparseMat& m); + //! equivalent to the corresponding constructor + SparseMat& operator = (const Mat& m); + + //! creates full copy of the matrix + SparseMat clone() const CV_NODISCARD; + + //! copies all the data to the destination matrix. All the previous content of m is erased + void copyTo( SparseMat& m ) const; + //! converts sparse matrix to dense matrix. + void copyTo( Mat& m ) const; + //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type + void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; + //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. + /*! + @param [out] m - output matrix; if it does not have a proper size or type before the operation, + it is reallocated + @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels + are the same as the input has; if rtype is negative, the output matrix will have the + same type as the input. + @param [in] alpha - optional scale factor + @param [in] beta - optional delta added to the scaled values + */ + void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; + + // not used now + void assignTo( SparseMat& m, int type=-1 ) const; + + //! reallocates sparse matrix. + /*! + If the matrix already had the proper size and type, + it is simply cleared with clear(), otherwise, + the old matrix is released (using release()) and the new one is allocated. + */ + void create(int dims, const int* _sizes, int _type); + //! sets all the sparse matrix elements to 0, which means clearing the hash table. + void clear(); + //! manually increments the reference counter to the header. + void addref(); + // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. + void release(); + + //! converts sparse matrix to the old-style representation; all the elements are copied. + //operator CvSparseMat*() const; + //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) + size_t elemSize() const; + //! returns elemSize()/channels() + size_t elemSize1() const; + + //! returns type of sparse matrix elements + int type() const; + //! returns the depth of sparse matrix elements + int depth() const; + //! returns the number of channels + int channels() const; + + //! returns the array of sizes, or NULL if the matrix is not allocated + const int* size() const; + //! returns the size of i-th matrix dimension (or 0) + int size(int i) const; + //! returns the matrix dimensionality + int dims() const; + //! returns the number of non-zero elements (=the number of hash table nodes) + size_t nzcount() const; + + //! computes the element hash value (1D case) + size_t hash(int i0) const; + //! computes the element hash value (2D case) + size_t hash(int i0, int i1) const; + //! computes the element hash value (3D case) + size_t hash(int i0, int i1, int i2) const; + //! computes the element hash value (nD case) + size_t hash(const int* idx) const; + + //!@{ + /*! + specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. + return pointer to the matrix element. + - if the element is there (it's non-zero), the pointer to it is returned + - if it's not there and createMissing=false, NULL pointer is returned + - if it's not there and createMissing=true, then the new element + is created and initialized with 0. Pointer to it is returned + - if the optional hashval pointer is not NULL, the element hash value is + not computed, but *hashval is taken instead. + */ + //! returns pointer to the specified element (1D case) + uchar* ptr(int i0, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (2D case) + uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (3D case) + uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (nD case) + uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); + //!@} + + //!@{ + /*! + return read-write reference to the specified sparse matrix element. + + `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. + The methods always return a valid reference. + If the element did not exist, it is created and initialiazed with 0. + */ + //! returns reference to the specified element (1D case) + template _Tp& ref(int i0, size_t* hashval=0); + //! returns reference to the specified element (2D case) + template _Tp& ref(int i0, int i1, size_t* hashval=0); + //! returns reference to the specified element (3D case) + template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! returns reference to the specified element (nD case) + template _Tp& ref(const int* idx, size_t* hashval=0); + //!@} + + //!@{ + /*! + return value of the specified sparse matrix element. + + `value<_Tp>(i0,...[,hashval])` is equivalent to + @code + { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } + @endcode + + That is, if the element did not exist, the methods return 0. + */ + //! returns value of the specified element (1D case) + template _Tp value(int i0, size_t* hashval=0) const; + //! returns value of the specified element (2D case) + template _Tp value(int i0, int i1, size_t* hashval=0) const; + //! returns value of the specified element (3D case) + template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns value of the specified element (nD case) + template _Tp value(const int* idx, size_t* hashval=0) const; + //!@} + + //!@{ + /*! + Return pointer to the specified sparse matrix element if it exists + + `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. + + If the specified element does not exist, the methods return NULL. + */ + //! returns pointer to the specified element (1D case) + template const _Tp* find(int i0, size_t* hashval=0) const; + //! returns pointer to the specified element (2D case) + template const _Tp* find(int i0, int i1, size_t* hashval=0) const; + //! returns pointer to the specified element (3D case) + template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns pointer to the specified element (nD case) + template const _Tp* find(const int* idx, size_t* hashval=0) const; + //!@} + + //! erases the specified element (2D case) + void erase(int i0, int i1, size_t* hashval=0); + //! erases the specified element (3D case) + void erase(int i0, int i1, int i2, size_t* hashval=0); + //! erases the specified element (nD case) + void erase(const int* idx, size_t* hashval=0); + + //!@{ + /*! + return the sparse matrix iterator pointing to the first sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix beginning + SparseMatIterator begin(); + //! returns the sparse matrix iterator at the matrix beginning + template SparseMatIterator_<_Tp> begin(); + //! returns the read-only sparse matrix iterator at the matrix beginning + SparseMatConstIterator begin() const; + //! returns the read-only sparse matrix iterator at the matrix beginning + template SparseMatConstIterator_<_Tp> begin() const; + //!@} + /*! + return the sparse matrix iterator pointing to the element following the last sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix end + SparseMatIterator end(); + //! returns the read-only sparse matrix iterator at the matrix end + SparseMatConstIterator end() const; + //! returns the typed sparse matrix iterator at the matrix end + template SparseMatIterator_<_Tp> end(); + //! returns the typed read-only sparse matrix iterator at the matrix end + template SparseMatConstIterator_<_Tp> end() const; + + //! returns the value stored in the sparse martix node + template _Tp& value(Node* n); + //! returns the value stored in the sparse martix node + template const _Tp& value(const Node* n) const; + + ////////////// some internal-use methods /////////////// + Node* node(size_t nidx); + const Node* node(size_t nidx) const; + + uchar* newNode(const int* idx, size_t hashval); + void removeNode(size_t hidx, size_t nidx, size_t previdx); + void resizeHashTab(size_t newsize); + + int flags; + Hdr* hdr; +}; + + + +///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// + +/** @brief Template sparse n-dimensional array class derived from SparseMat + +SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies +notation of some operations: +@code + int sz[] = {10, 20, 30}; + SparseMat_ M(3, sz); + ... + M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); +@endcode + */ +template class SparseMat_ : public SparseMat +{ +public: + typedef SparseMatIterator_<_Tp> iterator; + typedef SparseMatConstIterator_<_Tp> const_iterator; + + //! the default constructor + SparseMat_(); + //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) + SparseMat_(int dims, const int* _sizes); + //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_(const SparseMat& m); + //! the copy constructor. This is O(1) operation - no data is copied + SparseMat_(const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_(const Mat& m); + //! converts the old-style sparse matrix to the C++ class. All the elements are copied + //SparseMat_(const CvSparseMat* m); + //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_& operator = (const SparseMat& m); + //! the assignment operator. This is O(1) operation - no data is copied + SparseMat_& operator = (const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_& operator = (const Mat& m); + + //! makes full copy of the matrix. All the elements are duplicated + SparseMat_ clone() const CV_NODISCARD; + //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) + void create(int dims, const int* _sizes); + //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied + //operator CvSparseMat*() const; + + //! returns type of the matrix elements + int type() const; + //! returns depth of the matrix elements + int depth() const; + //! returns the number of channels in each matrix element + int channels() const; + + //! equivalent to SparseMat::ref<_Tp>(i0, hashval) + _Tp& ref(int i0, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) + _Tp& ref(int i0, int i1, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) + _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(idx, hashval) + _Tp& ref(const int* idx, size_t* hashval=0); + + //! equivalent to SparseMat::value<_Tp>(i0, hashval) + _Tp operator()(int i0, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) + _Tp operator()(int i0, int i1, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) + _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(idx, hashval) + _Tp operator()(const int* idx, size_t* hashval=0) const; + + //! returns sparse matrix iterator pointing to the first sparse matrix element + SparseMatIterator_<_Tp> begin(); + //! returns read-only sparse matrix iterator pointing to the first sparse matrix element + SparseMatConstIterator_<_Tp> begin() const; + //! returns sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatIterator_<_Tp> end(); + //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatConstIterator_<_Tp> end() const; +}; + + + +////////////////////////////////// MatConstIterator ////////////////////////////////// + +class CV_EXPORTS MatConstIterator +{ +public: + typedef uchar* value_type; + typedef ptrdiff_t difference_type; + typedef const uchar** pointer; + typedef uchar* reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator(const Mat* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, const int* _idx); + //! copy constructor + MatConstIterator(const MatConstIterator& it); + + //! copy operator + MatConstIterator& operator = (const MatConstIterator& it); + //! returns the current matrix element + const uchar* operator *() const; + //! returns the i-th matrix element, relative to the current + const uchar* operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator& operator --(); + //! decrements the iterator + MatConstIterator operator --(int); + //! increments the iterator + MatConstIterator& operator ++(); + //! increments the iterator + MatConstIterator operator ++(int); + //! returns the current iterator position + Point pos() const; + //! returns the current iterator position + void pos(int* _idx) const; + + ptrdiff_t lpos() const; + void seek(ptrdiff_t ofs, bool relative = false); + void seek(const int* _idx, bool relative = false); + + const Mat* m; + size_t elemSize; + const uchar* ptr; + const uchar* sliceStart; + const uchar* sliceEnd; +}; + + + +////////////////////////////////// MatConstIterator_ ///////////////////////////////// + +/** @brief Matrix read-only iterator + */ +template +class MatConstIterator_ : public MatConstIterator +{ +public: + typedef _Tp value_type; + typedef ptrdiff_t difference_type; + typedef const _Tp* pointer; + typedef const _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator_(const Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatConstIterator_(const MatConstIterator_& it); + + //! copy operator + MatConstIterator_& operator = (const MatConstIterator_& it); + //! returns the current matrix element + const _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + const _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator_& operator --(); + //! decrements the iterator + MatConstIterator_ operator --(int); + //! increments the iterator + MatConstIterator_& operator ++(); + //! increments the iterator + MatConstIterator_ operator ++(int); + //! returns the current iterator position + Point pos() const; +}; + + + +//////////////////////////////////// MatIterator_ //////////////////////////////////// + +/** @brief Matrix read-write iterator +*/ +template +class MatIterator_ : public MatConstIterator_<_Tp> +{ +public: + typedef _Tp* pointer; + typedef _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! the default constructor + MatIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatIterator_(Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatIterator_(const MatIterator_& it); + //! copy operator + MatIterator_& operator = (const MatIterator_<_Tp>& it ); + + //! returns the current matrix element + _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatIterator_& operator --(); + //! decrements the iterator + MatIterator_ operator --(int); + //! increments the iterator + MatIterator_& operator ++(); + //! increments the iterator + MatIterator_ operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator /////////////////////////////// + +/** @brief Read-Only Sparse Matrix Iterator. + + Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: + + \code + SparseMatConstIterator it = m.begin(), it_end = m.end(); + double s = 0; + CV_Assert( m.type() == CV_32F ); + for( ; it != it_end; ++it ) + s += it.value(); + \endcode +*/ +class CV_EXPORTS SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatConstIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator(const SparseMatConstIterator& it); + + //! the assignment operator + SparseMatConstIterator& operator = (const SparseMatConstIterator& it); + + //! template method returning the current matrix element + template const _Tp& value() const; + //! returns the current node of the sparse matrix. it.node->idx is the current element index + const SparseMat::Node* node() const; + + //! moves iterator to the previous element + SparseMatConstIterator& operator --(); + //! moves iterator to the previous element + SparseMatConstIterator operator --(int); + //! moves iterator to the next element + SparseMatConstIterator& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator operator ++(int); + + //! moves iterator to the element after the last element + void seekEnd(); + + const SparseMat* m; + size_t hashidx; + uchar* ptr; +}; + + + +////////////////////////////////// SparseMatIterator ///////////////////////////////// + +/** @brief Read-write Sparse Matrix Iterator + + The class is similar to cv::SparseMatConstIterator, + but can be used for in-place modification of the matrix elements. +*/ +class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator(SparseMat* _m); + //! the full constructor setting the iterator to the specified sparse matrix element + SparseMatIterator(SparseMat* _m, const int* idx); + //! the copy constructor + SparseMatIterator(const SparseMatIterator& it); + + //! the assignment operator + SparseMatIterator& operator = (const SparseMatIterator& it); + //! returns read-write reference to the current sparse matrix element + template _Tp& value() const; + //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) + SparseMat::Node* node() const; + + //! moves iterator to the next element + SparseMatIterator& operator ++(); + //! moves iterator to the next element + SparseMatIterator operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator_ ////////////////////////////// + +/** @brief Template Read-Only Sparse Matrix Iterator Class. + + This is the derived from SparseMatConstIterator class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatConstIterator_ : public SparseMatConstIterator +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatConstIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator_(const SparseMat_<_Tp>* _m); + SparseMatConstIterator_(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator_(const SparseMatConstIterator_& it); + + //! the assignment operator + SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); + //! the element access operator + const _Tp& operator *() const; + + //! moves iterator to the next element + SparseMatConstIterator_& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator_ operator ++(int); +}; + + + +///////////////////////////////// SparseMatIterator_ ///////////////////////////////// + +/** @brief Template Read-Write Sparse Matrix Iterator Class. + + This is the derived from cv::SparseMatConstIterator_ class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator_(SparseMat_<_Tp>* _m); + SparseMatIterator_(SparseMat* _m); + //! the copy constructor + SparseMatIterator_(const SparseMatIterator_& it); + + //! the assignment operator + SparseMatIterator_& operator = (const SparseMatIterator_& it); + //! returns the reference to the current element + _Tp& operator *() const; + + //! moves the iterator to the next element + SparseMatIterator_& operator ++(); + //! moves the iterator to the next element + SparseMatIterator_ operator ++(int); +}; + + + +/////////////////////////////////// NAryMatIterator ////////////////////////////////// + +/** @brief n-ary multi-dimensional array iterator. + +Use the class to implement unary, binary, and, generally, n-ary element-wise operations on +multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some +may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of +the iterators after each small operations may be a big overhead. In this case consider using +NAryMatIterator to iterate through several matrices simultaneously as long as they have the same +geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, +`it.planes[1]`,... will be the slices of the corresponding matrices. + +The example below illustrates how you can compute a normalized and threshold 3D color histogram: +@code + void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) + { + const int histSize[] = {N, N, N}; + + // make sure that the histogram has a proper size and type + hist.create(3, histSize, CV_32F); + + // and clear it + hist = Scalar(0); + + // the loop below assumes that the image + // is a 8-bit 3-channel. check it. + CV_Assert(image.type() == CV_8UC3); + MatConstIterator_ it = image.begin(), + it_end = image.end(); + for( ; it != it_end; ++it ) + { + const Vec3b& pix = *it; + hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; + } + + minProb *= image.rows*image.cols; + + // initialize iterator (the style is different from STL). + // after initialization the iterator will contain + // the number of slices or planes the iterator will go through. + // it simultaneously increments iterators for several matrices + // supplied as a null terminated list of pointers + const Mat* arrays[] = {&hist, 0}; + Mat planes[1]; + NAryMatIterator itNAry(arrays, planes, 1); + double s = 0; + // iterate through the matrix. on each iteration + // itNAry.planes[i] (of type Mat) will be set to the current plane + // of the i-th n-dim matrix passed to the iterator constructor. + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + { + threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); + s += sum(itNAry.planes[0])[0]; + } + + s = 1./s; + itNAry = NAryMatIterator(arrays, planes, 1); + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + itNAry.planes[0] *= s; } -} +@endcode + */ +class CV_EXPORTS NAryMatIterator +{ +public: + //! the default constructor + NAryMatIterator(); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); + //! the separate iterator initialization method + void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); + + //! proceeds to the next plane of every iterated matrix + NAryMatIterator& operator ++(); + //! proceeds to the next plane of every iterated matrix (postfix increment operator) + NAryMatIterator operator ++(int); + + //! the iterated arrays + const Mat** arrays; + //! the current planes + Mat* planes; + //! data pointers + uchar** ptrs; + //! the number of arrays + int narrays; + //! the number of hyper-planes that the iterator steps through + size_t nplanes; + //! the size of each segment (in elements) + size_t size; +protected: + int iterdepth; + size_t idx; +}; -/////////////////////////////// Input/Output Arrays ///////////////////////////////// -template inline _InputArray::_InputArray(const vector<_Tp>& vec) - : flags(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} - -template inline _InputArray::_InputArray(const vector >& vec) - : flags(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} - -template inline _InputArray::_InputArray(const vector >& vec) - : flags(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type), obj((void*)&vec) {} - -template inline _InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) - : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m) {} - -template inline _InputArray::_InputArray(const _Tp* vec, int n) - : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)vec), sz(n, 1) {} - -inline _InputArray::_InputArray(const Scalar& s) - : flags(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F), obj((void*)&s), sz(1, 4) {} - -template inline _InputArray::_InputArray(const Mat_<_Tp>& m) - : flags(FIXED_TYPE + MAT + DataType<_Tp>::type), obj((void*)&m) {} - -template inline _OutputArray::_OutputArray(vector<_Tp>& vec) - : _InputArray(vec) {} -template inline _OutputArray::_OutputArray(vector >& vec) - : _InputArray(vec) {} -template inline _OutputArray::_OutputArray(vector >& vec) - : _InputArray(vec) {} -template inline _OutputArray::_OutputArray(Mat_<_Tp>& m) - : _InputArray(m) {} -template inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) - : _InputArray(mtx) {} -template inline _OutputArray::_OutputArray(_Tp* vec, int n) - : _InputArray(vec, n) {} - -template inline _OutputArray::_OutputArray(const vector<_Tp>& vec) - : _InputArray(vec) {flags |= FIXED_SIZE;} -template inline _OutputArray::_OutputArray(const vector >& vec) - : _InputArray(vec) {flags |= FIXED_SIZE;} -template inline _OutputArray::_OutputArray(const vector >& vec) - : _InputArray(vec) {flags |= FIXED_SIZE;} - -template inline _OutputArray::_OutputArray(const Mat_<_Tp>& m) - : _InputArray(m) {flags |= FIXED_SIZE;} -template inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) - : _InputArray(mtx) {} -template inline _OutputArray::_OutputArray(const _Tp* vec, int n) - : _InputArray(vec, n) {} - -//////////////////////////////////// Matrix Expressions ///////////////////////////////////////// +///////////////////////////////// Matrix Expressions ///////////////////////////////// class CV_EXPORTS MatOp { public: - MatOp() {}; - virtual ~MatOp() {}; + MatOp(); + virtual ~MatOp(); virtual bool elementWise(const MatExpr& expr) const; virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; @@ -1212,45 +3502,80 @@ public: virtual int type(const MatExpr& expr) const; }; +/** @brief Matrix expression representation +@anchor MatrixExpressions +This is a list of implemented matrix operations that can be combined in arbitrary complex +expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a +real-valued scalar ( double )): +- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` +- Scaling: `A*alpha` +- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` +- Matrix multiplication: `A*B` +- Transposition: `A.t()` (means AT) +- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: + `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` +- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of + `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose + elements are set to 255 (if the particular element or pair of elements satisfy the condition) or + 0. +- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of + `&`, `|`, `^`. +- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` +- Element-wise absolute value: `abs(A)` +- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` +- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, + mean, sum, countNonZero, trace, determinant, repeat, and others. +- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated + initializers, matrix constructors and operators that extract sub-matrices (see Mat description). +- Mat_() constructors to cast the result to the proper type. +@note Comma-separated initializers and probably some other operations may require additional +explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. +Here are examples of matrix expressions: +@code + // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) + SVD svd(A); + Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); + + // compute the new vector of parameters in the Levenberg-Marquardt algorithm + x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); + + // sharpen image using "unsharp mask" algorithm + Mat blurred; double sigma = 1, threshold = 5, amount = 1; + GaussianBlur(img, blurred, Size(), sigma, sigma); + Mat lowContrastMask = abs(img - blurred) < threshold; + Mat sharpened = img*(1+amount) + blurred*(-amount); + img.copyTo(sharpened, lowContrastMask); +@endcode +*/ class CV_EXPORTS MatExpr { public: - MatExpr() : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s(Scalar()) {} - MatExpr(const MatOp* _op, int _flags, const Mat& _a=Mat(), const Mat& _b=Mat(), - const Mat& _c=Mat(), double _alpha=1, double _beta=1, const Scalar& _s=Scalar()) - : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) {} + MatExpr(); explicit MatExpr(const Mat& m); - operator Mat() const - { - Mat m; - op->assign(*this, m); - return m; - } - template operator Mat_<_Tp>() const - { - Mat_<_Tp> m; - op->assign(*this, m, DataType<_Tp>::type); - return m; - } + MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), + const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); + + operator Mat() const; + template operator Mat_<_Tp>() const; + + Size size() const; + int type() const; MatExpr row(int y) const; MatExpr col(int x) const; - MatExpr diag(int d=0) const; + MatExpr diag(int d = 0) const; MatExpr operator()( const Range& rowRange, const Range& colRange ) const; MatExpr operator()( const Rect& roi ) const; - Mat cross(const Mat& m) const; - double dot(const Mat& m) const; - MatExpr t() const; MatExpr inv(int method = DECOMP_LU) const; MatExpr mul(const MatExpr& e, double scale=1) const; MatExpr mul(const Mat& m, double scale=1) const; - Size size() const; - int type() const; + Mat cross(const Mat& m) const; + double dot(const Mat& m) const; const MatOp* op; int flags; @@ -1260,7 +3585,10 @@ public: Scalar s; }; +//! @} core_basic +//! @relates cv::MatExpr +//! @{ CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); @@ -1269,6 +3597,10 @@ CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } +template static inline +MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); @@ -1278,6 +3610,10 @@ CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } +template static inline +MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } CV_EXPORTS MatExpr operator - (const Mat& m); CV_EXPORTS MatExpr operator - (const MatExpr& e); @@ -1290,6 +3626,10 @@ CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } +template static inline +MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator / (const Mat& a, double s); @@ -1299,1324 +3639,123 @@ CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } +template static inline +MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator < (const Mat& a, double s); CV_EXPORTS MatExpr operator < (double s, const Mat& a); +template static inline +MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } +template static inline +MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator <= (const Mat& a, double s); CV_EXPORTS MatExpr operator <= (double s, const Mat& a); +template static inline +MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } +template static inline +MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator == (const Mat& a, double s); CV_EXPORTS MatExpr operator == (double s, const Mat& a); +template static inline +MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } +template static inline +MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator != (const Mat& a, double s); CV_EXPORTS MatExpr operator != (double s, const Mat& a); +template static inline +MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } +template static inline +MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator >= (const Mat& a, double s); CV_EXPORTS MatExpr operator >= (double s, const Mat& a); +template static inline +MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } +template static inline +MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator > (const Mat& a, double s); CV_EXPORTS MatExpr operator > (double s, const Mat& a); - -CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr min(const Mat& a, double s); -CV_EXPORTS MatExpr min(double s, const Mat& a); - -CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr max(const Mat& a, double s); -CV_EXPORTS MatExpr max(double s, const Mat& a); - -template static inline MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::min((const Mat&)a, (const Mat&)b); -} - -template static inline MatExpr min(const Mat_<_Tp>& a, double s) -{ - return cv::min((const Mat&)a, s); -} - -template static inline MatExpr min(double s, const Mat_<_Tp>& a) -{ - return cv::min((const Mat&)a, s); -} - -template static inline MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::max((const Mat&)a, (const Mat&)b); -} - -template static inline MatExpr max(const Mat_<_Tp>& a, double s) -{ - return cv::max((const Mat&)a, s); -} - -template static inline MatExpr max(double s, const Mat_<_Tp>& a) -{ - return cv::max((const Mat&)a, s); -} - -template static inline void min(const Mat_<_Tp>& a, const Mat_<_Tp>& b, Mat_<_Tp>& c) -{ - cv::min((const Mat&)a, (const Mat&)b, (Mat&)c); -} - -template static inline void min(const Mat_<_Tp>& a, double s, Mat_<_Tp>& c) -{ - cv::min((const Mat&)a, s, (Mat&)c); -} - -template static inline void min(double s, const Mat_<_Tp>& a, Mat_<_Tp>& c) -{ - cv::min((const Mat&)a, s, (Mat&)c); -} - -template static inline void max(const Mat_<_Tp>& a, const Mat_<_Tp>& b, Mat_<_Tp>& c) -{ - cv::max((const Mat&)a, (const Mat&)b, (Mat&)c); -} - -template static inline void max(const Mat_<_Tp>& a, double s, Mat_<_Tp>& c) -{ - cv::max((const Mat&)a, s, (Mat&)c); -} - -template static inline void max(double s, const Mat_<_Tp>& a, Mat_<_Tp>& c) -{ - cv::max((const Mat&)a, s, (Mat&)c); -} - +template static inline +MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } +template static inline +MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); +template static inline +MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } +template static inline +MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); +template static inline +MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } +template static inline +MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); +template static inline +MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } +template static inline +MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } CV_EXPORTS MatExpr operator ~(const Mat& m); +CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr min(const Mat& a, double s); +CV_EXPORTS MatExpr min(double s, const Mat& a); +template static inline +MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } +template static inline +MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } + +CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr max(const Mat& a, double s); +CV_EXPORTS MatExpr max(double s, const Mat& a); +template static inline +MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } +template static inline +MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } + +/** @brief Calculates an absolute value of each matrix element. + +abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: +- C = abs(A-B) is equivalent to `absdiff(A, B, C)` +- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` +- C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, +beta)` + +The output matrix has the same size and the same type as the input one except for the last case, +where C is depth=CV_8U . +@param m matrix. +@sa @ref MatrixExpressions, absdiff, convertScaleAbs + */ CV_EXPORTS MatExpr abs(const Mat& m); +/** @overload +@param e matrix expression. +*/ CV_EXPORTS MatExpr abs(const MatExpr& e); +//! @} relates cv::MatExpr -template static inline MatExpr abs(const Mat_<_Tp>& m) -{ - return cv::abs((const Mat&)m); -} +} // cv -////////////////////////////// Augmenting algebraic operations ////////////////////////////////// +#include "opencv2/core/mat.inl.hpp" -inline Mat& Mat::operator = (const MatExpr& e) -{ - e.op->assign(e, *this); - return *this; -} - -template inline Mat_<_Tp>::Mat_(const MatExpr& e) -{ - e.op->assign(e, *this, DataType<_Tp>::type); -} - -template Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) -{ - e.op->assign(e, *this, DataType<_Tp>::type); - return *this; -} - -static inline Mat& operator += (const Mat& a, const Mat& b) -{ - add(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator += (const Mat& a, const Scalar& s) -{ - add(a, s, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - add(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline -Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const Scalar& s) -{ - add(a, s, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator += (const Mat& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator -= (const Mat& a, const Mat& b) -{ - subtract(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator -= (const Mat& a, const Scalar& s) -{ - subtract(a, s, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - subtract(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline -Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const Scalar& s) -{ - subtract(a, s, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator -= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator *= (const Mat& a, const Mat& b) -{ - gemm(a, b, 1, Mat(), 0, (Mat&)a, 0); - return (Mat&)a; -} - -static inline Mat& operator *= (const Mat& a, double s) -{ - a.convertTo((Mat&)a, -1, s); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - gemm(a, b, 1, Mat(), 0, (Mat&)a, 0); - return (Mat_<_Tp>&)a; -} - -template static inline -Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, double s) -{ - a.convertTo((Mat&)a, -1, s); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator *= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator /= (const Mat& a, const Mat& b) -{ - divide(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator /= (const Mat& a, double s) -{ - a.convertTo((Mat&)a, -1, 1./s); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - divide(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline -Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, double s) -{ - a.convertTo((Mat&)a, -1, 1./s); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator /= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return (Mat&)a; -} - -template static inline -Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -////////////////////////////// Logical operations /////////////////////////////// - -static inline Mat& operator &= (const Mat& a, const Mat& b) -{ - bitwise_and(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator &= (const Mat& a, const Scalar& s) -{ - bitwise_and(a, s, (Mat&)a); - return (Mat&)a; -} - -template static inline Mat_<_Tp>& -operator &= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - bitwise_and(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline Mat_<_Tp>& -operator &= (const Mat_<_Tp>& a, const Scalar& s) -{ - bitwise_and(a, s, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator |= (const Mat& a, const Mat& b) -{ - bitwise_or(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator |= (const Mat& a, const Scalar& s) -{ - bitwise_or(a, s, (Mat&)a); - return (Mat&)a; -} - -template static inline Mat_<_Tp>& -operator |= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - bitwise_or(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline Mat_<_Tp>& -operator |= (const Mat_<_Tp>& a, const Scalar& s) -{ - bitwise_or(a, s, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -static inline Mat& operator ^= (const Mat& a, const Mat& b) -{ - bitwise_xor(a, b, (Mat&)a); - return (Mat&)a; -} - -static inline Mat& operator ^= (const Mat& a, const Scalar& s) -{ - bitwise_xor(a, s, (Mat&)a); - return (Mat&)a; -} - -template static inline Mat_<_Tp>& -operator ^= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - bitwise_xor(a, b, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -template static inline Mat_<_Tp>& -operator ^= (const Mat_<_Tp>& a, const Scalar& s) -{ - bitwise_xor(a, s, (Mat&)a); - return (Mat_<_Tp>&)a; -} - -/////////////////////////////// Miscellaneous operations ////////////////////////////// - -template void split(const Mat& src, vector >& mv) -{ split(src, (vector&)mv ); } - -////////////////////////////////////////////////////////////// - -template inline MatExpr Mat_<_Tp>::zeros(int rows, int cols) -{ - return Mat::zeros(rows, cols, DataType<_Tp>::type); -} - -template inline MatExpr Mat_<_Tp>::zeros(Size sz) -{ - return Mat::zeros(sz, DataType<_Tp>::type); -} - -template inline MatExpr Mat_<_Tp>::ones(int rows, int cols) -{ - return Mat::ones(rows, cols, DataType<_Tp>::type); -} - -template inline MatExpr Mat_<_Tp>::ones(Size sz) -{ - return Mat::ones(sz, DataType<_Tp>::type); -} - -template inline MatExpr Mat_<_Tp>::eye(int rows, int cols) -{ - return Mat::eye(rows, cols, DataType<_Tp>::type); -} - -template inline MatExpr Mat_<_Tp>::eye(Size sz) -{ - return Mat::eye(sz, DataType<_Tp>::type); -} - -//////////////////////////////// Iterators & Comma initializers ////////////////////////////////// - -inline MatConstIterator::MatConstIterator() - : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) {} - -inline MatConstIterator::MatConstIterator(const Mat* _m) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - if( m && m->isContinuous() ) - { - sliceStart = m->data; - sliceEnd = sliceStart + m->total()*elemSize; - } - seek((const int*)0); -} - -inline MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - sliceStart = m->data; - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[]={_row, _col}; - seek(idx); -} - -inline MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - sliceStart = m->data; - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[]={_pt.y, _pt.x}; - seek(idx); -} - -inline MatConstIterator::MatConstIterator(const MatConstIterator& it) - : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) -{} - -inline MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) -{ - m = it.m; elemSize = it.elemSize; ptr = it.ptr; - sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; - return *this; -} - -inline uchar* MatConstIterator::operator *() const { return ptr; } - -inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) -{ - if( !m || ofs == 0 ) - return *this; - ptrdiff_t ofsb = ofs*elemSize; - ptr += ofsb; - if( ptr < sliceStart || sliceEnd <= ptr ) - { - ptr -= ofsb; - seek(ofs, true); - } - return *this; -} - -inline MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) -{ return (*this += -ofs); } - -inline MatConstIterator& MatConstIterator::operator --() -{ - if( m && (ptr -= elemSize) < sliceStart ) - { - ptr += elemSize; - seek(-1, true); - } - return *this; -} - -inline MatConstIterator MatConstIterator::operator --(int) -{ - MatConstIterator b = *this; - *this += -1; - return b; -} - -inline MatConstIterator& MatConstIterator::operator ++() -{ - if( m && (ptr += elemSize) >= sliceEnd ) - { - ptr -= elemSize; - seek(1, true); - } - return *this; -} - -inline MatConstIterator MatConstIterator::operator ++(int) -{ - MatConstIterator b = *this; - *this += 1; - return b; -} - -template inline MatConstIterator_<_Tp>::MatConstIterator_() {} - -template inline MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) - : MatConstIterator(_m) {} - -template inline MatConstIterator_<_Tp>:: - MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator(_m, _row, _col) {} - -template inline MatConstIterator_<_Tp>:: - MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) - : MatConstIterator(_m, _pt) {} - -template inline MatConstIterator_<_Tp>:: - MatConstIterator_(const MatConstIterator_& it) - : MatConstIterator(it) {} - -template inline MatConstIterator_<_Tp>& - MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline _Tp MatConstIterator_<_Tp>::operator *() const { return *(_Tp*)(this->ptr); } - -template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ return (*this += -ofs); } - -template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - -template inline MatIterator_<_Tp>::MatIterator_() : MatConstIterator_<_Tp>() {} - -template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) - : MatConstIterator_<_Tp>(_m) {} - -template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator_<_Tp>(_m, _row, _col) {} - -template inline MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, Point _pt) - : MatConstIterator_<_Tp>(_m, _pt) {} - -template inline MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, const int* _idx) - : MatConstIterator_<_Tp>(_m, _idx) {} - -template inline MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) - : MatConstIterator_<_Tp>(it) {} - -template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline _Tp& MatIterator_<_Tp>::operator *() const { return *(_Tp*)(this->ptr); } - -template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ - MatConstIterator::operator += (-ofs); - return *this; -} - -template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - -template inline Point MatConstIterator_<_Tp>::pos() const -{ - if( !m ) - return Point(); - CV_DbgAssert( m->dims <= 2 ); - if( m->isContinuous() ) - { - ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; - int y = (int)(ofs / m->cols), x = (int)(ofs - (ptrdiff_t)y*m->cols); - return Point(x, y); - } - else - { - ptrdiff_t ofs = (uchar*)ptr - m->data; - int y = (int)(ofs / m->step), x = (int)((ofs - y*m->step)/sizeof(_Tp)); - return Point(x, y); - } -} - -static inline bool -operator == (const MatConstIterator& a, const MatConstIterator& b) -{ return a.m == b.m && a.ptr == b.ptr; } - -template static inline bool -operator != (const MatConstIterator& a, const MatConstIterator& b) -{ return !(a == b); } - -template static inline bool -operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ return a.m == b.m && a.ptr == b.ptr; } - -template static inline bool -operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ return a.m != b.m || a.ptr != b.ptr; } - -template static inline bool -operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ return a.m == b.m && a.ptr == b.ptr; } - -template static inline bool -operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ return a.m != b.m || a.ptr != b.ptr; } - -static inline bool -operator < (const MatConstIterator& a, const MatConstIterator& b) -{ return a.ptr < b.ptr; } - -static inline bool -operator > (const MatConstIterator& a, const MatConstIterator& b) -{ return a.ptr > b.ptr; } - -static inline bool -operator <= (const MatConstIterator& a, const MatConstIterator& b) -{ return a.ptr <= b.ptr; } - -static inline bool -operator >= (const MatConstIterator& a, const MatConstIterator& b) -{ return a.ptr >= b.ptr; } - -CV_EXPORTS ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a); - -static inline MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) -{ MatConstIterator b = a; return b += ofs; } - -static inline MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) -{ MatConstIterator b = a; return b += ofs; } - -static inline MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) -{ MatConstIterator b = a; return b += -ofs; } - -template static inline MatConstIterator_<_Tp> -operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } - -template static inline MatConstIterator_<_Tp> -operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) -{ MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } - -template static inline MatConstIterator_<_Tp> -operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatConstIterator_<_Tp>&)t; } - -inline uchar* MatConstIterator::operator [](ptrdiff_t i) const -{ return *(*this + i); } - -template inline _Tp MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const -{ return *(_Tp*)MatConstIterator::operator [](i); } - -template static inline MatIterator_<_Tp> -operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatIterator_<_Tp>&)t; } - -template static inline MatIterator_<_Tp> -operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) -{ MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatIterator_<_Tp>&)t; } - -template static inline MatIterator_<_Tp> -operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatIterator_<_Tp>&)t; } - -template inline _Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const -{ return *(*this + i); } - -template inline MatConstIterator_<_Tp> Mat_<_Tp>::begin() const -{ return Mat::begin<_Tp>(); } - -template inline MatConstIterator_<_Tp> Mat_<_Tp>::end() const -{ return Mat::end<_Tp>(); } - -template inline MatIterator_<_Tp> Mat_<_Tp>::begin() -{ return Mat::begin<_Tp>(); } - -template inline MatIterator_<_Tp> Mat_<_Tp>::end() -{ return Mat::end<_Tp>(); } - -template inline MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) : it(_m) {} - -template template inline MatCommaInitializer_<_Tp>& -MatCommaInitializer_<_Tp>::operator , (T2 v) -{ - CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); - *this->it = _Tp(v); ++this->it; - return *this; -} - -template inline Mat_<_Tp> MatCommaInitializer_<_Tp>::operator *() const -{ - CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); - return Mat_<_Tp>(*this->it.m); -} - -template inline MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const -{ - CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); - return Mat_<_Tp>(*this->it.m); -} - -template static inline MatCommaInitializer_<_Tp> -operator << (const Mat_<_Tp>& m, T2 val) -{ - MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); - return (commaInitializer, val); -} - -//////////////////////////////// SparseMat //////////////////////////////// - -inline SparseMat::SparseMat() -: flags(MAGIC_VAL), hdr(0) -{ -} - -inline SparseMat::SparseMat(int _dims, const int* _sizes, int _type) -: flags(MAGIC_VAL), hdr(0) -{ - create(_dims, _sizes, _type); -} - -inline SparseMat::SparseMat(const SparseMat& m) -: flags(m.flags), hdr(m.hdr) -{ - addref(); -} - -inline SparseMat::~SparseMat() -{ - release(); -} - -inline SparseMat& SparseMat::operator = (const SparseMat& m) -{ - if( this != &m ) - { - if( m.hdr ) - CV_XADD(&m.hdr->refcount, 1); - release(); - flags = m.flags; - hdr = m.hdr; - } - return *this; -} - -inline SparseMat& SparseMat::operator = (const Mat& m) -{ return (*this = SparseMat(m)); } - -inline SparseMat SparseMat::clone() const -{ - SparseMat temp; - this->copyTo(temp); - return temp; -} - - -inline void SparseMat::assignTo( SparseMat& m, int _type ) const -{ - if( _type < 0 ) - m = *this; - else - convertTo(m, _type); -} - -inline void SparseMat::addref() -{ if( hdr ) CV_XADD(&hdr->refcount, 1); } - -inline void SparseMat::release() -{ - if( hdr && CV_XADD(&hdr->refcount, -1) == 1 ) - delete hdr; - hdr = 0; -} - -inline size_t SparseMat::elemSize() const -{ return CV_ELEM_SIZE(flags); } - -inline size_t SparseMat::elemSize1() const -{ return CV_ELEM_SIZE1(flags); } - -inline int SparseMat::type() const -{ return CV_MAT_TYPE(flags); } - -inline int SparseMat::depth() const -{ return CV_MAT_DEPTH(flags); } - -inline int SparseMat::channels() const -{ return CV_MAT_CN(flags); } - -inline const int* SparseMat::size() const -{ - return hdr ? hdr->size : 0; -} - -inline int SparseMat::size(int i) const -{ - if( hdr ) - { - CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); - return hdr->size[i]; - } - return 0; -} - -inline int SparseMat::dims() const -{ - return hdr ? hdr->dims : 0; -} - -inline size_t SparseMat::nzcount() const -{ - return hdr ? hdr->nodeCount : 0; -} - -inline size_t SparseMat::hash(int i0) const -{ - return (size_t)i0; -} - -inline size_t SparseMat::hash(int i0, int i1) const -{ - return (size_t)(unsigned)i0*HASH_SCALE + (unsigned)i1; -} - -inline size_t SparseMat::hash(int i0, int i1, int i2) const -{ - return ((size_t)(unsigned)i0*HASH_SCALE + (unsigned)i1)*HASH_SCALE + (unsigned)i2; -} - -inline size_t SparseMat::hash(const int* idx) const -{ - size_t h = (unsigned)idx[0]; - if( !hdr ) - return 0; - int i, d = hdr->dims; - for( i = 1; i < d; i++ ) - h = h*HASH_SCALE + (unsigned)idx[i]; - return h; -} - -template inline _Tp& SparseMat::ref(int i0, size_t* hashval) -{ return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); } - -template inline _Tp& SparseMat::ref(int i0, int i1, size_t* hashval) -{ return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); } - -template inline _Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) -{ return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); } - -template inline _Tp& SparseMat::ref(const int* idx, size_t* hashval) -{ return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); } - -template inline _Tp SparseMat::value(int i0, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); - return p ? *p : _Tp(); -} - -template inline _Tp SparseMat::value(int i0, int i1, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); - return p ? *p : _Tp(); -} - -template inline _Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); - return p ? *p : _Tp(); -} - -template inline _Tp SparseMat::value(const int* idx, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); - return p ? *p : _Tp(); -} - -template inline const _Tp* SparseMat::find(int i0, size_t* hashval) const -{ return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); } - -template inline const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const -{ return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); } - -template inline const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const -{ return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); } - -template inline const _Tp* SparseMat::find(const int* idx, size_t* hashval) const -{ return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); } - -template inline _Tp& SparseMat::value(Node* n) -{ return *(_Tp*)((uchar*)n + hdr->valueOffset); } - -template inline const _Tp& SparseMat::value(const Node* n) const -{ return *(const _Tp*)((const uchar*)n + hdr->valueOffset); } - -inline SparseMat::Node* SparseMat::node(size_t nidx) -{ return (Node*)(void*)&hdr->pool[nidx]; } - -inline const SparseMat::Node* SparseMat::node(size_t nidx) const -{ return (const Node*)(void*)&hdr->pool[nidx]; } - -inline SparseMatIterator SparseMat::begin() -{ return SparseMatIterator(this); } - -inline SparseMatConstIterator SparseMat::begin() const -{ return SparseMatConstIterator(this); } - -inline SparseMatIterator SparseMat::end() -{ SparseMatIterator it(this); it.seekEnd(); return it; } - -inline SparseMatConstIterator SparseMat::end() const -{ SparseMatConstIterator it(this); it.seekEnd(); return it; } - -template inline SparseMatIterator_<_Tp> SparseMat::begin() -{ return SparseMatIterator_<_Tp>(this); } - -template inline SparseMatConstIterator_<_Tp> SparseMat::begin() const -{ return SparseMatConstIterator_<_Tp>(this); } - -template inline SparseMatIterator_<_Tp> SparseMat::end() -{ SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } - -template inline SparseMatConstIterator_<_Tp> SparseMat::end() const -{ SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } - - -inline SparseMatConstIterator::SparseMatConstIterator() -: m(0), hashidx(0), ptr(0) -{ -} - -inline SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) -: m(it.m), hashidx(it.hashidx), ptr(it.ptr) -{ -} - -static inline bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ return it1.m == it2.m && it1.ptr == it2.ptr; } - -static inline bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ return !(it1 == it2); } - - -inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) -{ - if( this != &it ) - { - m = it.m; - hashidx = it.hashidx; - ptr = it.ptr; - } - return *this; -} - -template inline const _Tp& SparseMatConstIterator::value() const -{ return *(_Tp*)ptr; } - -inline const SparseMat::Node* SparseMatConstIterator::node() const -{ - return ptr && m && m->hdr ? - (const SparseMat::Node*)(void*)(ptr - m->hdr->valueOffset) : 0; -} - -inline SparseMatConstIterator SparseMatConstIterator::operator ++(int) -{ - SparseMatConstIterator it = *this; - ++*this; - return it; -} - - -inline void SparseMatConstIterator::seekEnd() -{ - if( m && m->hdr ) - { - hashidx = m->hdr->hashtab.size(); - ptr = 0; - } -} - -inline SparseMatIterator::SparseMatIterator() -{} - -inline SparseMatIterator::SparseMatIterator(SparseMat* _m) -: SparseMatConstIterator(_m) -{} - -inline SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) -: SparseMatConstIterator(it) -{ -} - -inline SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) -{ - (SparseMatConstIterator&)*this = it; - return *this; -} - -template inline _Tp& SparseMatIterator::value() const -{ return *(_Tp*)ptr; } - -inline SparseMat::Node* SparseMatIterator::node() const -{ - return (SparseMat::Node*)SparseMatConstIterator::node(); -} - -inline SparseMatIterator& SparseMatIterator::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -inline SparseMatIterator SparseMatIterator::operator ++(int) -{ - SparseMatIterator it = *this; - ++*this; - return it; -} - - -template inline SparseMat_<_Tp>::SparseMat_() -{ flags = MAGIC_VAL | DataType<_Tp>::type; } - -template inline SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) -: SparseMat(_dims, _sizes, DataType<_Tp>::type) -{} - -template inline SparseMat_<_Tp>::SparseMat_(const SparseMat& m) -{ - if( m.type() == DataType<_Tp>::type ) - *this = (const SparseMat_<_Tp>&)m; - else - m.convertTo(*this, DataType<_Tp>::type); -} - -template inline SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) -{ - this->flags = m.flags; - this->hdr = m.hdr; - if( this->hdr ) - CV_XADD(&this->hdr->refcount, 1); -} - -template inline SparseMat_<_Tp>::SparseMat_(const Mat& m) -{ - SparseMat sm(m); - *this = sm; -} - -template inline SparseMat_<_Tp>::SparseMat_(const CvSparseMat* m) -{ - SparseMat sm(m); - *this = sm; -} - -template inline SparseMat_<_Tp>& -SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) -{ - if( this != &m ) - { - if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); - release(); - flags = m.flags; - hdr = m.hdr; - } - return *this; -} - -template inline SparseMat_<_Tp>& -SparseMat_<_Tp>::operator = (const SparseMat& m) -{ - if( m.type() == DataType<_Tp>::type ) - return (*this = (const SparseMat_<_Tp>&)m); - m.convertTo(*this, DataType<_Tp>::type); - return *this; -} - -template inline SparseMat_<_Tp>& -SparseMat_<_Tp>::operator = (const Mat& m) -{ return (*this = SparseMat(m)); } - -template inline SparseMat_<_Tp> -SparseMat_<_Tp>::clone() const -{ - SparseMat_<_Tp> m; - this->copyTo(m); - return m; -} - -template inline void -SparseMat_<_Tp>::create(int _dims, const int* _sizes) -{ - SparseMat::create(_dims, _sizes, DataType<_Tp>::type); -} - -template inline -SparseMat_<_Tp>::operator CvSparseMat*() const -{ - return SparseMat::operator CvSparseMat*(); -} - -template inline int SparseMat_<_Tp>::type() const -{ return DataType<_Tp>::type; } - -template inline int SparseMat_<_Tp>::depth() const -{ return DataType<_Tp>::depth; } - -template inline int SparseMat_<_Tp>::channels() const -{ return DataType<_Tp>::channels; } - -template inline _Tp& -SparseMat_<_Tp>::ref(int i0, size_t* hashval) -{ return SparseMat::ref<_Tp>(i0, hashval); } - -template inline _Tp -SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const -{ return SparseMat::value<_Tp>(i0, hashval); } - -template inline _Tp& -SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) -{ return SparseMat::ref<_Tp>(i0, i1, hashval); } - -template inline _Tp -SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const -{ return SparseMat::value<_Tp>(i0, i1, hashval); } - -template inline _Tp& -SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) -{ return SparseMat::ref<_Tp>(i0, i1, i2, hashval); } - -template inline _Tp -SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const -{ return SparseMat::value<_Tp>(i0, i1, i2, hashval); } - -template inline _Tp& -SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) -{ return SparseMat::ref<_Tp>(idx, hashval); } - -template inline _Tp -SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const -{ return SparseMat::value<_Tp>(idx, hashval); } - -template inline SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() -{ return SparseMatIterator_<_Tp>(this); } - -template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const -{ return SparseMatConstIterator_<_Tp>(this); } - -template inline SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() -{ SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } - -template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const -{ SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) -: SparseMatConstIterator(_m) -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) -: SparseMatConstIterator(_m) -{ - CV_Assert( _m->type() == DataType<_Tp>::type ); -} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) -: SparseMatConstIterator(it) -{} - -template inline SparseMatConstIterator_<_Tp>& -SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) -{ return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); } - -template inline const _Tp& -SparseMatConstIterator_<_Tp>::operator *() const -{ return *(const _Tp*)this->ptr; } - -template inline SparseMatConstIterator_<_Tp>& -SparseMatConstIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline SparseMatConstIterator_<_Tp> -SparseMatConstIterator_<_Tp>::operator ++(int) -{ - SparseMatConstIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_() -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) -: SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) -: SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) -: SparseMatConstIterator_<_Tp>(it) -{} - -template inline SparseMatIterator_<_Tp>& -SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) -{ return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); } - -template inline _Tp& -SparseMatIterator_<_Tp>::operator *() const -{ return *(_Tp*)this->ptr; } - -template inline SparseMatIterator_<_Tp>& -SparseMatIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline SparseMatIterator_<_Tp> -SparseMatIterator_<_Tp>::operator ++(int) -{ - SparseMatIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - -} - -#endif -#endif +#endif // OPENCV_CORE_MAT_HPP diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/operations.hpp b/HuaGoCorrect/pub/opencv/include/opencv2/core/operations.hpp index 325b7ea..082fef4 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/operations.hpp +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/operations.hpp @@ -12,6 +12,8 @@ // // 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. +// Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, @@ -40,770 +42,63 @@ // //M*/ -#ifndef __OPENCV_CORE_OPERATIONS_HPP__ -#define __OPENCV_CORE_OPERATIONS_HPP__ +#ifndef OPENCV_CORE_OPERATIONS_HPP +#define OPENCV_CORE_OPERATIONS_HPP -#ifndef SKIP_INCLUDES - #include - #include -#endif // SKIP_INCLUDES - - -#ifdef __cplusplus - -/////// exchange-add operation for atomic operations on reference counters /////// -#if defined __INTEL_COMPILER && !(defined WIN32 || defined _WIN32) // atomic increment on the linux version of the Intel(tm) compiler - #define CV_XADD(addr,delta) _InterlockedExchangeAdd(const_cast(reinterpret_cast(addr)), delta) -#elif defined __GNUC__ - - #if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) - #ifdef __ATOMIC_SEQ_CST - #define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), (delta), __ATOMIC_SEQ_CST) - #else - #define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), (delta), 5) - #endif - #elif __GNUC__*10 + __GNUC_MINOR__ >= 42 - - #if !(defined WIN32 || defined _WIN32) && (defined __i486__ || defined __i586__ || \ - defined __i686__ || defined __MMX__ || defined __SSE__ || defined __ppc__) || \ - (defined __GNUC__ && defined _STLPORT_MAJOR) || \ - defined __EMSCRIPTEN__ - - #define CV_XADD __sync_fetch_and_add - #else - #include - #define CV_XADD __gnu_cxx::__exchange_and_add - #endif - - #else - #include - #if __GNUC__*10 + __GNUC_MINOR__ >= 34 - #define CV_XADD __gnu_cxx::__exchange_and_add - #else - #define CV_XADD __exchange_and_add - #endif - #endif - -#elif defined WIN32 || defined _WIN32 || defined WINCE - namespace cv { CV_EXPORTS int _interlockedExchangeAdd(int* addr, int delta); } - #define CV_XADD cv::_interlockedExchangeAdd - -#else - static inline int CV_XADD(int* addr, int delta) - { int tmp = *addr; *addr += delta; return tmp; } +#ifndef __cplusplus +# error operations.hpp header must be compiled as C++ #endif -#include +#include -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4127) //conditional expression is constant -#endif +//! @cond IGNORED namespace cv { -using std::cos; -using std::sin; -using std::max; -using std::min; -using std::exp; -using std::log; -using std::pow; -using std::sqrt; +////////////////////////////// Matx methods depending on core API ///////////////////////////// - -/////////////// saturate_cast (used in image & signal processing) /////////////////// - -template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } -template static inline _Tp saturate_cast(schar v) { return _Tp(v); } -template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } -template static inline _Tp saturate_cast(short v) { return _Tp(v); } -template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } -template static inline _Tp saturate_cast(int v) { return _Tp(v); } -template static inline _Tp saturate_cast(float v) { return _Tp(v); } -template static inline _Tp saturate_cast(double v) { return _Tp(v); } - -template<> inline uchar saturate_cast(schar v) -{ return (uchar)std::max((int)v, 0); } -template<> inline uchar saturate_cast(ushort v) -{ return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(int v) -{ return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } -template<> inline uchar saturate_cast(short v) -{ return saturate_cast((int)v); } -template<> inline uchar saturate_cast(unsigned v) -{ return (uchar)std::min(v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(float v) -{ int iv = cvRound(v); return saturate_cast(iv); } -template<> inline uchar saturate_cast(double v) -{ int iv = cvRound(v); return saturate_cast(iv); } - -template<> inline schar saturate_cast(uchar v) -{ return (schar)std::min((int)v, SCHAR_MAX); } -template<> inline schar saturate_cast(ushort v) -{ return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } -template<> inline schar saturate_cast(int v) -{ - return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? - v : v > 0 ? SCHAR_MAX : SCHAR_MIN); -} -template<> inline schar saturate_cast(short v) -{ return saturate_cast((int)v); } -template<> inline schar saturate_cast(unsigned v) -{ return (schar)std::min(v, (unsigned)SCHAR_MAX); } - -template<> inline schar saturate_cast(float v) -{ int iv = cvRound(v); return saturate_cast(iv); } -template<> inline schar saturate_cast(double v) -{ int iv = cvRound(v); return saturate_cast(iv); } - -template<> inline ushort saturate_cast(schar v) -{ return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(short v) -{ return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(int v) -{ return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } -template<> inline ushort saturate_cast(unsigned v) -{ return (ushort)std::min(v, (unsigned)USHRT_MAX); } -template<> inline ushort saturate_cast(float v) -{ int iv = cvRound(v); return saturate_cast(iv); } -template<> inline ushort saturate_cast(double v) -{ int iv = cvRound(v); return saturate_cast(iv); } - -template<> inline short saturate_cast(ushort v) -{ return (short)std::min((int)v, SHRT_MAX); } -template<> inline short saturate_cast(int v) -{ - return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? - v : v > 0 ? SHRT_MAX : SHRT_MIN); -} -template<> inline short saturate_cast(unsigned v) -{ return (short)std::min(v, (unsigned)SHRT_MAX); } -template<> inline short saturate_cast(float v) -{ int iv = cvRound(v); return saturate_cast(iv); } -template<> inline short saturate_cast(double v) -{ int iv = cvRound(v); return saturate_cast(iv); } - -template<> inline int saturate_cast(float v) { return cvRound(v); } -template<> inline int saturate_cast(double v) { return cvRound(v); } - -// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. -template<> inline unsigned saturate_cast(float v){ return cvRound(v); } -template<> inline unsigned saturate_cast(double v) { return cvRound(v); } - -inline int fast_abs(uchar v) { return v; } -inline int fast_abs(schar v) { return std::abs((int)v); } -inline int fast_abs(ushort v) { return v; } -inline int fast_abs(short v) { return std::abs((int)v); } -inline int fast_abs(int v) { return std::abs(v); } -inline float fast_abs(float v) { return std::abs(v); } -inline double fast_abs(double v) { return std::abs(v); } - -//////////////////////////////// Matx ///////////////////////////////// - - -template inline Matx<_Tp, m, n>::Matx() -{ - for(int i = 0; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0) -{ - val[0] = v0; - for(int i = 1; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) -{ - assert(channels >= 2); - val[0] = v0; val[1] = v1; - for(int i = 2; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) -{ - assert(channels >= 3); - val[0] = v0; val[1] = v1; val[2] = v2; - for(int i = 3; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ - assert(channels >= 4); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - for(int i = 4; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) -{ - assert(channels >= 5); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; - for(int i = 5; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5) -{ - assert(channels >= 6); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; - for(int i = 6; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6) -{ - assert(channels >= 7); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; - for(int i = 7; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7) -{ - assert(channels >= 8); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - for(int i = 8; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8) -{ - assert(channels >= 9); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; - for(int i = 9; i < channels; i++) val[i] = _Tp(0); -} - -template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9) -{ - assert(channels >= 10); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; - for(int i = 10; i < channels; i++) val[i] = _Tp(0); -} - - -template -inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11) -{ - assert(channels == 12); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; -} - -template -inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13, _Tp v14, _Tp v15) -{ - assert(channels == 16); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; -} - -template inline Matx<_Tp, m, n>::Matx(const _Tp* values) -{ - for( int i = 0; i < channels; i++ ) val[i] = values[i]; -} - -template inline Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) +namespace internal { - Matx<_Tp, m, n> M; - for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() -{ - return all(0); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() -{ - return all(1); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < MIN(m,n); i++) - M(i,i) = 1; - return M; -} - -template inline _Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const -{ - _Tp s = 0; - for( int i = 0; i < m*n; i++ ) s += val[i]*M.val[i]; - return s; -} - - -template inline double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const -{ - double s = 0; - for( int i = 0; i < m*n; i++ ) s += (double)val[i]*M.val[i]; - return s; -} - - - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < MIN(m,n); i++) - M(i,i) = d(i, 0); - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - Mat matM(M, false); - cv::randu(matM, Scalar(a), Scalar(b)); - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - Mat matM(M, false); - cv::randn(matM, Scalar(a), Scalar(b)); - return M; -} - -template template -inline Matx<_Tp, m, n>::operator Matx() const -{ - Matx M; - for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); - return M; -} - - -template template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const -{ - CV_DbgAssert(m1*n1 == m*n); - return (const Matx<_Tp, m1, n1>&)*this; -} - - -template -template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int i, int j) const -{ - CV_DbgAssert(0 <= i && i+m1 <= m && 0 <= j && j+n1 <= n); - Matx<_Tp, m1, n1> s; - for( int di = 0; di < m1; di++ ) - for( int dj = 0; dj < n1; dj++ ) - s(di, dj) = (*this)(i+di, j+dj); - return s; -} - - -template inline -Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const -{ - CV_DbgAssert((unsigned)i < (unsigned)m); - return Matx<_Tp, 1, n>(&val[i*n]); -} - - -template inline -Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const -{ - CV_DbgAssert((unsigned)j < (unsigned)n); - Matx<_Tp, m, 1> v; - for( int i = 0; i < m; i++ ) - v.val[i] = val[i*n + j]; - return v; -} - - -template inline -typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const -{ - diag_type d; - for( int i = 0; i < MIN(m, n); i++ ) - d.val[i] = val[i*n + i]; - return d; -} - - -template inline -const _Tp& Matx<_Tp, m, n>::operator ()(int i, int j) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)m && (unsigned)j < (unsigned)n ); - return this->val[i*n + j]; -} - - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int i, int j) -{ - CV_DbgAssert( (unsigned)i < (unsigned)m && (unsigned)j < (unsigned)n ); - return val[i*n + j]; -} - - -template inline -const _Tp& Matx<_Tp, m, n>::operator ()(int i) const -{ - CV_DbgAssert( (m == 1 || n == 1) && (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int i) -{ - CV_DbgAssert( (m == 1 || n == 1) && (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - - -template static inline -Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - - -template static inline -Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) -{ - for( int i = 0; i < m*n; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); -} - - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) -{ - for( int i = 0; i < m*n; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); -} - - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) -{ - for( int i = 0; i < m*n; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * alpha); -} - - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) -{ - for( int i = 0; i < m*n; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); -} - - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - { - _Tp s = 0; - for( int k = 0; k < l; k++ ) - s += a(i, k) * b(k, j); - val[i*n + j] = s; - } -} - - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - val[i*n + j] = a(j, i); -} - - -template static inline -Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_AddOp()); -} - - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_SubOp()); -} - - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); -} - - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); -} - - -template static inline -Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) -{ - Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); - return reinterpret_cast&>(c); -} - - -template static inline -Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 2, 1> tmp = a*Vec<_Tp,2>(b.x, b.y); - return Point_<_Tp>(tmp.val[0], tmp.val[1]); -} - - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a*Vec<_Tp,3>(b.x, b.y, b.z); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a*Vec<_Tp,3>(b.x, b.y, 1); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - - -template static inline -Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) -{ - return a*Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); -} - - -template static inline -Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) -{ - Matx c(Matx(a), b, Matx_MatMulOp()); - return static_cast(c); -} - - -static inline -Scalar operator * (const Matx& a, const Scalar& b) -{ - Matx c(a, b, Matx_MatMulOp()); - return static_cast(c); -} - - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const -{ - return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); -} - - -CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); - -template struct Matx_DetOp +template struct Matx_FastInvOp { - double operator ()(const Matx<_Tp, m, m>& a) const + bool operator()(const Matx<_Tp, m, n>& a, Matx<_Tp, n, m>& b, int method) const { - Matx<_Tp, m, m> temp = a; - double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); - if( p == 0 ) - return p; - for( int i = 0; i < m; i++ ) - p *= temp(i, i); - return 1./p; + return invert(a, b, method) != 0; } }; - -template struct Matx_DetOp<_Tp, 1> -{ - double operator ()(const Matx<_Tp, 1, 1>& a) const - { - return a(0,0); - } -}; - - -template struct Matx_DetOp<_Tp, 2> -{ - double operator ()(const Matx<_Tp, 2, 2>& a) const - { - return a(0,0)*a(1,1) - a(0,1)*a(1,0); - } -}; - - -template struct Matx_DetOp<_Tp, 3> -{ - double operator ()(const Matx<_Tp, 3, 3>& a) const - { - return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - - a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + - a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); - } -}; - -template static inline -double determinant(const Matx<_Tp, m, m>& a) -{ - return Matx_DetOp<_Tp, m>()(a); -} - - -template static inline -double trace(const Matx<_Tp, m, n>& a) -{ - _Tp s = 0; - for( int i = 0; i < std::min(m, n); i++ ) - s += a(i,i); - return s; -} - - -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const -{ - return Matx<_Tp, n, m>(*this, Matx_TOp()); -} - - -template struct Matx_FastInvOp +template struct Matx_FastInvOp<_Tp, m, m> { bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const { - Matx<_Tp, m, m> temp = a; + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; - // assume that b is all 0's on input => make it a unity matrix - for( int i = 0; i < m; i++ ) - b(i, i) = (_Tp)1; + // assume that b is all 0's on input => make it a unity matrix + for (int i = 0; i < m; i++) + b(i, i) = (_Tp)1; - if( method == DECOMP_CHOLESKY ) - return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); + if (method == DECOMP_CHOLESKY) + return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); - return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; + return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; + } + else + { + return invert(a, b, method) != 0; + } } }; - -template struct Matx_FastInvOp<_Tp, 2> +template struct Matx_FastInvOp<_Tp, 2, 2> { - bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int) const + bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int /*method*/) const { - _Tp d = determinant(a); - if( d == 0 ) + _Tp d = (_Tp)determinant(a); + if (d == 0) return false; d = 1/d; b(1,1) = a(0,0)*d; @@ -814,13 +109,12 @@ template struct Matx_FastInvOp<_Tp, 2> } }; - -template struct Matx_FastInvOp<_Tp, 3> +template struct Matx_FastInvOp<_Tp, 3, 3> { - bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int) const + bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int /*method*/) const { _Tp d = (_Tp)determinant(a); - if( d == 0 ) + if (d == 0) return false; d = 1/d; b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; @@ -839,44 +133,43 @@ template struct Matx_FastInvOp<_Tp, 3> }; -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method) const +template struct Matx_FastSolveOp { - Matx<_Tp, n, m> b; - bool ok; - if( method == DECOMP_LU || method == DECOMP_CHOLESKY ) - ok = Matx_FastInvOp<_Tp, m>()(*this, b, method); - else + bool operator()(const Matx<_Tp, m, l>& a, const Matx<_Tp, m, n>& b, + Matx<_Tp, l, n>& x, int method) const { - Mat A(*this, false), B(b, false); - ok = (invert(A, B, method) != 0); + return cv::solve(a, b, x, method); } - return ok ? b : Matx<_Tp, n, m>::zeros(); -} +}; - -template struct Matx_FastSolveOp +template struct Matx_FastSolveOp<_Tp, m, m, n> { bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, Matx<_Tp, m, n>& x, int method) const { - Matx<_Tp, m, m> temp = a; - x = b; - if( method == DECOMP_CHOLESKY ) - return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; + x = b; + if( method == DECOMP_CHOLESKY ) + return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); - return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; + return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; + } + else + { + return cv::solve(a, b, x, method); + } } }; - -template struct Matx_FastSolveOp<_Tp, 2, 1> +template struct Matx_FastSolveOp<_Tp, 2, 2, 1> { bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, Matx<_Tp, 2, 1>& x, int) const { - _Tp d = determinant(a); - if( d == 0 ) + _Tp d = (_Tp)determinant(a); + if (d == 0) return false; d = 1/d; x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; @@ -885,14 +178,13 @@ template struct Matx_FastSolveOp<_Tp, 2, 1> } }; - -template struct Matx_FastSolveOp<_Tp, 3, 1> +template struct Matx_FastSolveOp<_Tp, 3, 3, 1> { bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, Matx<_Tp, 3, 1>& x, int) const { _Tp d = (_Tp)determinant(a); - if( d == 0 ) + if (d == 0) return false; d = 1/d; x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - @@ -910,2553 +202,285 @@ template struct Matx_FastSolveOp<_Tp, 3, 1> } }; +} // internal + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randu(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randn(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const +{ + Matx<_Tp, n, m> b; + bool ok = cv::internal::Matx_FastInvOp<_Tp, m, n>()(*this, b, method); + if (p_is_ok) *p_is_ok = ok; + return ok ? b : Matx<_Tp, n, m>::zeros(); +} template template inline Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const { Matx<_Tp, n, l> x; - bool ok; - if( method == DECOMP_LU || method == DECOMP_CHOLESKY ) - ok = Matx_FastSolveOp<_Tp, m, l>()(*this, rhs, x, method); - else - { - Mat A(*this, false), B(rhs, false), X(x, false); - ok = cv::solve(A, B, X, method); - } - + bool ok = cv::internal::Matx_FastSolveOp<_Tp, m, n, l>()(*this, rhs, x, method); return ok ? x : Matx<_Tp, n, l>::zeros(); } -template inline -Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const -{ - Matx<_Tp, n, 1> x = solve(reinterpret_cast&>(rhs), method); - return reinterpret_cast&>(x); -} - -template static inline -_AccTp normL2Sqr(const _Tp* a, int n) -{ - _AccTp s = 0; - int i=0; - #if CV_ENABLE_UNROLLED - for( ; i <= n - 4; i += 4 ) - { - _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = a[i]; - s += v*v; - } - return s; -} - - -template static inline -_AccTp normL1(const _Tp* a, int n) -{ - _AccTp s = 0; - int i = 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - s += (_AccTp)fast_abs(a[i]) + (_AccTp)fast_abs(a[i+1]) + - (_AccTp)fast_abs(a[i+2]) + (_AccTp)fast_abs(a[i+3]); - } -#endif - for( ; i < n; i++ ) - s += fast_abs(a[i]); - return s; -} - - -template static inline -_AccTp normInf(const _Tp* a, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - s = std::max(s, (_AccTp)fast_abs(a[i])); - return s; -} - - -template static inline -_AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += v*v; - } - return s; -} - -CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); -CV_EXPORTS float normL1_(const float* a, const float* b, int n); -CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); - -template<> inline float normL2Sqr(const float* a, const float* b, int n) -{ - if( n >= 8 ) - return normL2Sqr_(a, b, n); - float s = 0; - for( int i = 0; i < n; i++ ) - { - float v = a[i] - b[i]; - s += v*v; - } - return s; -} - - -template static inline -_AccTp normL1(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += std::abs(v); - } - return s; -} - -template<> inline float normL1(const float* a, const float* b, int n) -{ - if( n >= 8 ) - return normL1_(a, b, n); - float s = 0; - for( int i = 0; i < n; i++ ) - { - float v = a[i] - b[i]; - s += std::abs(v); - } - return s; -} - -template<> inline int normL1(const uchar* a, const uchar* b, int n) -{ - return normL1_(a, b, n); -} - -template static inline -_AccTp normInf(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - { - _AccTp v0 = a[i] - b[i]; - s = std::max(s, std::abs(v0)); - } - return s; -} - - -template static inline -double norm(const Matx<_Tp, m, n>& M) -{ - return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); -} - - -template static inline -double norm(const Matx<_Tp, m, n>& M, int normType) -{ - return normType == NORM_INF ? (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n) : - normType == NORM_L1 ? (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n) : - std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); -} - - -template static inline -bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - if( a.val[i] != b.val[i] ) return false; - return true; -} - -template static inline -bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return !(a == b); -} - - -template static inline -MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) -{ - MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); - return (commaInitializer, val); -} - -template inline -MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) - : dst(_mtx), idx(0) -{} - -template template inline -MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) -{ - CV_DbgAssert( idx < m*n ); - dst->val[idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const -{ - CV_DbgAssert( idx == n*m ); - return *dst; -} - -/////////////////////////// short vector (Vec) ///////////////////////////// - -template inline Vec<_Tp, cn>::Vec() -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0) - : Matx<_Tp, cn, 1>(v0) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) - : Matx<_Tp, cn, 1>(v0, v1) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) - : Matx<_Tp, cn, 1>(v0, v1, v2) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) -{} - -template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) -{} - -template inline Vec<_Tp, cn>::Vec(const _Tp* values) - : Matx<_Tp, cn, 1>(values) -{} - - -template inline Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) - : Matx<_Tp, cn, 1>(m.val) -{} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) -: Matx<_Tp, cn, 1>(a, b, op) -{} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) -: Matx<_Tp, cn, 1>(a, b, op) -{} - -template template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) -: Matx<_Tp, cn, 1>(a, alpha, op) -{} - -template inline Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = alpha; - return v; -} - -template inline Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const -{ - Vec<_Tp, cn> w; - for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); - return w; -} - -template Vec<_Tp, 2> conjugate(const Vec<_Tp, 2>& v) -{ - return Vec<_Tp, 2>(v[0], -v[1]); -} - -template Vec<_Tp, 4> conjugate(const Vec<_Tp, 4>& v) -{ - return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); -} - -template<> inline Vec Vec::conj() const -{ - return conjugate(*this); -} - -template<> inline Vec Vec::conj() const -{ - return conjugate(*this); -} - -template<> inline Vec Vec::conj() const -{ - return conjugate(*this); -} - -template<> inline Vec Vec::conj() const -{ - return conjugate(*this); -} - -template inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const -{ - CV_Error(CV_StsError, "for arbitrary-size vector there is no cross-product defined"); - return Vec<_Tp, cn>(); -} - -template template -inline Vec<_Tp, cn>::operator Vec() const -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); - return v; -} - -template inline Vec<_Tp, cn>::operator CvScalar() const -{ - CvScalar s = {{0,0,0,0}}; - int i; - for( i = 0; i < std::min(cn, 4); i++ ) s.val[i] = this->val[i]; - for( ; i < 4; i++ ) s.val[i] = 0; - return s; -} - -template inline const _Tp& Vec<_Tp, cn>::operator [](int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline _Tp& Vec<_Tp, cn>::operator [](int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline const _Tp& Vec<_Tp, cn>::operator ()(int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline _Tp& Vec<_Tp, cn>::operator ()(int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template static inline Vec<_Tp1, cn>& -operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - -template static inline Vec<_Tp1, cn>& -operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - -template static inline Vec<_Tp, cn> -operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_AddOp()); -} - -template static inline Vec<_Tp, cn> -operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_SubOp()); -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) -{ - float ialpha = 1.f/alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline Vec<_Tp, cn> -operator * (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator * (int alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator * (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator * (float alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator * (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator * (double alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator / (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator / (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator / (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline Vec<_Tp, cn> -operator - (const Vec<_Tp, cn>& a) -{ - Vec<_Tp,cn> t; - for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); - return t; -} - -template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), - saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), - saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), - saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); -} - -template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - v1 = v1 * v2; - return v1; -} - -template<> inline Vec Vec::cross(const Vec& v) const -{ - return Vec(val[1]*v.val[2] - val[2]*v.val[1], - val[2]*v.val[0] - val[0]*v.val[2], - val[0]*v.val[1] - val[1]*v.val[0]); -} - -template<> inline Vec Vec::cross(const Vec& v) const -{ - return Vec(val[1]*v.val[2] - val[2]*v.val[1], - val[2]*v.val[0] - val[0]*v.val[2], - val[0]*v.val[1] - val[1]*v.val[0]); -} - -template inline Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) -{ - double nv = norm(v); - return v * (nv ? 1./nv : 0.); -} - -template static inline -VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) -{ - VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); - return (commaInitializer, val); -} - -template inline -VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) - : MatxCommaInitializer<_Tp, cn, 1>(_vec) -{} - -template template inline -VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) -{ - CV_DbgAssert( this->idx < cn ); - this->dst->val[this->idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const -{ - CV_DbgAssert( this->idx == cn ); - return *this->dst; -} - -//////////////////////////////// Complex ////////////////////////////// - -template inline Complex<_Tp>::Complex() : re(0), im(0) {} -template inline Complex<_Tp>::Complex( _Tp _re, _Tp _im ) : re(_re), im(_im) {} -template template inline Complex<_Tp>::operator Complex() const -{ return Complex(saturate_cast(re), saturate_cast(im)); } -template inline Complex<_Tp> Complex<_Tp>::conj() const -{ return Complex<_Tp>(re, -im); } - -template static inline -bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return a.re == b.re && a.im == b.im; } - -template static inline -bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return a.re != b.re || a.im != b.im; } - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return Complex<_Tp>( a.re + b.re, a.im + b.im ); } - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) -{ a.re += b.re; a.im += b.im; return a; } - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return Complex<_Tp>( a.re - b.re, a.im - b.im ); } - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ a.re -= b.re; a.im -= b.im; return a; } - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a) -{ return Complex<_Tp>(-a.re, -a.im); } - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); } - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) -{ return Complex<_Tp>( a.re*b, a.im*b ); } - -template static inline -Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) -{ return Complex<_Tp>( a.re*b, a.im*b ); } - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) -{ return Complex<_Tp>( a.re + b, a.im ); } - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) -{ return Complex<_Tp>( a.re - b, a.im ); } - -template static inline -Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) -{ return Complex<_Tp>( a.re + b, a.im ); } - -template static inline -Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) -{ return Complex<_Tp>( b - a.re, -a.im ); } - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) -{ a.re += b; return a; } - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) -{ a.re -= b; return a; } - -template static inline -Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) -{ a.re *= b; a.im *= b; return a; } - -template static inline -double abs(const Complex<_Tp>& a) -{ return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); } - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - double t = 1./((double)b.re*b.re + (double)b.im*b.im); - return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), - (_Tp)((-a.re*b.im + a.im*b.re)*t) ); -} - -template static inline -Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return (a = a / b); -} - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - return Complex<_Tp>( a.re*t, a.im*t ); -} -template static inline -Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>(b)/a; -} - -template static inline -Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - a.re *= t; a.im *= t; return a; -} - -//////////////////////////////// 2D Point //////////////////////////////// - -template inline Point_<_Tp>::Point_() : x(0), y(0) {} -template inline Point_<_Tp>::Point_(_Tp _x, _Tp _y) : x(_x), y(_y) {} -template inline Point_<_Tp>::Point_(const Point_& pt) : x(pt.x), y(pt.y) {} -template inline Point_<_Tp>::Point_(const CvPoint& pt) : x((_Tp)pt.x), y((_Tp)pt.y) {} -template inline Point_<_Tp>::Point_(const CvPoint2D32f& pt) - : x(saturate_cast<_Tp>(pt.x)), y(saturate_cast<_Tp>(pt.y)) {} -template inline Point_<_Tp>::Point_(const Size_<_Tp>& sz) : x(sz.width), y(sz.height) {} -template inline Point_<_Tp>::Point_(const Vec<_Tp,2>& v) : x(v[0]), y(v[1]) {} -template inline Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) -{ x = pt.x; y = pt.y; return *this; } - -template template inline Point_<_Tp>::operator Point_<_Tp2>() const -{ return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); } -template inline Point_<_Tp>::operator CvPoint() const -{ return cvPoint(saturate_cast(x), saturate_cast(y)); } -template inline Point_<_Tp>::operator CvPoint2D32f() const -{ return cvPoint2D32f((float)x, (float)y); } -template inline Point_<_Tp>::operator Vec<_Tp, 2>() const -{ return Vec<_Tp, 2>(x, y); } - -template inline _Tp Point_<_Tp>::dot(const Point_& pt) const -{ return saturate_cast<_Tp>(x*pt.x + y*pt.y); } -template inline double Point_<_Tp>::ddot(const Point_& pt) const -{ return (double)x*pt.x + (double)y*pt.y; } - -template inline double Point_<_Tp>::cross(const Point_& pt) const -{ return (double)x*pt.y - (double)y*pt.x; } - -template static inline Point_<_Tp>& -operator += (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x = saturate_cast<_Tp>(a.x + b.x); - a.y = saturate_cast<_Tp>(a.y + b.y); - return a; -} - -template static inline Point_<_Tp>& -operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x = saturate_cast<_Tp>(a.x - b.x); - a.y = saturate_cast<_Tp>(a.y - b.y); - return a; -} - -template static inline Point_<_Tp>& -operator *= (Point_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - return a; -} - -template static inline Point_<_Tp>& -operator *= (Point_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - return a; -} - -template static inline Point_<_Tp>& -operator *= (Point_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - return a; -} - -template static inline double norm(const Point_<_Tp>& pt) -{ return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); } - -template static inline bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ return a.x == b.x && a.y == b.y; } - -template static inline bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ return a.x != b.x || a.y != b.y; } - -template static inline Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); } - -template static inline Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); } -template static inline Point_<_Tp> operator - (const Point_<_Tp>& a) -{ return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); } +////////////////////////// Augmenting algebraic & logical operations ////////////////////////// + +#define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + static inline A& operator op (A& a, const B& b) { cvop; return a; } + +#define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_TN(op, cvop, A) \ + template static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \ + template static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } + +CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a,Mat(b),a), Mat) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a,Mat(b),a), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, int b) -{ return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a,Mat(b),a), Mat) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a,Mat(b),a), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (int a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } +CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) +CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, float b) -{ return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } +CV_MAT_AUG_OPERATOR (/=, cv::divide(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) +CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), a), Mat) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), a), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (float a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), a), Mat) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), a), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, double b) -{ return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), a), Mat) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), a), Mat_<_Tp>) -template static inline Point_<_Tp> operator * (double a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Mat) +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), a), Mat) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), a), Mat_<_Tp>) -//////////////////////////////// 3D Point //////////////////////////////// +#undef CV_MAT_AUG_OPERATOR_TN +#undef CV_MAT_AUG_OPERATOR_T +#undef CV_MAT_AUG_OPERATOR +#undef CV_MAT_AUG_OPERATOR1 -template inline Point3_<_Tp>::Point3_() : x(0), y(0), z(0) {} -template inline Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) : x(_x), y(_y), z(_z) {} -template inline Point3_<_Tp>::Point3_(const Point3_& pt) : x(pt.x), y(pt.y), z(pt.z) {} -template inline Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) : x(pt.x), y(pt.y), z(_Tp()) {} -template inline Point3_<_Tp>::Point3_(const CvPoint3D32f& pt) : - x(saturate_cast<_Tp>(pt.x)), y(saturate_cast<_Tp>(pt.y)), z(saturate_cast<_Tp>(pt.z)) {} -template inline Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) : x(v[0]), y(v[1]), z(v[2]) {} -template template inline Point3_<_Tp>::operator Point3_<_Tp2>() const -{ return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); } -template inline Point3_<_Tp>::operator CvPoint3D32f() const -{ return cvPoint3D32f((float)x, (float)y, (float)z); } +///////////////////////////////////////////// SVD ///////////////////////////////////////////// -template inline Point3_<_Tp>::operator Vec<_Tp, 3>() const -{ return Vec<_Tp, 3>(x, y, z); } - -template inline Point3_<_Tp>& Point3_<_Tp>::operator = (const Point3_& pt) -{ x = pt.x; y = pt.y; z = pt.z; return *this; } - -template inline _Tp Point3_<_Tp>::dot(const Point3_& pt) const -{ return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); } -template inline double Point3_<_Tp>::ddot(const Point3_& pt) const -{ return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; } - -template inline Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const -{ - return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); -} - -template static inline Point3_<_Tp>& -operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) +inline SVD::SVD() {} +inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } +inline void SVD::solveZ( InputArray m, OutputArray _dst ) { - a.x = saturate_cast<_Tp>(a.x + b.x); - a.y = saturate_cast<_Tp>(a.y + b.y); - a.z = saturate_cast<_Tp>(a.z + b.z); - return a; + Mat mtx = m.getMat(); + SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); + _dst.create(svd.vt.cols, 1, svd.vt.type()); + Mat dst = _dst.getMat(); + svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); } -template static inline Point3_<_Tp>& -operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) +template inline void + SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) { - a.x = saturate_cast<_Tp>(a.x - b.x); - a.y = saturate_cast<_Tp>(a.y - b.y); - a.z = saturate_cast<_Tp>(a.z - b.z); - return a; + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); + SVD::compute(_a, _w, _u, _vt); + CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); } -template static inline Point3_<_Tp>& -operator *= (Point3_<_Tp>& a, int b) +template inline void +SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) { - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - a.z = saturate_cast<_Tp>(a.z*b); - return a; + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _w(w, false); + SVD::compute(_a, _w); + CV_Assert(_w.data == (uchar*)&w.val[0]); +} + +template inline void +SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, + const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, + Matx<_Tp, n, nb>& dst ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); + SVD::backSubst(_w, _u, _vt, _rhs, _dst); + CV_Assert(_dst.data == (uchar*)&dst.val[0]); } -template static inline Point3_<_Tp>& -operator *= (Point3_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - a.z = saturate_cast<_Tp>(a.z*b); - return a; -} - -template static inline Point3_<_Tp>& -operator *= (Point3_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x*b); - a.y = saturate_cast<_Tp>(a.y*b); - a.z = saturate_cast<_Tp>(a.z*b); - return a; -} - -template static inline double norm(const Point3_<_Tp>& pt) -{ return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); } - -template static inline bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ return a.x == b.x && a.y == b.y && a.z == b.z; } - -template static inline bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ return a.x != b.x || a.y != b.y || a.z != b.z; } - -template static inline Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), - saturate_cast<_Tp>(a.y + b.y), - saturate_cast<_Tp>(a.z + b.z)); } - -template static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), - saturate_cast<_Tp>(a.y - b.y), - saturate_cast<_Tp>(a.z - b.z)); } - -template static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a) -{ return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), - saturate_cast<_Tp>(-a.y), - saturate_cast<_Tp>(-a.z) ); } - -template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), - saturate_cast<_Tp>(a.y*b), - saturate_cast<_Tp>(a.z*b) ); } - -template static inline Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(b.x*a), - saturate_cast<_Tp>(b.y*a), - saturate_cast<_Tp>(b.z*a) ); } - -template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), - saturate_cast<_Tp>(a.y*b), - saturate_cast<_Tp>(a.z*b) ); } - -template static inline Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(b.x*a), - saturate_cast<_Tp>(b.y*a), - saturate_cast<_Tp>(b.z*a) ); } - -template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), - saturate_cast<_Tp>(a.y*b), - saturate_cast<_Tp>(a.z*b) ); } - -template static inline Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) -{ return Point3_<_Tp>( saturate_cast<_Tp>(b.x*a), - saturate_cast<_Tp>(b.y*a), - saturate_cast<_Tp>(b.z*a) ); } - -//////////////////////////////// Size //////////////////////////////// - -template inline Size_<_Tp>::Size_() - : width(0), height(0) {} -template inline Size_<_Tp>::Size_(_Tp _width, _Tp _height) - : width(_width), height(_height) {} -template inline Size_<_Tp>::Size_(const Size_& sz) - : width(sz.width), height(sz.height) {} -template inline Size_<_Tp>::Size_(const CvSize& sz) - : width(saturate_cast<_Tp>(sz.width)), height(saturate_cast<_Tp>(sz.height)) {} -template inline Size_<_Tp>::Size_(const CvSize2D32f& sz) - : width(saturate_cast<_Tp>(sz.width)), height(saturate_cast<_Tp>(sz.height)) {} -template inline Size_<_Tp>::Size_(const Point_<_Tp>& pt) : width(pt.x), height(pt.y) {} - -template template inline Size_<_Tp>::operator Size_<_Tp2>() const -{ return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } -template inline Size_<_Tp>::operator CvSize() const -{ return cvSize(saturate_cast(width), saturate_cast(height)); } -template inline Size_<_Tp>::operator CvSize2D32f() const -{ return cvSize2D32f((float)width, (float)height); } - -template inline Size_<_Tp>& Size_<_Tp>::operator = (const Size_<_Tp>& sz) -{ width = sz.width; height = sz.height; return *this; } -template static inline Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) -{ return Size_<_Tp>(a.width * b, a.height * b); } -template static inline Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ return Size_<_Tp>(a.width + b.width, a.height + b.height); } -template static inline Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ return Size_<_Tp>(a.width - b.width, a.height - b.height); } -template inline _Tp Size_<_Tp>::area() const { return width*height; } - -template static inline Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) -{ a.width += b.width; a.height += b.height; return a; } -template static inline Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) -{ a.width -= b.width; a.height -= b.height; return a; } - -template static inline bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ return a.width == b.width && a.height == b.height; } -template static inline bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ return a.width != b.width || a.height != b.height; } - -//////////////////////////////// Rect //////////////////////////////// -template inline Rect_<_Tp>::Rect_() : x(0), y(0), width(0), height(0) {} -template inline Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) : x(_x), y(_y), width(_width), height(_height) {} -template inline Rect_<_Tp>::Rect_(const Rect_<_Tp>& r) : x(r.x), y(r.y), width(r.width), height(r.height) {} -template inline Rect_<_Tp>::Rect_(const CvRect& r) : x((_Tp)r.x), y((_Tp)r.y), width((_Tp)r.width), height((_Tp)r.height) {} -template inline Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) : - x(org.x), y(org.y), width(sz.width), height(sz.height) {} -template inline Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) -{ - x = std::min(pt1.x, pt2.x); y = std::min(pt1.y, pt2.y); - width = std::max(pt1.x, pt2.x) - x; height = std::max(pt1.y, pt2.y) - y; -} -template inline Rect_<_Tp>& Rect_<_Tp>::operator = ( const Rect_<_Tp>& r ) -{ x = r.x; y = r.y; width = r.width; height = r.height; return *this; } - -template inline Point_<_Tp> Rect_<_Tp>::tl() const { return Point_<_Tp>(x,y); } -template inline Point_<_Tp> Rect_<_Tp>::br() const { return Point_<_Tp>(x+width, y+height); } - -template static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ a.x += b.x; a.y += b.y; return a; } -template static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ a.x -= b.x; a.y -= b.y; return a; } - -template static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ a.width += b.width; a.height += b.height; return a; } - -template static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ a.width -= b.width; a.height -= b.height; return a; } - -template static inline Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - _Tp x1 = std::max(a.x, b.x), y1 = std::max(a.y, b.y); - a.width = std::min(a.x + a.width, b.x + b.width) - x1; - a.height = std::min(a.y + a.height, b.y + b.height) - y1; - a.x = x1; a.y = y1; - if( a.width <= 0 || a.height <= 0 ) - a = Rect(); - return a; -} - -template static inline Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - _Tp x1 = std::min(a.x, b.x), y1 = std::min(a.y, b.y); - a.width = std::max(a.x + a.width, b.x + b.width) - x1; - a.height = std::max(a.y + a.height, b.y + b.height) - y1; - a.x = x1; a.y = y1; - return a; -} - -template inline Size_<_Tp> Rect_<_Tp>::size() const { return Size_<_Tp>(width, height); } -template inline _Tp Rect_<_Tp>::area() const { return width*height; } - -template template inline Rect_<_Tp>::operator Rect_<_Tp2>() const -{ return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), - saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } -template inline Rect_<_Tp>::operator CvRect() const -{ return cvRect(saturate_cast(x), saturate_cast(y), - saturate_cast(width), saturate_cast(height)); } - -template inline bool Rect_<_Tp>::contains(const Point_<_Tp>& pt) const -{ return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; } - -template static inline bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; -} - -template static inline bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; -} - -template static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); -} - -template static inline Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); -} - -template static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) -{ - return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); -} - -template static inline Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c &= b; -} - -template static inline Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c |= b; -} - -template inline bool Point_<_Tp>::inside( const Rect_<_Tp>& r ) const -{ - return r.contains(*this); -} - -inline RotatedRect::RotatedRect() { angle = 0; } -inline RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) - : center(_center), size(_size), angle(_angle) {} -inline RotatedRect::RotatedRect(const CvBox2D& box) - : center(box.center), size(box.size), angle(box.angle) {} -inline RotatedRect::operator CvBox2D() const -{ - CvBox2D box; box.center = center; box.size = size; box.angle = angle; - return box; -} - -//////////////////////////////// Scalar_ /////////////////////////////// - -template inline Scalar_<_Tp>::Scalar_() -{ this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; } - -template inline Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ this->val[0] = v0; this->val[1] = v1; this->val[2] = v2; this->val[3] = v3; } - -template inline Scalar_<_Tp>::Scalar_(const CvScalar& s) -{ - this->val[0] = saturate_cast<_Tp>(s.val[0]); - this->val[1] = saturate_cast<_Tp>(s.val[1]); - this->val[2] = saturate_cast<_Tp>(s.val[2]); - this->val[3] = saturate_cast<_Tp>(s.val[3]); -} - -template inline Scalar_<_Tp>::Scalar_(_Tp v0) -{ this->val[0] = v0; this->val[1] = this->val[2] = this->val[3] = 0; } - -template inline Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) -{ return Scalar_<_Tp>(v0, v0, v0, v0); } -template inline Scalar_<_Tp>::operator CvScalar() const -{ return cvScalar(this->val[0], this->val[1], this->val[2], this->val[3]); } - -template template inline Scalar_<_Tp>::operator Scalar_() const -{ - return Scalar_(saturate_cast(this->val[0]), - saturate_cast(this->val[1]), - saturate_cast(this->val[2]), - saturate_cast(this->val[3])); -} - -template static inline Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] = saturate_cast<_Tp>(a.val[0] + b.val[0]); - a.val[1] = saturate_cast<_Tp>(a.val[1] + b.val[1]); - a.val[2] = saturate_cast<_Tp>(a.val[2] + b.val[2]); - a.val[3] = saturate_cast<_Tp>(a.val[3] + b.val[3]); - return a; -} - -template static inline Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] = saturate_cast<_Tp>(a.val[0] - b.val[0]); - a.val[1] = saturate_cast<_Tp>(a.val[1] - b.val[1]); - a.val[2] = saturate_cast<_Tp>(a.val[2] - b.val[2]); - a.val[3] = saturate_cast<_Tp>(a.val[3] - b.val[3]); - return a; -} - -template static inline Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) -{ - a.val[0] = saturate_cast<_Tp>(a.val[0] * v); - a.val[1] = saturate_cast<_Tp>(a.val[1] * v); - a.val[2] = saturate_cast<_Tp>(a.val[2] * v); - a.val[3] = saturate_cast<_Tp>(a.val[3] * v); - return a; -} - -template inline Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& t, double scale ) const -{ - return Scalar_<_Tp>( saturate_cast<_Tp>(this->val[0]*t.val[0]*scale), - saturate_cast<_Tp>(this->val[1]*t.val[1]*scale), - saturate_cast<_Tp>(this->val[2]*t.val[2]*scale), - saturate_cast<_Tp>(this->val[3]*t.val[3]*scale)); -} - -template static inline bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] == b.val[0] && a.val[1] == b.val[1] && - a.val[2] == b.val[2] && a.val[3] == b.val[3]; -} - -template static inline bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] != b.val[0] || a.val[1] != b.val[1] || - a.val[2] != b.val[2] || a.val[3] != b.val[3]; -} - -template static inline Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] + b.val[0]), - saturate_cast<_Tp>(a.val[1] + b.val[1]), - saturate_cast<_Tp>(a.val[2] + b.val[2]), - saturate_cast<_Tp>(a.val[3] + b.val[3])); -} - -template static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), - saturate_cast<_Tp>(a.val[1] - b.val[1]), - saturate_cast<_Tp>(a.val[2] - b.val[2]), - saturate_cast<_Tp>(a.val[3] - b.val[3])); -} - -template static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] * alpha), - saturate_cast<_Tp>(a.val[1] * alpha), - saturate_cast<_Tp>(a.val[2] * alpha), - saturate_cast<_Tp>(a.val[3] * alpha)); -} - -template static inline Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) -{ - return a*alpha; -} - -template static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), saturate_cast<_Tp>(-a.val[1]), - saturate_cast<_Tp>(-a.val[2]), saturate_cast<_Tp>(-a.val[3])); -} - - -template static inline Scalar_<_Tp> -operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), - saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), - saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), - saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); -} - -template static inline Scalar_<_Tp>& -operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a*b; - return a; -} - -template inline Scalar_<_Tp> Scalar_<_Tp>::conj() const -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0]), - saturate_cast<_Tp>(-this->val[1]), - saturate_cast<_Tp>(-this->val[2]), - saturate_cast<_Tp>(-this->val[3])); -} - -template inline bool Scalar_<_Tp>::isReal() const -{ - return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] / alpha), - saturate_cast<_Tp>(a.val[1] / alpha), - saturate_cast<_Tp>(a.val[2] / alpha), - saturate_cast<_Tp>(a.val[3] / alpha)); -} - -template static inline -Scalar_ operator / (const Scalar_& a, float alpha) -{ - float s = 1/alpha; - return Scalar_(a.val[0]*s, a.val[1]*s, a.val[2]*s, a.val[3]*s); -} - -template static inline -Scalar_ operator / (const Scalar_& a, double alpha) -{ - double s = 1/alpha; - return Scalar_(a.val[0]*s, a.val[1]*s, a.val[2]*s, a.val[3]*s); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) -{ - a = a/alpha; - return a; -} - -template static inline -Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) -{ - _Tp s = a/(b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); - return b.conj()*s; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return a*((_Tp)1/b); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a/b; - return a; -} - -//////////////////////////////// Range ///////////////////////////////// - -inline Range::Range() : start(0), end(0) {} -inline Range::Range(int _start, int _end) : start(_start), end(_end) {} -inline Range::Range(const CvSlice& slice) : start(slice.start_index), end(slice.end_index) -{ - if( start == 0 && end == CV_WHOLE_SEQ_END_INDEX ) - *this = Range::all(); -} - -inline int Range::size() const { return end - start; } -inline bool Range::empty() const { return start == end; } -inline Range Range::all() { return Range(INT_MIN, INT_MAX); } - -static inline bool operator == (const Range& r1, const Range& r2) -{ return r1.start == r2.start && r1.end == r2.end; } - -static inline bool operator != (const Range& r1, const Range& r2) -{ return !(r1 == r2); } - -static inline bool operator !(const Range& r) -{ return r.start == r.end; } - -static inline Range operator & (const Range& r1, const Range& r2) -{ - Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); - r.end = std::max(r.end, r.start); - return r; -} - -static inline Range& operator &= (Range& r1, const Range& r2) -{ - r1 = r1 & r2; - return r1; -} - -static inline Range operator + (const Range& r1, int delta) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline Range operator + (int delta, const Range& r1) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline Range operator - (const Range& r1, int delta) -{ - return r1 + (-delta); -} - -inline Range::operator CvSlice() const -{ return *this != Range::all() ? cvSlice(start, end) : CV_WHOLE_SEQ; } - - - -//////////////////////////////// Vector //////////////////////////////// - -// template vector class. It is similar to STL's vector, -// with a few important differences: -// 1) it can be created on top of user-allocated data w/o copying it -// 2) vector b = a means copying the header, -// not the underlying data (use clone() to make a deep copy) -template class Vector -{ -public: - typedef _Tp value_type; - typedef _Tp* iterator; - typedef const _Tp* const_iterator; - typedef _Tp& reference; - typedef const _Tp& const_reference; - - struct Hdr - { - Hdr() : data(0), datastart(0), refcount(0), size(0), capacity(0) {}; - _Tp* data; - _Tp* datastart; - int* refcount; - size_t size; - size_t capacity; - }; - - Vector() {} - Vector(size_t _size) { resize(_size); } - Vector(size_t _size, const _Tp& val) - { - resize(_size); - for(size_t i = 0; i < _size; i++) - hdr.data[i] = val; - } - Vector(_Tp* _data, size_t _size, bool _copyData=false) - { set(_data, _size, _copyData); } - - template Vector(const Vec<_Tp, n>& vec) - { set((_Tp*)&vec.val[0], n, true); } - - Vector(const std::vector<_Tp>& vec, bool _copyData=false) - { set(!vec.empty() ? (_Tp*)&vec[0] : 0, vec.size(), _copyData); } - - Vector(const Vector& d) { *this = d; } - - Vector(const Vector& d, const Range& r_) - { - Range r = r_ == Range::all() ? Range(0, d.size()) : r_; - /*if( r == Range::all() ) - r = Range(0, d.size());*/ - if( r.size() > 0 && r.start >= 0 && r.end <= d.size() ) - { - if( d.hdr.refcount ) - CV_XADD(d.hdr.refcount, 1); - hdr.refcount = d.hdr.refcount; - hdr.datastart = d.hdr.datastart; - hdr.data = d.hdr.data + r.start; - hdr.capacity = hdr.size = r.size(); - } - } - - Vector<_Tp>& operator = (const Vector& d) - { - if( this != &d ) - { - if( d.hdr.refcount ) - CV_XADD(d.hdr.refcount, 1); - release(); - hdr = d.hdr; - } - return *this; - } - - ~Vector() { release(); } - - Vector<_Tp> clone() const - { return hdr.data ? Vector<_Tp>(hdr.data, hdr.size, true) : Vector<_Tp>(); } - - void copyTo(Vector<_Tp>& vec) const - { - size_t i, sz = size(); - vec.resize(sz); - const _Tp* src = hdr.data; - _Tp* dst = vec.hdr.data; - for( i = 0; i < sz; i++ ) - dst[i] = src[i]; - } - - void copyTo(std::vector<_Tp>& vec) const - { - size_t i, sz = size(); - vec.resize(sz); - const _Tp* src = hdr.data; - _Tp* dst = sz ? &vec[0] : 0; - for( i = 0; i < sz; i++ ) - dst[i] = src[i]; - } - - operator CvMat() const - { return cvMat((int)size(), 1, type(), (void*)hdr.data); } - - _Tp& operator [] (size_t i) { CV_DbgAssert( i < size() ); return hdr.data[i]; } - const _Tp& operator [] (size_t i) const { CV_DbgAssert( i < size() ); return hdr.data[i]; } - Vector operator() (const Range& r) const { return Vector(*this, r); } - _Tp& back() { CV_DbgAssert(!empty()); return hdr.data[hdr.size-1]; } - const _Tp& back() const { CV_DbgAssert(!empty()); return hdr.data[hdr.size-1]; } - _Tp& front() { CV_DbgAssert(!empty()); return hdr.data[0]; } - const _Tp& front() const { CV_DbgAssert(!empty()); return hdr.data[0]; } - - _Tp* begin() { return hdr.data; } - _Tp* end() { return hdr.data + hdr.size; } - const _Tp* begin() const { return hdr.data; } - const _Tp* end() const { return hdr.data + hdr.size; } - - void addref() { if( hdr.refcount ) CV_XADD(hdr.refcount, 1); } - void release() - { - if( hdr.refcount && CV_XADD(hdr.refcount, -1) == 1 ) - { - delete[] hdr.datastart; - delete hdr.refcount; - } - hdr = Hdr(); - } - - void set(_Tp* _data, size_t _size, bool _copyData=false) - { - if( !_copyData ) - { - release(); - hdr.data = hdr.datastart = _data; - hdr.size = hdr.capacity = _size; - hdr.refcount = 0; - } - else - { - reserve(_size); - for( size_t i = 0; i < _size; i++ ) - hdr.data[i] = _data[i]; - hdr.size = _size; - } - } - - void reserve(size_t newCapacity) - { - _Tp* newData; - int* newRefcount; - size_t i, oldSize = hdr.size; - if( (!hdr.refcount || *hdr.refcount == 1) && hdr.capacity >= newCapacity ) - return; - newCapacity = std::max(newCapacity, oldSize); - newData = new _Tp[newCapacity]; - newRefcount = new int(1); - for( i = 0; i < oldSize; i++ ) - newData[i] = hdr.data[i]; - release(); - hdr.data = hdr.datastart = newData; - hdr.capacity = newCapacity; - hdr.size = oldSize; - hdr.refcount = newRefcount; - } - - void resize(size_t newSize) - { - size_t i; - newSize = std::max(newSize, (size_t)0); - if( (!hdr.refcount || *hdr.refcount == 1) && hdr.size == newSize ) - return; - if( newSize > hdr.capacity ) - reserve(std::max(newSize, std::max((size_t)4, hdr.capacity*2))); - for( i = hdr.size; i < newSize; i++ ) - hdr.data[i] = _Tp(); - hdr.size = newSize; - } - - Vector<_Tp>& push_back(const _Tp& elem) - { - if( hdr.size == hdr.capacity ) - reserve( std::max((size_t)4, hdr.capacity*2) ); - hdr.data[hdr.size++] = elem; - return *this; - } - - Vector<_Tp>& pop_back() - { - if( hdr.size > 0 ) - --hdr.size; - return *this; - } - - size_t size() const { return hdr.size; } - size_t capacity() const { return hdr.capacity; } - bool empty() const { return hdr.size == 0; } - void clear() { resize(0); } - int type() const { return DataType<_Tp>::type; } - -protected: - Hdr hdr; -}; - - -template inline typename DataType<_Tp>::work_type -dot(const Vector<_Tp>& v1, const Vector<_Tp>& v2) -{ - typedef typename DataType<_Tp>::work_type _Tw; - size_t i = 0, n = v1.size(); - assert(v1.size() == v2.size()); - - _Tw s = 0; - const _Tp *ptr1 = &v1[0], *ptr2 = &v2[0]; - for( ; i < n; i++ ) - s += (_Tw)ptr1[i]*ptr2[i]; - - return s; -} +/////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// -// Multiply-with-Carry RNG -inline RNG::RNG() { state = 0xffffffff; } +inline RNG::RNG() { state = 0xffffffff; } inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } + +inline RNG::operator uchar() { return (uchar)next(); } +inline RNG::operator schar() { return (schar)next(); } +inline RNG::operator ushort() { return (ushort)next(); } +inline RNG::operator short() { return (short)next(); } +inline RNG::operator int() { return (int)next(); } +inline RNG::operator unsigned() { return next(); } +inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } +inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } + +inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } +inline unsigned RNG::operator ()() { return next(); } + +inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } +inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } +inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } + +inline bool RNG::operator ==(const RNG& other) const { return state == other.state; } + inline unsigned RNG::next() { - state = (uint64)(unsigned)state*CV_RNG_COEFF + (unsigned)(state >> 32); + state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); return (unsigned)state; } -inline RNG::operator uchar() { return (uchar)next(); } -inline RNG::operator schar() { return (schar)next(); } -inline RNG::operator ushort() { return (ushort)next(); } -inline RNG::operator short() { return (short)next(); } -inline RNG::operator unsigned() { return next(); } -inline unsigned RNG::operator ()(unsigned N) {return (unsigned)uniform(0,N);} -inline unsigned RNG::operator ()() {return next();} -inline RNG::operator int() { return (int)next(); } -// * (2^32-1)^-1 -inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } -inline RNG::operator double() +//! returns the next unifomly-distributed random number of the specified type +template static inline _Tp randu() { - unsigned t = next(); - return (((uint64)t << 32) | next())*5.4210108624275221700372640043497e-20; + return (_Tp)theRNG(); } -inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next()%(b - a) + a); } -inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } -inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } -inline TermCriteria::TermCriteria() : type(0), maxCount(0), epsilon(0) {} -inline TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) - : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} -inline TermCriteria::TermCriteria(const CvTermCriteria& criteria) - : type(criteria.type), maxCount(criteria.max_iter), epsilon(criteria.epsilon) {} -inline TermCriteria::operator CvTermCriteria() const -{ return cvTermCriteria(type, maxCount, epsilon); } +///////////////////////////////// Formatted string generation ///////////////////////////////// -inline uchar* LineIterator::operator *() { return ptr; } -inline LineIterator& LineIterator::operator ++() -{ - int mask = err < 0 ? -1 : 0; - err += minusDelta + (plusDelta & mask); - ptr += minusStep + (plusStep & mask); - return *this; -} -inline LineIterator LineIterator::operator ++(int) -{ - LineIterator it = *this; - ++(*this); - return it; -} -inline Point LineIterator::pos() const -{ - Point p; - p.y = (int)((ptr - ptr0)/step); - p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize); - return p; -} - -/////////////////////////////// AutoBuffer //////////////////////////////////////// - -template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer() -{ - ptr = buf; - size = fixed_size; -} - -template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) -{ - ptr = buf; - size = fixed_size; - allocate(_size); -} - -template inline AutoBuffer<_Tp, fixed_size>::~AutoBuffer() -{ deallocate(); } - -template inline void AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) -{ - if(_size <= size) - return; - deallocate(); - if(_size > fixed_size) - { - ptr = cv::allocate<_Tp>(_size); - size = _size; - } -} - -template inline void AutoBuffer<_Tp, fixed_size>::deallocate() -{ - if( ptr != buf ) - { - cv::deallocate<_Tp>(ptr, size); - ptr = buf; - size = fixed_size; - } -} - -template inline AutoBuffer<_Tp, fixed_size>::operator _Tp* () -{ return ptr; } - -template inline AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const -{ return ptr; } - - -/////////////////////////////////// Ptr //////////////////////////////////////// - -template inline Ptr<_Tp>::Ptr() : obj(0), refcount(0) {} -template inline Ptr<_Tp>::Ptr(_Tp* _obj) : obj(_obj) -{ - if(obj) - { - refcount = (int*)fastMalloc(sizeof(*refcount)); - *refcount = 1; - } - else - refcount = 0; -} - -template inline void Ptr<_Tp>::addref() -{ if( refcount ) CV_XADD(refcount, 1); } - -template inline void Ptr<_Tp>::release() -{ - if( refcount && CV_XADD(refcount, -1) == 1 ) - { - delete_obj(); - fastFree(refcount); - } - refcount = 0; - obj = 0; -} - -template inline void Ptr<_Tp>::delete_obj() -{ - if( obj ) delete obj; -} - -template inline Ptr<_Tp>::~Ptr() { release(); } - -template inline Ptr<_Tp>::Ptr(const Ptr<_Tp>& _ptr) -{ - obj = _ptr.obj; - refcount = _ptr.refcount; - addref(); -} - -template inline Ptr<_Tp>& Ptr<_Tp>::operator = (const Ptr<_Tp>& _ptr) -{ - if (this != &_ptr) - { - int* _refcount = _ptr.refcount; - if( _refcount ) - CV_XADD(_refcount, 1); - release(); - obj = _ptr.obj; - refcount = _refcount; - } - return *this; -} - -template inline _Tp* Ptr<_Tp>::operator -> () { return obj; } -template inline const _Tp* Ptr<_Tp>::operator -> () const { return obj; } - -template inline Ptr<_Tp>::operator _Tp* () { return obj; } -template inline Ptr<_Tp>::operator const _Tp*() const { return obj; } - -template inline bool Ptr<_Tp>::empty() const { return obj == 0; } - -template template Ptr<_Tp>::Ptr(const Ptr<_Tp2>& p) - : obj(0), refcount(0) -{ - if (p.empty()) - return; - - _Tp* p_casted = dynamic_cast<_Tp*>(p.obj); - if (!p_casted) - return; - - obj = p_casted; - refcount = p.refcount; - addref(); -} - -template template inline Ptr<_Tp2> Ptr<_Tp>::ptr() -{ - Ptr<_Tp2> p; - if( !obj ) - return p; - - _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); - if (!obj_casted) - return p; - - if( refcount ) - CV_XADD(refcount, 1); - - p.obj = obj_casted; - p.refcount = refcount; - return p; -} - -template template inline const Ptr<_Tp2> Ptr<_Tp>::ptr() const -{ - Ptr<_Tp2> p; - if( !obj ) - return p; - - _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); - if (!obj_casted) - return p; - - if( refcount ) - CV_XADD(refcount, 1); - - p.obj = obj_casted; - p.refcount = refcount; - return p; -} - -//// specializied implementations of Ptr::delete_obj() for classic OpenCV types - -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); - -//////////////////////////////////////// XML & YAML I/O //////////////////////////////////// - -CV_EXPORTS_W void write( FileStorage& fs, const string& name, int value ); -CV_EXPORTS_W void write( FileStorage& fs, const string& name, float value ); -CV_EXPORTS_W void write( FileStorage& fs, const string& name, double value ); -CV_EXPORTS_W void write( FileStorage& fs, const string& name, const string& value ); - -template inline void write(FileStorage& fs, const _Tp& value) -{ write(fs, string(), value); } - -CV_EXPORTS void writeScalar( FileStorage& fs, int value ); -CV_EXPORTS void writeScalar( FileStorage& fs, float value ); -CV_EXPORTS void writeScalar( FileStorage& fs, double value ); -CV_EXPORTS void writeScalar( FileStorage& fs, const string& value ); - -template<> inline void write( FileStorage& fs, const int& value ) -{ - writeScalar(fs, value); -} - -template<> inline void write( FileStorage& fs, const float& value ) -{ - writeScalar(fs, value); -} - -template<> inline void write( FileStorage& fs, const double& value ) -{ - writeScalar(fs, value); -} - -template<> inline void write( FileStorage& fs, const string& value ) -{ - writeScalar(fs, value); -} - -template inline void write(FileStorage& fs, const Point_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); -} - -template inline void write(FileStorage& fs, const Point3_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); - write(fs, pt.z); -} - -template inline void write(FileStorage& fs, const Size_<_Tp>& sz ) -{ - write(fs, sz.width); - write(fs, sz.height); -} - -template inline void write(FileStorage& fs, const Complex<_Tp>& c ) -{ - write(fs, c.re); - write(fs, c.im); -} - -template inline void write(FileStorage& fs, const Rect_<_Tp>& r ) -{ - write(fs, r.x); - write(fs, r.y); - write(fs, r.width); - write(fs, r.height); -} - -template inline void write(FileStorage& fs, const Vec<_Tp, cn>& v ) -{ - for(int i = 0; i < cn; i++) - write(fs, v.val[i]); -} - -template inline void write(FileStorage& fs, const Scalar_<_Tp>& s ) -{ - write(fs, s.val[0]); - write(fs, s.val[1]); - write(fs, s.val[2]); - write(fs, s.val[3]); -} - -inline void write(FileStorage& fs, const Range& r ) -{ - write(fs, r.start); - write(fs, r.end); -} - -class CV_EXPORTS WriteStructContext -{ -public: - WriteStructContext(FileStorage& _fs, const string& name, - int flags, const string& typeName=string()); - ~WriteStructContext(); - FileStorage* fs; -}; - -template inline void write(FileStorage& fs, const string& name, const Point_<_Tp>& pt ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, pt.x); - write(fs, pt.y); -} - -template inline void write(FileStorage& fs, const string& name, const Point3_<_Tp>& pt ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, pt.x); - write(fs, pt.y); - write(fs, pt.z); -} - -template inline void write(FileStorage& fs, const string& name, const Size_<_Tp>& sz ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, sz.width); - write(fs, sz.height); -} - -template inline void write(FileStorage& fs, const string& name, const Complex<_Tp>& c ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, c.re); - write(fs, c.im); -} - -template inline void write(FileStorage& fs, const string& name, const Rect_<_Tp>& r ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, r.x); - write(fs, r.y); - write(fs, r.width); - write(fs, r.height); -} - -template inline void write(FileStorage& fs, const string& name, const Vec<_Tp, cn>& v ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - for(int i = 0; i < cn; i++) - write(fs, v.val[i]); -} - -template inline void write(FileStorage& fs, const string& name, const Scalar_<_Tp>& s ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, s.val[0]); - write(fs, s.val[1]); - write(fs, s.val[2]); - write(fs, s.val[3]); -} - -inline void write(FileStorage& fs, const string& name, const Range& r ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+CV_NODE_FLOW); - write(fs, r.start); - write(fs, r.end); -} - -template class VecWriterProxy -{ -public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const vector<_Tp>& vec) const - { - size_t i, count = vec.size(); - for( i = 0; i < count; i++ ) - write( *fs, vec[i] ); - } - FileStorage* fs; -}; - -template class VecWriterProxy<_Tp,1> -{ -public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const vector<_Tp>& vec) const - { - int _fmt = DataType<_Tp>::fmt; - char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' }; - fs->writeRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, vec.size()*sizeof(_Tp) ); - } - FileStorage* fs; -}; - -template static inline void write( FileStorage& fs, const vector<_Tp>& vec ) -{ - VecWriterProxy<_Tp, DataType<_Tp>::fmt != 0> w(&fs); - w(vec); -} - -template static inline void write( FileStorage& fs, const string& name, - const vector<_Tp>& vec ) -{ - WriteStructContext ws(fs, name, CV_NODE_SEQ+(DataType<_Tp>::fmt != 0 ? CV_NODE_FLOW : 0)); - write(fs, vec); -} - -CV_EXPORTS_W void write( FileStorage& fs, const string& name, const Mat& value ); -CV_EXPORTS void write( FileStorage& fs, const string& name, const SparseMat& value ); - -template static inline FileStorage& operator << (FileStorage& fs, const _Tp& value) -{ - if( !fs.isOpened() ) - return fs; - if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) - CV_Error( CV_StsError, "No element name has been given" ); - write( fs, fs.elname, value ); - if( fs.state & FileStorage::INSIDE_MAP ) - fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; - return fs; -} - -CV_EXPORTS FileStorage& operator << (FileStorage& fs, const string& str); - -static inline FileStorage& operator << (FileStorage& fs, const char* str) -{ return (fs << string(str)); } - -static inline FileStorage& operator << (FileStorage& fs, char* value) -{ return (fs << string(value)); } - -inline FileNode::FileNode() : fs(0), node(0) {} -inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) - : fs(_fs), node(_node) {} - -inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {} - -inline int FileNode::type() const { return !node ? NONE : (node->tag & TYPE_MASK); } -inline bool FileNode::empty() const { return node == 0; } -inline bool FileNode::isNone() const { return type() == NONE; } -inline bool FileNode::isSeq() const { return type() == SEQ; } -inline bool FileNode::isMap() const { return type() == MAP; } -inline bool FileNode::isInt() const { return type() == INT; } -inline bool FileNode::isReal() const { return type() == REAL; } -inline bool FileNode::isString() const { return type() == STR; } -inline bool FileNode::isNamed() const { return !node ? false : (node->tag & NAMED) != 0; } -inline size_t FileNode::size() const -{ - int t = type(); - return t == MAP ? (size_t)((CvSet*)node->data.map)->active_count : - t == SEQ ? (size_t)node->data.seq->total : (size_t)!isNone(); -} - -inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; } -inline const CvFileNode* FileNode::operator* () const { return node; } - -static inline void read(const FileNode& node, int& value, int default_value) -{ - value = !node.node ? default_value : - CV_NODE_IS_INT(node.node->tag) ? node.node->data.i : - CV_NODE_IS_REAL(node.node->tag) ? cvRound(node.node->data.f) : 0x7fffffff; -} - -static inline void read(const FileNode& node, bool& value, bool default_value) -{ - int temp; read(node, temp, (int)default_value); - value = temp != 0; -} - -static inline void read(const FileNode& node, uchar& value, uchar default_value) -{ - int temp; read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline void read(const FileNode& node, schar& value, schar default_value) -{ - int temp; read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline void read(const FileNode& node, ushort& value, ushort default_value) -{ - int temp; read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline void read(const FileNode& node, short& value, short default_value) -{ - int temp; read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline void read(const FileNode& node, float& value, float default_value) -{ - value = !node.node ? default_value : - CV_NODE_IS_INT(node.node->tag) ? (float)node.node->data.i : - CV_NODE_IS_REAL(node.node->tag) ? (float)node.node->data.f : 1e30f; -} - -static inline void read(const FileNode& node, double& value, double default_value) -{ - value = !node.node ? default_value : - CV_NODE_IS_INT(node.node->tag) ? (double)node.node->data.i : - CV_NODE_IS_REAL(node.node->tag) ? node.node->data.f : 1e300; -} - -static inline void read(const FileNode& node, string& value, const string& default_value) -{ - value = !node.node ? default_value : CV_NODE_IS_STRING(node.node->tag) ? string(node.node->data.str.ptr) : string(""); -} +/** @brief Returns a text string formatted using the printf-like expression. -template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) -{ - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) -{ - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2])); -} - -template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) -{ - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} +The function acts like sprintf but forms and returns an STL string. It can be used to form an error +message in the Exception constructor. +@param fmt printf-compatible formatting specifiers. + */ +CV_EXPORTS String format( const char* fmt, ... ); -template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) -{ - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} +///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// -template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) +static inline +Ptr format(InputArray mtx, int fmt) { - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); + return Formatter::get(fmt)->format(mtx.getMat()); } -template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) +static inline +int print(Ptr fmtd, FILE* stream = stdout) { - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); -} + int written = 0; + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + written += fputs(str, stream); -template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) -{ - vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); + return written; } -static inline void read(const FileNode& node, Range& value, const Range& default_value) +static inline +int print(const Mat& mtx, FILE* stream = stdout) { - Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); - read(node, temp, default_temp); - value.start = temp.x; value.end = temp.y; + return print(Formatter::get()->format(mtx), stream); } -CV_EXPORTS_W void read(const FileNode& node, Mat& mat, const Mat& default_mat=Mat() ); -CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat=SparseMat() ); - -inline FileNode::operator int() const +static inline +int print(const UMat& mtx, FILE* stream = stdout) { - int value; - read(*this, value, 0); - return value; + return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); } -inline FileNode::operator float() const -{ - float value; - read(*this, value, 0.f); - return value; -} -inline FileNode::operator double() const -{ - double value; - read(*this, value, 0.); - return value; -} -inline FileNode::operator string() const -{ - string value; - read(*this, value, value); - return value; -} - -inline void FileNode::readRaw( const string& fmt, uchar* vec, size_t len ) const -{ - begin().readRaw( fmt, vec, len ); -} - -template class VecReaderProxy -{ -public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(vector<_Tp>& vec, size_t count) const - { - count = std::min(count, it->remaining); - vec.resize(count); - for( size_t i = 0; i < count; i++, ++(*it) ) - read(**it, vec[i], _Tp()); - } - FileNodeIterator* it; -}; - -template class VecReaderProxy<_Tp,1> -{ -public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(vector<_Tp>& vec, size_t count) const - { - size_t remaining = it->remaining, cn = DataType<_Tp>::channels; - int _fmt = DataType<_Tp>::fmt; - char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' }; - size_t remaining1 = remaining/cn; - count = count < remaining1 ? count : remaining1; - vec.resize(count); - it->readRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp) ); - } - FileNodeIterator* it; -}; - -template static inline void -read( FileNodeIterator& it, vector<_Tp>& vec, size_t maxCount=(size_t)INT_MAX ) -{ - VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it); - r(vec, maxCount); -} - -template static inline void -read( const FileNode& node, vector<_Tp>& vec, const vector<_Tp>& default_value=vector<_Tp>() ) -{ - if(!node.node) - vec = default_value; - else - { - FileNodeIterator it = node.begin(); - read( it, vec ); - } -} - -inline FileNodeIterator FileNode::begin() const -{ - return FileNodeIterator(fs, node); -} - -inline FileNodeIterator FileNode::end() const -{ - return FileNodeIterator(fs, node, size()); -} - -inline FileNode FileNodeIterator::operator *() const -{ return FileNode(fs, (const CvFileNode*)(void*)reader.ptr); } - -inline FileNode FileNodeIterator::operator ->() const -{ return FileNode(fs, (const CvFileNode*)(void*)reader.ptr); } - -template static inline FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) -{ read( *it, value, _Tp()); return ++it; } template static inline -FileNodeIterator& operator >> (FileNodeIterator& it, vector<_Tp>& vec) +int print(const std::vector >& vec, FILE* stream = stdout) { - VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it); - r(vec, (size_t)INT_MAX); - return it; + return print(Formatter::get()->format(Mat(vec)), stream); } -template static inline void operator >> (const FileNode& n, _Tp& value) -{ read( n, value, _Tp()); } - -template static inline void operator >> (const FileNode& n, vector<_Tp>& vec) -{ FileNodeIterator it = n.begin(); it >> vec; } - -static inline bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2) +template static inline +int print(const std::vector >& vec, FILE* stream = stdout) { - return it1.fs == it2.fs && it1.container == it2.container && - it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining; + return print(Formatter::get()->format(Mat(vec)), stream); } -static inline bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2) +template static inline +int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) { - return !(it1 == it2); + return print(Formatter::get()->format(cv::Mat(matx)), stream); } -static inline ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it2.remaining - it1.remaining; -} - -static inline bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it1.remaining > it2.remaining; -} - -inline FileNode FileStorage::getFirstTopLevelNode() const -{ - FileNode r = root(); - FileNodeIterator it = r.begin(); - return it != r.end() ? *it : FileNode(); -} - -//////////////////////////////////////// Various algorithms //////////////////////////////////// - -template static inline _Tp gcd(_Tp a, _Tp b) -{ - if( a < b ) - std::swap(a, b); - while( b > 0 ) - { - _Tp r = a % b; - a = b; - b = r; - } - return a; -} +//! @endcond /****************************************************************************************\ - - Generic implementation of QuickSort algorithm - Use it as: vector<_Tp> a; ... sort(a,); - - The current implementation was derived from *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. - +* Auxiliary algorithms * \****************************************************************************************/ -template void sort( vector<_Tp>& vec, _LT LT=_LT() ) -{ - int isort_thresh = 7; - int sp = 0; +/** @brief Splits an element set into equivalency classes. - struct - { - _Tp *lb; - _Tp *ub; - } stack[48]; - - size_t total = vec.size(); - - if( total <= 1 ) - return; - - _Tp* arr = &vec[0]; - stack[0].lb = arr; - stack[0].ub = arr + (total - 1); - - while( sp >= 0 ) - { - _Tp* left = stack[sp].lb; - _Tp* right = stack[sp--].ub; - - for(;;) - { - int i, n = (int)(right - left) + 1, m; - _Tp* ptr; - _Tp* ptr2; - - if( n <= isort_thresh ) - { - insert_sort: - for( ptr = left + 1; ptr <= right; ptr++ ) - { - for( ptr2 = ptr; ptr2 > left && LT(ptr2[0],ptr2[-1]); ptr2--) - std::swap( ptr2[0], ptr2[-1] ); - } - break; - } - else - { - _Tp* left0; - _Tp* left1; - _Tp* right0; - _Tp* right1; - _Tp* pivot; - _Tp* a; - _Tp* b; - _Tp* c; - int swap_cnt = 0; - - left0 = left; - right0 = right; - pivot = left + (n/2); - - if( n > 40 ) - { - int d = n / 8; - a = left, b = left + d, c = left + 2*d; - left = LT(*a, *b) ? (LT(*b, *c) ? b : (LT(*a, *c) ? c : a)) - : (LT(*c, *b) ? b : (LT(*a, *c) ? a : c)); - - a = pivot - d, b = pivot, c = pivot + d; - pivot = LT(*a, *b) ? (LT(*b, *c) ? b : (LT(*a, *c) ? c : a)) - : (LT(*c, *b) ? b : (LT(*a, *c) ? a : c)); - - a = right - 2*d, b = right - d, c = right; - right = LT(*a, *b) ? (LT(*b, *c) ? b : (LT(*a, *c) ? c : a)) - : (LT(*c, *b) ? b : (LT(*a, *c) ? a : c)); - } - - a = left, b = pivot, c = right; - pivot = LT(*a, *b) ? (LT(*b, *c) ? b : (LT(*a, *c) ? c : a)) - : (LT(*c, *b) ? b : (LT(*a, *c) ? a : c)); - if( pivot != left0 ) - { - std::swap( *pivot, *left0 ); - pivot = left0; - } - left = left1 = left0 + 1; - right = right1 = right0; - - for(;;) - { - while( left <= right && !LT(*pivot, *left) ) - { - if( !LT(*left, *pivot) ) - { - if( left > left1 ) - std::swap( *left1, *left ); - swap_cnt = 1; - left1++; - } - left++; - } - - while( left <= right && !LT(*right, *pivot) ) - { - if( !LT(*pivot, *right) ) - { - if( right < right1 ) - std::swap( *right1, *right ); - swap_cnt = 1; - right1--; - } - right--; - } - - if( left > right ) - break; - std::swap( *left, *right ); - swap_cnt = 1; - left++; - right--; - } - - if( swap_cnt == 0 ) - { - left = left0, right = right0; - goto insert_sort; - } - - n = std::min( (int)(left1 - left0), (int)(left - left1) ); - for( i = 0; i < n; i++ ) - std::swap( left0[i], left[i-n] ); - - n = std::min( (int)(right0 - right1), (int)(right1 - right) ); - for( i = 0; i < n; i++ ) - std::swap( left[i], right0[i-n+1] ); - n = (int)(left - left1); - m = (int)(right1 - right); - if( n > 1 ) - { - if( m > 1 ) - { - if( n > m ) - { - stack[++sp].lb = left0; - stack[sp].ub = left0 + n - 1; - left = right0 - m + 1, right = right0; - } - else - { - stack[++sp].lb = right0 - m + 1; - stack[sp].ub = right0; - left = left0, right = left0 + n - 1; - } - } - else - left = left0, right = left0 + n - 1; - } - else if( m > 1 ) - left = right0 - m + 1, right = right0; - else - break; - } - } - } -} - -template class LessThan -{ -public: - bool operator()(const _Tp& a, const _Tp& b) const { return a < b; } -}; - -template class GreaterEq -{ -public: - bool operator()(const _Tp& a, const _Tp& b) const { return a >= b; } -}; - -template class LessThanIdx -{ -public: - LessThanIdx( const _Tp* _arr ) : arr(_arr) {} - bool operator()(int a, int b) const { return arr[a] < arr[b]; } - const _Tp* arr; -}; - -template class GreaterEqIdx -{ -public: - GreaterEqIdx( const _Tp* _arr ) : arr(_arr) {} - bool operator()(int a, int b) const { return arr[a] >= arr[b]; } - const _Tp* arr; -}; - - -// This function splits the input sequence or set into one or more equivalence classes and -// returns the vector of labels - 0-based class indexes for each element. -// predicate(a,b) returns true if the two sequence elements certainly belong to the same class. -// -// The algorithm is described in "Introduction to Algorithms" -// by Cormen, Leiserson and Rivest, the chapter "Data structures for disjoint sets" +The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements +into one or more equivalency classes, as described in + . The function returns the number of +equivalency classes. +@param _vec Set of elements stored as a vector. +@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is +a 0-based cluster index of `vec[i]`. +@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an +instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The +predicate returns true when the elements are certainly in the same class, and returns false if they +may or may not be in the same class. +@ingroup core_cluster +*/ template int -partition( const vector<_Tp>& _vec, vector& labels, - _EqPredicate predicate=_EqPredicate()) +partition( const std::vector<_Tp>& _vec, std::vector& labels, + _EqPredicate predicate=_EqPredicate()) { int i, j, N = (int)_vec.size(); const _Tp* vec = &_vec[0]; @@ -3464,7 +488,7 @@ partition( const vector<_Tp>& _vec, vector& labels, const int PARENT=0; const int RANK=1; - vector _nodes(N*2); + std::vector _nodes(N*2); int (*nodes)[2] = (int(*)[2])&_nodes[0]; // The first O(N) pass: create N single-vertex trees @@ -3504,7 +528,7 @@ partition( const vector<_Tp>& _vec, vector& labels, nodes[root2][RANK] += rank == rank2; root = root2; } - assert( nodes[root][PARENT] < 0 ); + CV_Assert( nodes[root][PARENT] < 0 ); int k = j, parent; @@ -3544,506 +568,6 @@ partition( const vector<_Tp>& _vec, vector& labels, return nclasses; } +} // cv -////////////////////////////////////////////////////////////////////////////// - -// 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, r); } - -template inline void Seq<_Tp>::copyTo(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], range); -} - -template inline Seq<_Tp>::operator vector<_Tp>() const -{ - 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( std::abs(static_cast(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); -} - - -template struct RTTIImpl -{ -public: - static int isInstance(const void* ptr) - { - static _ClsName dummy; - static void* dummyp = &dummy; - union - { - const void* p; - const void** pp; - } a, b; - a.p = dummyp; - b.p = ptr; - return *a.pp == *b.pp; - } - static void release(void** dbptr) - { - if(dbptr && *dbptr) - { - delete (_ClsName*)*dbptr; - *dbptr = 0; - } - } - static void* read(CvFileStorage* fs, CvFileNode* n) - { - FileNode fn(fs, n); - _ClsName* obj = new _ClsName; - if(obj->read(fn)) - return obj; - delete obj; - return 0; - } - - static void write(CvFileStorage* _fs, const char* name, const void* ptr, CvAttrList) - { - if(ptr && _fs) - { - FileStorage fs(_fs); - fs.fs.addref(); - ((const _ClsName*)ptr)->write(fs, string(name)); - } - } - - static void* clone(const void* ptr) - { - if(!ptr) - return 0; - return new _ClsName(*(const _ClsName*)ptr); - } -}; - - -class CV_EXPORTS Formatter -{ -public: - virtual ~Formatter() {} - virtual void write(std::ostream& out, const Mat& m, const int* params=0, int nparams=0) const = 0; - virtual void write(std::ostream& out, const void* data, int nelems, int type, - const int* params=0, int nparams=0) const = 0; - static const Formatter* get(const char* fmt=""); - static const Formatter* setDefault(const Formatter* fmt); -}; - - -struct CV_EXPORTS Formatted -{ - Formatted(const Mat& m, const Formatter* fmt, - const vector& params); - Formatted(const Mat& m, const Formatter* fmt, - const int* params=0); - Mat mtx; - const Formatter* fmt; - vector params; -}; - -static inline Formatted format(const Mat& mtx, const char* fmt, - const vector& params=vector()) -{ - return Formatted(mtx, Formatter::get(fmt), params); -} - -template static inline Formatted format(const vector >& vec, - const char* fmt, const vector& params=vector()) -{ - return Formatted(Mat(vec), Formatter::get(fmt), params); -} - -template static inline Formatted format(const vector >& vec, - const char* fmt, const vector& params=vector()) -{ - return Formatted(Mat(vec), Formatter::get(fmt), params); -} - -/** \brief prints Mat to the output stream in Matlab notation - * use like - @verbatim - Mat my_mat = Mat::eye(3,3,CV_32F); - std::cout << my_mat; - @endverbatim - */ -static inline std::ostream& operator << (std::ostream& out, const Mat& mtx) -{ - Formatter::get()->write(out, mtx); - return out; -} - -/** \brief prints Mat to the output stream allows in the specified notation (see format) - * use like - @verbatim - Mat my_mat = Mat::eye(3,3,CV_32F); - std::cout << my_mat; - @endverbatim - */ -static inline std::ostream& operator << (std::ostream& out, const Formatted& fmtd) -{ - fmtd.fmt->write(out, fmtd.mtx); - return out; -} - - -template static inline std::ostream& operator << (std::ostream& out, - const vector >& vec) -{ - Formatter::get()->write(out, Mat(vec)); - return out; -} - - -template static inline std::ostream& operator << (std::ostream& out, - const vector >& vec) -{ - Formatter::get()->write(out, Mat(vec)); - return out; -} - - -/** Writes a Matx to an output stream. - */ -template inline std::ostream& operator<<(std::ostream& out, const Matx<_Tp, m, n>& matx) -{ - out << cv::Mat(matx); - return out; -} - -/** Writes a point to an output stream in Matlab notation - */ -template inline std::ostream& operator<<(std::ostream& out, const Point_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << "]"; - return out; -} - -/** Writes a point to an output stream in Matlab notation - */ -template inline std::ostream& operator<<(std::ostream& out, const Point3_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; - return out; -} - -/** Writes a Vec to an output stream. Format example : [10, 20, 30] - */ -template inline std::ostream& operator<<(std::ostream& out, const Vec<_Tp, n>& vec) -{ - out << "["; - - if(Vec<_Tp, n>::depth < CV_32F) - { - for (int i = 0; i < n - 1; ++i) { - out << (int)vec[i] << ", "; - } - out << (int)vec[n-1] << "]"; - } - else - { - for (int i = 0; i < n - 1; ++i) { - out << vec[i] << ", "; - } - out << vec[n-1] << "]"; - } - - return out; -} - -/** Writes a Size_ to an output stream. Format example : [640 x 480] - */ -template inline std::ostream& operator<<(std::ostream& out, const Size_<_Tp>& size) -{ - out << "[" << size.width << " x " << size.height << "]"; - return out; -} - -/** Writes a Rect_ to an output stream. Format example : [640 x 480 from (10, 20)] - */ -template inline std::ostream& operator<<(std::ostream& out, const Rect_<_Tp>& rect) -{ - out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; - return out; -} - - -template inline Ptr<_Tp> Algorithm::create(const string& name) -{ - return _create(name).ptr<_Tp>(); -} - -template -inline void Algorithm::set(const char* _name, const Ptr<_Tp>& value) -{ - Ptr algo_ptr = value. template ptr(); - if (algo_ptr.empty()) { - CV_Error( CV_StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); - } - info()->set(this, _name, ParamType::type, &algo_ptr); -} - -template -inline void Algorithm::set(const string& _name, const Ptr<_Tp>& value) -{ - this->set<_Tp>(_name.c_str(), value); -} - -template -inline void Algorithm::setAlgorithm(const char* _name, const Ptr<_Tp>& value) -{ - Ptr algo_ptr = value. template ptr(); - if (algo_ptr.empty()) { - CV_Error( CV_StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); - } - info()->set(this, _name, ParamType::type, &algo_ptr); -} - -template -inline void Algorithm::setAlgorithm(const string& _name, const Ptr<_Tp>& value) -{ - this->set<_Tp>(_name.c_str(), value); -} - -template inline typename ParamType<_Tp>::member_type Algorithm::get(const string& _name) const -{ - typename ParamType<_Tp>::member_type value; - info()->get(this, _name.c_str(), ParamType<_Tp>::type, &value); - return value; -} - -template inline typename ParamType<_Tp>::member_type Algorithm::get(const char* _name) const -{ - typename ParamType<_Tp>::member_type value; - info()->get(this, _name, ParamType<_Tp>::type, &value); - return value; -} - -template inline void AlgorithmInfo::addParam(Algorithm& algo, const char* parameter, - Ptr<_Tp>& value, bool readOnly, Ptr<_Tp> (Algorithm::*getter)(), void (Algorithm::*setter)(const Ptr<_Tp>&), - const string& help) -{ - //TODO: static assert: _Tp inherits from _Base - addParam_(algo, parameter, ParamType<_Base>::type, &value, readOnly, - (Algorithm::Getter)getter, (Algorithm::Setter)setter, help); -} - -template inline void AlgorithmInfo::addParam(Algorithm& algo, const char* parameter, - Ptr<_Tp>& value, bool readOnly, Ptr<_Tp> (Algorithm::*getter)(), void (Algorithm::*setter)(const Ptr<_Tp>&), - const string& help) -{ - //TODO: static assert: _Tp inherits from Algorithm - addParam_(algo, parameter, ParamType::type, &value, readOnly, - (Algorithm::Getter)getter, (Algorithm::Setter)setter, help); -} - -} - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -#endif // __cplusplus #endif diff --git a/HuaGoCorrect/pub/opencv/include/opencv2/core/types_c.h b/HuaGoCorrect/pub/opencv/include/opencv2/core/types_c.h index 989b799..5f63eb8 100644 --- a/HuaGoCorrect/pub/opencv/include/opencv2/core/types_c.h +++ b/HuaGoCorrect/pub/opencv/include/opencv2/core/types_c.h @@ -12,6 +12,7 @@ // // 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, @@ -40,63 +41,35 @@ // //M*/ -#ifndef __OPENCV_CORE_TYPES_H__ -#define __OPENCV_CORE_TYPES_H__ +#ifndef OPENCV_CORE_TYPES_H +#define OPENCV_CORE_TYPES_H -#if !defined _CRT_SECURE_NO_DEPRECATE && defined _MSC_VER -# if _MSC_VER > 1300 -# define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio 2005 warnings */ -# endif +#if !defined(__OPENCV_BUILD) && !defined(CV__DISABLE_C_API_CTORS) +#define CV__ENABLE_C_API_CTORS // enable C API ctors (must be removed) #endif +//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only -#ifndef SKIP_INCLUDES +#ifdef __cplusplus -#include -#include -#include -#include - -#if !defined _MSC_VER && !defined __BORLANDC__ -# include -#endif - -#if defined __ICL -# define CV_ICC __ICL -#elif defined __ICC -# define CV_ICC __ICC -#elif defined __ECL -# define CV_ICC __ECL -#elif defined __ECC -# define CV_ICC __ECC -#elif defined __INTEL_COMPILER -# define CV_ICC __INTEL_COMPILER -#endif - -#if defined CV_ICC && !defined CV_ENABLE_UNROLLED -# define CV_ENABLE_UNROLLED 0 +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#define CV_STRUCT_INITIALIZER {0,} #else -# define CV_ENABLE_UNROLLED 1 +#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 -#if (defined _M_X64 && defined _MSC_VER && _MSC_VER >= 1400) || (__GNUC__ >= 4 && defined __x86_64__) -# if defined WIN32 -# include -# endif -# if defined __SSE2__ || !defined __GNUC__ -# include -# endif -#endif - -#if defined __BORLANDC__ -# include #else -# include +#define CV_STRUCT_INITIALIZER {0} #endif + #ifdef HAVE_IPL # ifndef __IPL_H__ -# if defined WIN32 || defined _WIN32 +# if defined _WIN32 # include # else # include @@ -106,9 +79,16 @@ # define HAVE_IPL #endif +#include "opencv2/core/cvdef.h" + +#ifndef SKIP_INCLUDES +#include +#include +#include +#include #endif // SKIP_INCLUDES -#if defined WIN32 || defined _WIN32 +#if defined _WIN32 # define CV_CDECL __cdecl # define CV_STDCALL __stdcall #else @@ -116,12 +96,10 @@ # define CV_STDCALL #endif -#ifndef CV_EXTERN_C +#ifndef CV_DEFAULT # ifdef __cplusplus -# define CV_EXTERN_C extern "C" # define CV_DEFAULT(val) = val # else -# define CV_EXTERN_C # define CV_DEFAULT(val) # endif #endif @@ -134,169 +112,103 @@ # endif #endif -#ifndef CV_INLINE -# if defined __cplusplus -# define CV_INLINE inline -# elif defined _MSC_VER -# define CV_INLINE __inline -# else -# define CV_INLINE static -# endif -#endif /* CV_INLINE */ - -#if (defined WIN32 || defined _WIN32 || defined WINCE) && defined CVAPI_EXPORTS -# define CV_EXPORTS __declspec(dllexport) -#else -# define CV_EXPORTS -#endif - #ifndef CVAPI # define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL #endif -#if defined _MSC_VER || defined __BORLANDC__ - typedef __int64 int64; - typedef unsigned __int64 uint64; -# define CV_BIG_INT(n) n##I64 -# define CV_BIG_UINT(n) n##UI64 -#else - typedef int64_t int64; - typedef uint64_t uint64; -# define CV_BIG_INT(n) n##LL -# define CV_BIG_UINT(n) n##ULL +#ifndef CV_IMPL +# define CV_IMPL CV_EXTERN_C #endif -#ifndef HAVE_IPL - typedef unsigned char uchar; - typedef unsigned short ushort; +#ifdef __cplusplus +# include "opencv2/core.hpp" #endif -typedef signed char schar; +/** @addtogroup core_c + @{ +*/ -/* special informative macros for wrapper generators */ -#define CV_CARRAY(counter) -#define CV_CUSTOM_CARRAY(args) -#define CV_EXPORTS_W CV_EXPORTS -#define CV_EXPORTS_W_SIMPLE CV_EXPORTS -#define CV_EXPORTS_AS(synonym) CV_EXPORTS -#define CV_EXPORTS_W_MAP CV_EXPORTS -#define CV_IN_OUT -#define CV_OUT -#define CV_PROP -#define CV_PROP_RW -#define CV_WRAP -#define CV_WRAP_AS(synonym) -#define CV_WRAP_DEFAULT(value) +/** @brief This is the "metatype" used *only* as a function parameter. -/* CvArr* is used to pass arbitrary - * array-like data structures - * into functions where the particular - * array type is recognized at runtime: +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 union Cv32suf -{ - int i; - unsigned u; - float f; -} -Cv32suf; - -typedef union Cv64suf -{ - int64 i; - uint64 u; - double f; -} -Cv64suf; - typedef int CVStatus; +/** @see cv::Error::Code */ enum { - CV_StsOk= 0, /* everithing 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, /**/ - CV_BadModelOrChSeq= -14, /**/ - CV_BadNumChannels= -15, /**/ - CV_BadNumChannel1U= -16, /**/ - CV_BadDepth= -17, /**/ - CV_BadAlphaChannel= -18, /**/ - CV_BadOrder= -19, /**/ - CV_BadOrigin= -20, /**/ - CV_BadAlign= -21, /**/ - CV_BadCallBack= -22, /**/ - CV_BadTileSize= -23, /**/ - CV_BadCOI= -24, /**/ - CV_BadROISize= -25, /**/ - CV_MaskIsTiled= -26, /**/ - CV_StsNullPtr= -27, /* null pointer */ - CV_StsVecLengthErr= -28, /* incorrect vector length */ - CV_StsFilterStructContentErr= -29, /* incorr. filter structure content */ - CV_StsKernelStructContentErr= -30, /* incorr. 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, - CV_GpuApiCallError= -217, - CV_OpenGlNotSupported= -218, - CV_OpenGlApiCallError= -219, - CV_OpenCLDoubleNotSupported= -220, - CV_OpenCLInitError= -221, - CV_OpenCLNoAMDBlasFft= -222 + 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 * \****************************************************************************************/ -#ifdef HAVE_TEGRA_OPTIMIZATION -# include "tegra_round.hpp" -#endif - -#define CV_PI 3.1415926535897932384626433832795 -#define CV_LOG2 0.69314718055994530941723212145818 - #define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) -#ifndef MIN -# define MIN(a,b) ((a) > (b) ? (b) : (a)) -#endif - -#ifndef MAX -# define MAX(a,b) ((a) < (b) ? (b) : (a)) -#endif - -/* min & max without jumps */ +/** min & max without jumps */ #define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) #define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) -/* absolute value without jumps */ +/** absolute value without jumps */ #ifndef __cplusplus # define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) #else @@ -305,94 +217,9 @@ enum { #define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) #define CV_SIGN(a) CV_CMP((a),0) -CV_INLINE int cvRound( double value ) -{ -#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && defined __SSE2__ && !defined __APPLE__) - __m128d t = _mm_set_sd( value ); - return _mm_cvtsd_si32(t); -#elif defined _MSC_VER && defined _M_IX86 - int t; - __asm - { - fld value; - fistp t; - } - return t; -#elif defined _MSC_VER && defined _M_ARM && defined HAVE_TEGRA_OPTIMIZATION - TEGRA_ROUND(value); -#elif defined CV_ICC || defined __GNUC__ -# ifdef HAVE_TEGRA_OPTIMIZATION - TEGRA_ROUND(value); -# else - return (int)lrint(value); -# endif -#else - double intpart, fractpart; - fractpart = modf(value, &intpart); - if ((fabs(fractpart) != 0.5) || ((((int)intpart) % 2) != 0)) - return (int)(value + (value >= 0 ? 0.5 : -0.5)); - else - return (int)intpart; -#endif -} - -#if defined __SSE2__ || (defined _M_IX86_FP && 2 == _M_IX86_FP) -# include "emmintrin.h" -#endif - -CV_INLINE int cvFloor( double value ) -{ -#if defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__ && !defined __APPLE__) - __m128d t = _mm_set_sd( value ); - int i = _mm_cvtsd_si32(t); - return i - _mm_movemask_pd(_mm_cmplt_sd(t, _mm_cvtsi32_sd(t,i))); -#elif defined __GNUC__ - int i = (int)value; - return i - (i > value); -#else - int i = cvRound(value); - float diff = (float)(value - i); - return i - (diff < 0); -#endif -} - - -CV_INLINE int cvCeil( double value ) -{ -#if defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__) - __m128d t = _mm_set_sd( value ); - int i = _mm_cvtsd_si32(t); - return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i), t)); -#elif defined __GNUC__ - int i = (int)value; - return i + (i < value); -#else - int i = cvRound(value); - float diff = (float)(i - value); - return i + (diff < 0); -#endif -} - #define cvInvSqrt(value) ((float)(1./sqrt(value))) #define cvSqrt(value) ((float)sqrt(value)) -CV_INLINE int cvIsNaN( double value ) -{ - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + - ((unsigned)ieee754.u != 0) > 0x7ff00000; -} - - -CV_INLINE int cvIsInf( double value ) -{ - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && - (unsigned)ieee754.u == 0; -} - /*************** Random number generation *******************/ @@ -400,13 +227,27 @@ 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; } -/* Return random 32-bit unsigned integer: */ +/** @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; @@ -415,7 +256,12 @@ CV_INLINE unsigned cvRandInt( CvRNG* rng ) return (unsigned)temp; } -/* Returns random floating-point number between 0 and 1: */ +/** @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 */; @@ -462,46 +308,74 @@ CV_INLINE double cvRandReal( CvRNG* rng ) #define IPL_BORDER_REFLECT 2 #define IPL_BORDER_WRAP 3 -typedef struct _IplImage +#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, + 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. + 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, + int origin; /**< 0 - top-left origin, 1 - bottom-left origin (Windows bitmaps style). */ - int align; /* Alignment of image rows (4 or 8). + 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 + 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 + 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() {} + _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 coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ int xOffset; int yOffset; int width; @@ -536,7 +410,7 @@ IplConvKernelFP; #endif/*HAVE_IPL*/ -/* extra border mode */ +/** extra border mode */ #define IPL_BORDER_REFLECT_101 4 #define IPL_BORDER_TRANSPARENT 5 @@ -549,11 +423,11 @@ IplConvKernelFP; #define CV_IS_IMAGE(img) \ (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) -/* for storing double-precision +/** for storing double-precision floating point data in IplImage's */ #define IPL_DEPTH_64F 64 -/* get reference to pixel at (col,row), +/** 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)]) @@ -562,86 +436,29 @@ IplConvKernelFP; * Matrix type (CvMat) * \****************************************************************************************/ -#define CV_CN_MAX 512 -#define CV_CN_SHIFT 3 -#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) - -#define CV_8U 0 -#define CV_8S 1 -#define CV_16U 2 -#define CV_16S 3 -#define CV_32S 4 -#define CV_32F 5 -#define CV_64F 6 -#define CV_USRTYPE1 7 - -#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) -#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) - -#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) -#define CV_MAKE_TYPE CV_MAKETYPE - -#define CV_8UC1 CV_MAKETYPE(CV_8U,1) -#define CV_8UC2 CV_MAKETYPE(CV_8U,2) -#define CV_8UC3 CV_MAKETYPE(CV_8U,3) -#define CV_8UC4 CV_MAKETYPE(CV_8U,4) -#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) - -#define CV_8SC1 CV_MAKETYPE(CV_8S,1) -#define CV_8SC2 CV_MAKETYPE(CV_8S,2) -#define CV_8SC3 CV_MAKETYPE(CV_8S,3) -#define CV_8SC4 CV_MAKETYPE(CV_8S,4) -#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) - -#define CV_16UC1 CV_MAKETYPE(CV_16U,1) -#define CV_16UC2 CV_MAKETYPE(CV_16U,2) -#define CV_16UC3 CV_MAKETYPE(CV_16U,3) -#define CV_16UC4 CV_MAKETYPE(CV_16U,4) -#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) - -#define CV_16SC1 CV_MAKETYPE(CV_16S,1) -#define CV_16SC2 CV_MAKETYPE(CV_16S,2) -#define CV_16SC3 CV_MAKETYPE(CV_16S,3) -#define CV_16SC4 CV_MAKETYPE(CV_16S,4) -#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) - -#define CV_32SC1 CV_MAKETYPE(CV_32S,1) -#define CV_32SC2 CV_MAKETYPE(CV_32S,2) -#define CV_32SC3 CV_MAKETYPE(CV_32S,3) -#define CV_32SC4 CV_MAKETYPE(CV_32S,4) -#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) - -#define CV_32FC1 CV_MAKETYPE(CV_32F,1) -#define CV_32FC2 CV_MAKETYPE(CV_32F,2) -#define CV_32FC3 CV_MAKETYPE(CV_32F,3) -#define CV_32FC4 CV_MAKETYPE(CV_32F,4) -#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) - -#define CV_64FC1 CV_MAKETYPE(CV_64F,1) -#define CV_64FC2 CV_MAKETYPE(CV_64F,2) -#define CV_64FC3 CV_MAKETYPE(CV_64F,3) -#define CV_64FC4 CV_MAKETYPE(CV_64F,4) -#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) - #define CV_AUTO_STEP 0x7fffffff #define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) -#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) -#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) -#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) -#define CV_MAT_CONT_FLAG_SHIFT 14 -#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) -#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) -#define CV_IS_CONT_MAT CV_IS_MAT_CONT -#define CV_SUBMAT_FLAG_SHIFT 15 -#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) -#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) - #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; @@ -677,6 +494,10 @@ typedef struct CvMat int cols; #endif +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvMat() {} + CvMat(const cv::Mat& m) { *this = cvMat(m); } +#endif } CvMat; @@ -712,21 +533,12 @@ CvMat; #define CV_IS_MAT_CONST(mat) \ (((mat)->rows|(mat)->cols) == 1) -/* Size of each channel item, - 0x124489 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ -#define CV_ELEM_SIZE1(type) \ - ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) - -/* 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ -#define CV_ELEM_SIZE(type) \ - (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) - #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!!! +/** Inline constructor. No data is allocated internally!!! * (Use together with cvCreateData, or use cvCreateMat instead to * get a matrix with allocated data): */ @@ -747,6 +559,36 @@ CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL) return m; } +#ifdef __cplusplus + +CV_INLINE CvMat cvMat(const cv::Mat& m) +{ + CvMat self; + CV_DbgAssert(m.dims <= 2); + self = cvMat(m.rows, m.dims == 1 ? 1 : 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 && \ @@ -759,7 +601,15 @@ CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL) #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; @@ -777,7 +627,16 @@ CV_INLINE double cvmGet( const CvMat* mat, int row, int 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; @@ -811,9 +670,17 @@ CV_INLINE int cvIplDepth( int type ) #define CV_TYPE_NAME_MATND "opencv-nd-matrix" #define CV_MAX_DIM 32 -#define CV_MAX_DIM_HEAP 1024 -typedef struct CvMatND +#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; @@ -836,9 +703,24 @@ typedef struct CvMatND 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) @@ -868,9 +750,17 @@ typedef struct CvSparseMat 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) @@ -907,14 +797,14 @@ 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 */ +/** 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, +/** should be used as a parameter only, it turns to CV_HIST_UNIFORM_FLAG of hist->type */ #define CV_HIST_UNIFORM 1 @@ -922,9 +812,9 @@ 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. */ + float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ + float** thresh2; /**< For non-uniform histograms. */ + CvMatND mat; /**< Embedded matrix header for array histograms. */ } CvHistogram; @@ -947,28 +837,50 @@ CvHistogram; \****************************************************************************************/ /*************************************** 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 ) { - CvRect r; - - r.x = x; - r.y = y; - r.width = width; - r.height = 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 ) { @@ -994,26 +906,37 @@ CV_INLINE CvRect cvROIToRect( IplROI roi ) #define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER #define CV_TERMCRIT_EPS 2 +/** @sa TermCriteria + */ typedef struct CvTermCriteria { - int type; /* may be combination of + 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 ) { - CvTermCriteria t; - - t.type = type; - t.max_iter = max_iter; - t.epsilon = (float)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 ***********************************/ @@ -1022,52 +945,110 @@ 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 ) { - CvPoint p; - - p.x = x; - p.y = 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 ) { - CvPoint2D32f p; - - p.x = (float)x; - p.y = (float)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 ) { - CvPoint ipt; - ipt.x = cvRound(point.x); - ipt.y = cvRound(point.y); - +#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; } @@ -1077,37 +1058,78 @@ 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 ) { - CvPoint3D32f p; - - p.x = (float)x; - p.y = (float)y; - p.z = (float)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; - - p.x = x; - p.y = y; - + CvPoint2D64f p = { x, y }; return p; } @@ -1117,18 +1139,25 @@ 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; - - p.x = x; - p.y = y; - p.z = z; - + CvPoint3D64f p = { x, y, z }; return p; } @@ -1139,51 +1168,148 @@ 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 ) { - CvSize s; - - s.width = width; - s.height = 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 ) { - CvSize2D32f s; - - s.width = (float)width; - s.height = (float)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 +/** @sa RotatedRect + */ typedef struct CvBox2D { - CvPoint2D32f center; /* Center of the box. */ - CvSize2D32f size; /* Box width and length. */ - float angle; /* Angle between the horizontal axis */ - /* and the first side (i.e. length) in degrees */ + CvPoint2D32f center; /**< Center of the box. */ + CvSize2D32f size; /**< Box width and length. */ + float angle; /**< Angle between the horizontal axis */ + /**< and the first side (i.e. length) in degrees */ + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} + CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} +#endif +#ifdef __cplusplus + operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } +#endif } CvBox2D; -/* Line iterator state: */ +#ifdef __cplusplus +CV_INLINE CvBox2D cvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) +{ + CvBox2D self; + self.center = c; + self.size = s; + self.angle = a; + return self; +} +CV_INLINE CvBox2D cvBox2D(const cv::RotatedRect& rr) +{ + CvBox2D self; + self.center = cvPoint2D32f(rr.center); + self.size = cvSize2D32f(rr.size); + self.angle = rr.angle; + return self; +} +#endif + + +/** Line iterator state: */ typedef struct CvLineIterator { - /* Pointer to the current point: */ + /** Pointer to the current point: */ uchar* ptr; /* Bresenham algorithm state: */ @@ -1198,47 +1324,136 @@ 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 ) { - CvSlice slice; - slice.start_index = start; - slice.end_index = end; - +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) + CvSlice slice = { start, end }; +#else + CvSlice slice(start, end); +#endif return slice; } -#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff -#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) +#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; @@ -1246,7 +1461,11 @@ CV_INLINE CvScalar cvRealScalar( double val0 ) 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; @@ -1272,11 +1491,11 @@ CvMemBlock; 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. */ + 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; @@ -1297,38 +1516,38 @@ CvMemStoragePos; 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. */ + 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. */ + 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. */ + 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 { @@ -1340,8 +1559,7 @@ CvSeq; #define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" /*************************************** Set ********************************************/ -/* - 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. @@ -1371,28 +1589,30 @@ 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 */ +/** Checks whether the element pointed by ptr belongs to a set or not */ #define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) /************************************* 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. +/** @name Graph - Each edge consists of +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. - o Two pointers to the starting and ending vertices - (vtx[0] and vtx[1] respectively). +Each edge consists of: - 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 the starting and ending vertices (vtx[0] and vtx[1] respectively). - o 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. + 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; \ @@ -1425,7 +1645,7 @@ typedef struct CvGraphVtx2D } CvGraphVtx2D; -/* +/** Graph is "derived" from the set (this is set a of vertices) and includes another set (edges) */ @@ -1441,7 +1661,9 @@ CvGraph; #define CV_TYPE_NAME_GRAPH "opencv-graph" -/*********************************** Chain/Countour *************************************/ +/** @} */ + +/*********************************** Chain/Contour *************************************/ typedef struct CvChain { @@ -1480,45 +1702,45 @@ typedef CvContour CvPoint2DSeq; #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_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_USRTYPE1 -#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_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 */ +/** flag checking */ #define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) @@ -1552,7 +1774,7 @@ typedef CvContour CvPoint2DSeq; #define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) #define CV_IS_SEQ_SIMPLE( seq ) 1 -/* type checking macros */ +/** type checking macros */ #define CV_IS_SEQ_POINT_SET( seq ) \ ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) @@ -1593,11 +1815,11 @@ typedef CvContour CvPoint2DSeq; #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 */ + 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 { @@ -1608,14 +1830,13 @@ 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 */ - + 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 { @@ -1628,7 +1849,7 @@ CvSeqReader; /****************************************************************************************/ #define CV_SEQ_ELEM( seq, elem_type, index ) \ -/* assert gives some guarantee that parameter is valid */ \ +/** 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 < \ @@ -1637,7 +1858,7 @@ CvSeqReader; cvGetSeqElem( (CvSeq*)(seq), (index) ))) #define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) -/* Add element to sequence: */ +/** Add element to sequence: */ #define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ { \ if( (writer).ptr >= (writer).block_max ) \ @@ -1661,7 +1882,7 @@ CvSeqReader; } -/* Move reader position forward: */ +/** Move reader position forward: */ #define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ @@ -1671,7 +1892,7 @@ CvSeqReader; } -/* Move reader position backward: */ +/** Move reader position backward: */ #define CV_PREV_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ @@ -1680,7 +1901,7 @@ CvSeqReader; } \ } -/* Read element and move read position forward: */ +/** Read element and move read position forward: */ #define CV_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ @@ -1688,7 +1909,7 @@ CvSeqReader; CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ } -/* Read element and move read position backward: */ +/** Read element and move read position backward: */ #define CV_REV_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ @@ -1725,7 +1946,7 @@ CvSeqReader; /************ Graph macros ************/ -/* Return next graph edge for given vertex: */ +/** 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)]) @@ -1736,10 +1957,10 @@ CvSeqReader; * Data structures for persistence (a.k.a serialization) functionality * \****************************************************************************************/ -/* "black box" file storage */ +/** "black box" file storage */ typedef struct CvFileStorage CvFileStorage; -/* Storage flags: */ +/** Storage flags: */ #define CV_STORAGE_READ 0 #define CV_STORAGE_WRITE 1 #define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE @@ -1750,15 +1971,25 @@ typedef struct CvFileStorage CvFileStorage; #define CV_STORAGE_FORMAT_AUTO 0 #define CV_STORAGE_FORMAT_XML 8 #define CV_STORAGE_FORMAT_YAML 16 +#define CV_STORAGE_FORMAT_JSON 24 +#define CV_STORAGE_BASE64 64 +#define CV_STORAGE_WRITE_BASE64 (CV_STORAGE_BASE64 | CV_STORAGE_WRITE) -/* List of attributes: */ +/** @brief List of attributes. : + +In the current implementation, attributes are used to pass extra parameters when writing user +objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type +specification (type_id attribute). +@see cvAttrList, cvAttrValue + */ typedef struct CvAttrList { - const char** attr; /* NULL-terminated array of (attribute_name,attribute_value) pairs. */ - struct CvAttrList* next; /* Pointer to next chunk of the attributes list. */ + const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ + struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ } CvAttrList; +/** initializes CvAttrList structure */ CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), CvAttrList* next CV_DEFAULT(NULL) ) { @@ -1778,15 +2009,15 @@ struct CvTypeInfo; #define CV_NODE_FLOAT CV_NODE_REAL #define CV_NODE_STR 3 #define CV_NODE_STRING CV_NODE_STR -#define CV_NODE_REF 4 /* not used */ +#define CV_NODE_REF 4 /**< not used */ #define CV_NODE_SEQ 5 #define CV_NODE_MAP 6 #define CV_NODE_TYPE_MASK 7 #define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) -/* file node flags */ -#define CV_NODE_FLOW 8 /* Used only for writing structures in YAML format. */ +/** file node flags */ +#define CV_NODE_FLOW 8 /**