a big patch; use special proxy types (Input/OutputArray, Input/OutputArrayOfArrays) for passing in vectors, matrices etc.

pull/13383/head
Vadim Pisarevsky 14 years ago
parent 335370a7c0
commit abeeb40d46
  1. 255
      modules/calib3d/include/opencv2/calib3d/calib3d.hpp
  2. 63
      modules/calib3d/src/calibinit.cpp
  3. 647
      modules/calib3d/src/calibration.cpp
  4. 8
      modules/calib3d/src/circlesgrid.cpp
  5. 129
      modules/calib3d/src/fundam.cpp
  6. 34
      modules/calib3d/src/modelest.cpp
  7. 12
      modules/calib3d/src/quadsubpix.cpp
  8. 65
      modules/calib3d/src/solvepnp.cpp
  9. 7
      modules/calib3d/src/stereobm.cpp
  10. 84
      modules/calib3d/src/stereosgbm.cpp
  11. 11
      modules/calib3d/test/test_cameracalibration.cpp
  12. 4
      modules/calib3d/test/test_solvepnp_ransac.cpp
  13. 450
      modules/core/include/opencv2/core/core.hpp
  14. 43
      modules/core/include/opencv2/core/mat.hpp
  15. 18
      modules/core/include/opencv2/core/operations.hpp
  16. 3018
      modules/core/src/arithm.cpp
  17. 8
      modules/core/src/array.cpp
  18. 1251
      modules/core/src/convert.cpp
  19. 452
      modules/core/src/copy.cpp
  20. 215
      modules/core/src/datastructs.cpp
  21. 17
      modules/core/src/drawing.cpp
  22. 84
      modules/core/src/dxt.cpp
  23. 137
      modules/core/src/lapack.cpp
  24. 782
      modules/core/src/mathfuncs.cpp
  25. 1296
      modules/core/src/matmul.cpp
  26. 41
      modules/core/src/matop.cpp
  27. 929
      modules/core/src/matrix.cpp
  28. 258
      modules/core/src/precomp.hpp
  29. 532
      modules/core/src/rand.cpp
  30. 1907
      modules/core/src/stat.cpp
  31. 2
      modules/core/src/system.cpp
  32. 49
      modules/core/test/test_arithm.cpp
  33. 1
      modules/core/test/test_dxt.cpp
  34. 85
      modules/core/test/test_mat.cpp
  35. 2
      modules/features2d/src/bagofwords.cpp
  36. 11
      modules/features2d/test/test_nearestneighbors.cpp
  37. 2
      modules/gpu/test/test_filters.cpp
  38. 2
      modules/gpu/test/test_hog.cpp
  39. 2
      modules/gpu/test/test_operator_async_call.cpp
  40. 2
      modules/gpu/test/test_operator_convert_to.cpp
  41. 2
      modules/gpu/test/test_operator_copy_to.cpp
  42. 2
      modules/gpu/test/test_operator_set_to.cpp
  43. 2
      modules/gpu/test/test_stereo_bm.cpp
  44. 2
      modules/gpu/test/test_stereo_bm_async.cpp
  45. 2
      modules/gpu/test/test_stereo_bp.cpp
  46. 2
      modules/gpu/test/test_stereo_csbp.cpp
  47. 18
      modules/highgui/include/opencv2/highgui/highgui.hpp
  48. 11
      modules/highgui/src/loadsave.cpp
  49. 51
      modules/highgui/src/window.cpp
  50. 288
      modules/imgproc/include/opencv2/imgproc/imgproc.hpp
  51. 711
      modules/imgproc/src/accum.cpp
  52. 10
      modules/imgproc/src/canny.cpp
  53. 63
      modules/imgproc/src/color.cpp
  54. 250
      modules/imgproc/src/contours.cpp
  55. 34
      modules/imgproc/src/corner.cpp
  56. 10
      modules/imgproc/src/cornersubpix.cpp
  57. 61
      modules/imgproc/src/deriv.cpp
  58. 21
      modules/imgproc/src/distransform.cpp
  59. 25
      modules/imgproc/src/emd.cpp
  60. 16
      modules/imgproc/src/featureselect.cpp
  61. 87
      modules/imgproc/src/filter.cpp
  62. 12
      modules/imgproc/src/floodfill.cpp
  63. 13
      modules/imgproc/src/grabcut.cpp
  64. 94
      modules/imgproc/src/histogram.cpp
  65. 49
      modules/imgproc/src/hough.cpp
  66. 68
      modules/imgproc/src/imgwarp.cpp
  67. 9
      modules/imgproc/src/inpaint.cpp
  68. 7
      modules/imgproc/src/moments.cpp
  69. 63
      modules/imgproc/src/morph.cpp
  70. 37
      modules/imgproc/src/pyramids.cpp
  71. 12
      modules/imgproc/src/samplers.cpp
  72. 16
      modules/imgproc/src/segmentation.cpp
  73. 51
      modules/imgproc/src/smooth.cpp
  74. 138
      modules/imgproc/src/sumpixels.cpp
  75. 15
      modules/imgproc/src/templmatch.cpp
  76. 58
      modules/imgproc/src/thresh.cpp
  77. 124
      modules/imgproc/src/undistort.cpp
  78. 10
      modules/imgproc/src/utils.cpp
  79. 4
      modules/imgproc/test/test_imgwarp.cpp
  80. 7
      modules/ml/src/ann_mlp.cpp
  81. 12
      modules/ml/src/knearest.cpp
  82. 6
      modules/ml/test/test_emknearestkmeans.cpp
  83. 2
      modules/objdetect/src/planardetect.cpp
  84. 14
      modules/ts/include/opencv2/ts/ts.hpp
  85. 2
      modules/ts/src/ts_func.cpp
  86. 99
      modules/video/include/opencv2/video/background_segm.hpp
  87. 31
      modules/video/include/opencv2/video/tracking.hpp
  88. 8
      modules/video/src/bgfg_gaussmix.cpp
  89. 1241
      modules/video/src/bgfg_gaussmix2.cpp
  90. 16
      modules/video/src/camshift.cpp
  91. 55
      modules/video/src/lkpyramid.cpp
  92. 34
      modules/video/src/motempl.cpp
  93. 13
      modules/video/src/optflowgf.cpp
  94. 17
      modules/video/test/test_motiontemplates.cpp

@ -432,10 +432,7 @@ namespace cv
{ {
//! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation //! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation
CV_EXPORTS_W void Rodrigues(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void Rodrigues(const InputArray& src, OutputArray dst, OutputArray jacobian=OutputArray());
//! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation. Also computes the Jacobian matrix
CV_EXPORTS_AS(RodriguesJ) void Rodrigues(const Mat& src, CV_OUT Mat& dst, CV_OUT Mat& jacobian);
//! type of the robust estimation algorithm //! type of the robust estimation algorithm
enum enum
@ -445,128 +442,93 @@ enum
}; };
//! computes the best-fit perspective transformation mapping srcPoints to dstPoints. //! computes the best-fit perspective transformation mapping srcPoints to dstPoints.
CV_EXPORTS_AS(findHomographyAndOutliers) Mat findHomography( const Mat& srcPoints, CV_EXPORTS_W Mat findHomography( const InputArray& srcPoints,
const Mat& dstPoints, const InputArray& dstPoints,
vector<uchar>& mask, int method=0, int method=0, double ransacReprojThreshold=3,
double ransacReprojThreshold=3 ); OutputArray mask=OutputArray());
//! computes the best-fit perspective transformation mapping srcPoints to dstPoints.
CV_EXPORTS_W Mat findHomography( const Mat& srcPoints,
const Mat& dstPoints,
int method=0, double ransacReprojThreshold=3 );
//! computes the best-fit affine transformation that maps one 3D point set to another (RANSAC algorithm is used)
CV_EXPORTS int estimateAffine3D(const Mat& from, const Mat& to, CV_OUT Mat& dst,
CV_OUT vector<uchar>& outliers,
double param1 = 3.0, double param2 = 0.99);
//! Computes RQ decomposition of 3x3 matrix //! Computes RQ decomposition of 3x3 matrix
CV_EXPORTS void RQDecomp3x3( const Mat& M, Mat& R, Mat& Q ); CV_EXPORTS_W Vec3d RQDecomp3x3( const InputArray& src, OutputArray mtxR, OutputArray mtxQ,
OutputArray Qx=OutputArray(),
//! Computes RQ decomposition of 3x3 matrix. Also, decomposes the output orthogonal matrix into the 3 primitive rotation matrices OutputArray Qy=OutputArray(),
CV_EXPORTS_W Vec3d RQDecomp3x3( const Mat& M, Mat& R, Mat& Q, OutputArray Qz=OutputArray());
CV_OUT Mat& Qx, CV_OUT Mat& Qy, CV_OUT Mat& Qz );
//! Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector //! Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector
CV_EXPORTS void decomposeProjectionMatrix( const Mat& projMatrix, Mat& cameraMatrix, CV_EXPORTS_W void decomposeProjectionMatrix( const InputArray& projMatrix, OutputArray cameraMatrix,
Mat& rotMatrix, Mat& transVect ); OutputArray rotMatrix, OutputArray transVect,
OutputArray rotMatrixX=OutputArray(),
//! Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector. The rotation matrix is further decomposed OutputArray rotMatrixY=OutputArray(),
CV_EXPORTS_W void decomposeProjectionMatrix( const Mat& projMatrix, CV_OUT Mat& cameraMatrix, OutputArray rotMatrixZ=OutputArray(),
CV_OUT Mat& rotMatrix, CV_OUT Mat& transVect, OutputArray eulerAngles=OutputArray() );
CV_OUT Mat& rotMatrixX, CV_OUT Mat& rotMatrixY,
CV_OUT Mat& rotMatrixZ, CV_OUT Vec3d& eulerAngles );
//! computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients //! computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients
CV_EXPORTS_W void matMulDeriv( const Mat& A, const Mat& B, CV_OUT Mat& dABdA, CV_OUT Mat& dABdB ); CV_EXPORTS_W void matMulDeriv( const InputArray& A, const InputArray& B,
OutputArray dABdA,
//! composes 2 [R|t] transformations together OutputArray dABdB );
CV_EXPORTS_W void composeRT( const Mat& rvec1, const Mat& tvec1,
const Mat& rvec2, const Mat& tvec2,
CV_OUT Mat& rvec3, CV_OUT Mat& tvec3 );
//! composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments //! composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments
CV_EXPORTS_AS(composeRT_J) void composeRT( const Mat& rvec1, const Mat& tvec1, CV_EXPORTS_W void composeRT( const InputArray& rvec1, const InputArray& tvec1,
const Mat& rvec2, const Mat& tvec2, const InputArray& rvec2, const InputArray& tvec2,
CV_OUT Mat& rvec3, CV_OUT Mat& tvec3, OutputArray rvec3, OutputArray tvec3,
CV_OUT Mat& dr3dr1, CV_OUT Mat& dr3dt1, OutputArray dr3dr1=OutputArray(), OutputArray dr3dt1=OutputArray(),
CV_OUT Mat& dr3dr2, CV_OUT Mat& dr3dt2, OutputArray dr3dr2=OutputArray(), OutputArray dr3dt2=OutputArray(),
CV_OUT Mat& dt3dr1, CV_OUT Mat& dt3dt1, OutputArray dt3dr1=OutputArray(), OutputArray dt3dt1=OutputArray(),
CV_OUT Mat& dt3dr2, CV_OUT Mat& dt3dt2 ); OutputArray dt3dr2=OutputArray(), OutputArray dt3dt2=OutputArray() );
//! projects points from the model coordinate space to the image coordinates. Takes the intrinsic and extrinsic camera parameters into account
CV_EXPORTS_W void projectPoints( const Mat& objectPoints,
const Mat& rvec, const Mat& tvec,
const Mat& cameraMatrix,
const Mat& distCoeffs,
CV_OUT vector<Point2f>& imagePoints );
//! 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 //! 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_AS(projectPointsJ) void projectPoints( const Mat& objectPoints, CV_EXPORTS_W void projectPoints( const InputArray& objectPoints,
const Mat& rvec, const Mat& tvec, const InputArray& rvec, const InputArray& tvec,
const Mat& cameraMatrix, const InputArray& cameraMatrix, const InputArray& distCoeffs,
const Mat& distCoeffs, OutputArray imagePoints,
CV_OUT vector<Point2f>& imagePoints, OutputArray jacobian=OutputArray(),
CV_OUT Mat& dpdrot, CV_OUT Mat& dpdt, CV_OUT Mat& dpdf,
CV_OUT Mat& dpdc, CV_OUT Mat& dpddist,
double aspectRatio=0 ); double aspectRatio=0 );
//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled. //! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled.
CV_EXPORTS_W void solvePnP( const Mat& objectPoints, CV_EXPORTS_W void solvePnP( const InputArray& objectPoints, const InputArray& imagePoints,
const Mat& imagePoints, const InputArray& cameraMatrix, const InputArray& distCoeffs,
const Mat& cameraMatrix, OutputArray rvec, OutputArray tvec,
const Mat& distCoeffs,
CV_OUT Mat& rvec, CV_OUT Mat& tvec,
bool useExtrinsicGuess=false ); bool useExtrinsicGuess=false );
//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. //! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible.
CV_EXPORTS_W void solvePnPRansac( const Mat& objectPoints, CV_EXPORTS_W void solvePnPRansac( const InputArray& objectPoints,
const Mat& imagePoints, const InputArray& imagePoints,
const Mat& cameraMatrix, const InputArray& cameraMatrix,
const Mat& distCoeffs, const InputArray& distCoeffs,
CV_OUT Mat& rvec, OutputArray rvec,
CV_OUT Mat& tvec, OutputArray tvec,
bool useExtrinsicGuess = false, bool useExtrinsicGuess = false,
int iterationsCount = 100, int iterationsCount = 100,
float reprojectionError = 8.0, float reprojectionError = 8.0,
int minInliersCount = 100, int minInliersCount = 100,
CV_OUT vector<int>* inliers = NULL ); OutputArray inliers = OutputArray() );
//! initializes camera matrix from a few 3D points and the corresponding projections. //! initializes camera matrix from a few 3D points and the corresponding projections.
CV_EXPORTS_W Mat initCameraMatrix2D( const vector<vector<Point3f> >& objectPoints, CV_EXPORTS_W Mat initCameraMatrix2D( const InputArrayOfArrays& objectPoints,
const vector<vector<Point2f> >& imagePoints, const InputArrayOfArrays& imagePoints,
Size imageSize, double aspectRatio=1. ); Size imageSize, double aspectRatio=1. );
enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2, enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2,
CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8 }; CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8 };
//! finds checkerboard pattern of the specified size in the image //! finds checkerboard pattern of the specified size in the image
CV_EXPORTS_W bool findChessboardCorners( const Mat& image, Size patternSize, CV_EXPORTS_W bool findChessboardCorners( const InputArray& image, Size patternSize,
CV_OUT vector<Point2f>& corners, OutputArray corners,
int flags=CALIB_CB_ADAPTIVE_THRESH+ int flags=CALIB_CB_ADAPTIVE_THRESH+
CALIB_CB_NORMALIZE_IMAGE ); CALIB_CB_NORMALIZE_IMAGE );
//! finds subpixel-accurate positions of the chessboard corners //! finds subpixel-accurate positions of the chessboard corners
CV_EXPORTS bool find4QuadCornerSubpix(const Mat& img, std::vector<Point2f>& corners, CV_EXPORTS bool find4QuadCornerSubpix(const InputArray& img, InputOutputArray corners, Size region_size);
Size region_size);
//! draws the checkerboard pattern (found or partly found) in the image //! draws the checkerboard pattern (found or partly found) in the image
CV_EXPORTS_W void drawChessboardCorners( Mat& image, Size patternSize, CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize,
const Mat& corners, const InputArray& corners, bool patternWasFound );
bool patternWasFound );
CV_EXPORTS void drawChessboardCorners( Mat& image, Size patternSize,
const vector<Point2f>& corners,
bool patternWasFound );
enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2, enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2,
CALIB_CB_CLUSTERING = 4, CALIB_CB_WHITE_CIRCLES = 8 }; CALIB_CB_CLUSTERING = 4, CALIB_CB_WHITE_CIRCLES = 8 };
//! finds circles' grid pattern of the specified size in the image //! finds circles' grid pattern of the specified size in the image
CV_EXPORTS_W bool findCirclesGrid( const Mat& image, Size patternSize, CV_EXPORTS_W bool findCirclesGrid( const InputArray& image, Size patternSize,
CV_OUT vector<Point2f>& centers, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID );
int flags=CALIB_CB_SYMMETRIC_GRID );
enum enum
{ {
@ -590,16 +552,16 @@ enum
}; };
//! finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern. //! finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern.
CV_EXPORTS_W double calibrateCamera( const vector<vector<Point3f> >& objectPoints, CV_EXPORTS_W double calibrateCamera( const InputArrayOfArrays& objectPoints,
const vector<vector<Point2f> >& imagePoints, const InputArrayOfArrays& imagePoints,
Size imageSize, Size imageSize,
CV_IN_OUT Mat& cameraMatrix, CV_IN_OUT InputOutputArray cameraMatrix,
CV_IN_OUT Mat& distCoeffs, CV_IN_OUT InputOutputArray distCoeffs,
CV_OUT vector<Mat>& rvecs, CV_OUT vector<Mat>& tvecs, OutputArray rvecs, OutputArray tvecs,
int flags=0 ); int flags=0 );
//! computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size. //! computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size.
CV_EXPORTS_W void calibrationMatrixValues( const Mat& cameraMatrix, CV_EXPORTS_W void calibrationMatrixValues( const InputArray& cameraMatrix,
Size imageSize, Size imageSize,
double apertureWidth, double apertureWidth,
double apertureHeight, double apertureHeight,
@ -610,64 +572,58 @@ CV_EXPORTS_W void calibrationMatrixValues( const Mat& cameraMatrix,
CV_OUT double& aspectRatio ); CV_OUT double& aspectRatio );
//! finds intrinsic and extrinsic parameters of a stereo camera //! finds intrinsic and extrinsic parameters of a stereo camera
CV_EXPORTS_W double stereoCalibrate( const vector<vector<Point3f> >& objectPoints, CV_EXPORTS_W double stereoCalibrate( const InputArrayOfArrays& objectPoints,
const vector<vector<Point2f> >& imagePoints1, const InputArrayOfArrays& imagePoints1,
const vector<vector<Point2f> >& imagePoints2, const InputArrayOfArrays& imagePoints2,
CV_IN_OUT Mat& cameraMatrix1, CV_IN_OUT Mat& distCoeffs1, CV_IN_OUT InputOutputArray cameraMatrix1,
CV_IN_OUT Mat& cameraMatrix2, CV_IN_OUT Mat& distCoeffs2, CV_IN_OUT InputOutputArray distCoeffs1,
Size imageSize, CV_OUT Mat& R, CV_OUT Mat& T, CV_IN_OUT InputOutputArray cameraMatrix2,
CV_OUT Mat& E, CV_OUT Mat& F, CV_IN_OUT InputOutputArray distCoeffs2,
Size imageSize, OutputArray R,
OutputArray T, OutputArray E, OutputArray F,
TermCriteria criteria = TermCriteria(TermCriteria::COUNT+ TermCriteria criteria = TermCriteria(TermCriteria::COUNT+
TermCriteria::EPS, 30, 1e-6), TermCriteria::EPS, 30, 1e-6),
int flags=CALIB_FIX_INTRINSIC ); int flags=CALIB_FIX_INTRINSIC );
//! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters //! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters
CV_EXPORTS void stereoRectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, CV_EXPORTS void stereoRectify( const InputArray& cameraMatrix1, const InputArray& distCoeffs1,
const Mat& cameraMatrix2, const Mat& distCoeffs2, const InputArray& cameraMatrix2, const InputArray& distCoeffs2,
Size imageSize, const Mat& R, const Mat& T, Size imageSize, const InputArray& R, const InputArray& T,
CV_OUT Mat& R1, CV_OUT Mat& R2, OutputArray R1, OutputArray R2,
CV_OUT Mat& P1, CV_OUT Mat& P2, CV_OUT Mat& Q, OutputArray P1, OutputArray P2,
int flags=CALIB_ZERO_DISPARITY ); OutputArray Q, int flags=CALIB_ZERO_DISPARITY,
double alpha=-1, Size newImageSize=Size(),
//! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters CV_OUT Rect* validPixROI1=0, CV_OUT Rect* validPixROI2=0 );
CV_EXPORTS_W void stereoRectify( const Mat& cameraMatrix1, const Mat& distCoeffs1,
const Mat& cameraMatrix2, const Mat& distCoeffs2,
Size imageSize, const Mat& R, const Mat& T,
CV_OUT Mat& R1, CV_OUT Mat& R2,
CV_OUT Mat& P1, CV_OUT Mat& P2, CV_OUT Mat& Q,
double alpha, Size newImageSize=Size(),
CV_OUT Rect* validPixROI1=0, CV_OUT Rect* validPixROI2=0,
int flags=CALIB_ZERO_DISPARITY );
//! computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed) //! computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed)
CV_EXPORTS_W bool stereoRectifyUncalibrated( const Mat& points1, const Mat& points2, CV_EXPORTS_W bool stereoRectifyUncalibrated( const InputArray& points1, const InputArray& points2,
const Mat& F, Size imgSize, const InputArray& F, Size imgSize,
CV_OUT Mat& H1, CV_OUT Mat& H2, OutputArray H1, OutputArray H2,
double threshold=5 ); double threshold=5 );
//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. //! computes the rectification transformations for 3-head camera, where all the heads are on the same line.
CV_EXPORTS_W float rectify3Collinear( const Mat& cameraMatrix1, const Mat& distCoeffs1, CV_EXPORTS_W float rectify3Collinear( const InputArray& cameraMatrix1, const InputArray& distCoeffs1,
const Mat& cameraMatrix2, const Mat& distCoeffs2, const InputArray& cameraMatrix2, const InputArray& distCoeffs2,
const Mat& cameraMatrix3, const Mat& distCoeffs3, const InputArray& cameraMatrix3, const InputArray& distCoeffs3,
const vector<vector<Point2f> >& imgpt1, const InputArrayOfArrays& imgpt1, const InputArrayOfArrays& imgpt3,
const vector<vector<Point2f> >& imgpt3, Size imageSize, const InputArray& R12, const InputArray& T12,
Size imageSize, const Mat& R12, const Mat& T12, const InputArray& R13, const InputArray& T13,
const Mat& R13, const Mat& T13, OutputArray R1, OutputArray R2, OutputArray R3,
CV_OUT Mat& R1, CV_OUT Mat& R2, CV_OUT Mat& R3, OutputArray P1, OutputArray P2, OutputArray P3,
CV_OUT Mat& P1, CV_OUT Mat& P2, CV_OUT Mat& P3, CV_OUT Mat& Q, OutputArray Q, double alpha, Size newImgSize,
double alpha, Size newImgSize,
CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
//! returns the optimal new camera matrix //! returns the optimal new camera matrix
CV_EXPORTS_W Mat getOptimalNewCameraMatrix( const Mat& cameraMatrix, const Mat& distCoeffs, CV_EXPORTS_W Mat getOptimalNewCameraMatrix( const InputArray& cameraMatrix, const InputArray& distCoeffs,
Size imageSize, double alpha, Size newImgSize=Size(), Size imageSize, double alpha, Size newImgSize=Size(),
CV_OUT Rect* validPixROI=0); CV_OUT Rect* validPixROI=0);
//! converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) //! converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1))
CV_EXPORTS void convertPointsHomogeneous( const Mat& src, CV_OUT vector<Point3f>& dst ); CV_EXPORTS void convertPointsToHomogeneous( const InputArray& src, OutputArray dst );
//! converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) //! converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z))
CV_EXPORTS void convertPointsHomogeneous( const Mat& src, CV_OUT vector<Point2f>& dst ); CV_EXPORTS void convertPointsFromHomogeneous( const InputArray& src, OutputArray dst );
//! the algorithm for finding fundamental matrix //! the algorithm for finding fundamental matrix
enum enum
@ -679,19 +635,15 @@ enum
}; };
//! finds fundamental matrix from a set of corresponding 2D points //! finds fundamental matrix from a set of corresponding 2D points
CV_EXPORTS Mat findFundamentalMat( const Mat& points1, const Mat& points2, CV_EXPORTS_W Mat findFundamentalMat( const InputArray& points1, const InputArray& points2,
CV_OUT vector<uchar>& mask, int method=FM_RANSAC,
double param1=3., double param2=0.99 );
//! finds fundamental matrix from a set of corresponding 2D points
CV_EXPORTS_W Mat findFundamentalMat( const Mat& points1, const Mat& points2,
int method=FM_RANSAC, int method=FM_RANSAC,
double param1=3., double param2=0.99 ); double param1=3., double param2=0.99,
OutputArray mask=OutputArray());
//! finds coordinates of epipolar lines corresponding the specified points //! finds coordinates of epipolar lines corresponding the specified points
CV_EXPORTS void computeCorrespondEpilines( const Mat& points1, CV_EXPORTS void computeCorrespondEpilines( const InputArray& points1,
int whichImage, const Mat& F, int whichImage, const InputArray& F,
CV_OUT vector<Vec3f>& lines ); OutputArray lines );
template<> CV_EXPORTS void Ptr<CvStereoBMState>::delete_obj(); template<> CV_EXPORTS void Ptr<CvStereoBMState>::delete_obj();
@ -713,7 +665,8 @@ public:
//! the method that reinitializes the state. The previous content is destroyed //! the method that reinitializes the state. The previous content is destroyed
void init(int preset, int ndisparities=0, int SADWindowSize=21); void init(int preset, int ndisparities=0, int SADWindowSize=21);
//! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
CV_WRAP_AS(compute) void operator()( const Mat& left, const Mat& right, Mat& disparity, int disptype=CV_16S ); CV_WRAP_AS(compute) void operator()( const InputArray& left, const InputArray& right,
OutputArray disparity, int disptype=CV_16S );
//! pointer to the underlying CvStereoBMState //! pointer to the underlying CvStereoBMState
Ptr<CvStereoBMState> state; Ptr<CvStereoBMState> state;
@ -743,7 +696,8 @@ public:
virtual ~StereoSGBM(); virtual ~StereoSGBM();
//! the stereo correspondence operator that computes disparity map for the specified rectified stereo pair //! the stereo correspondence operator that computes disparity map for the specified rectified stereo pair
CV_WRAP_AS(compute) virtual void operator()(const Mat& left, const Mat& right, Mat& disp); CV_WRAP_AS(compute) virtual void operator()(const InputArray& left, const InputArray& right,
OutputArray disp);
CV_PROP_RW int minDisparity; CV_PROP_RW int minDisparity;
CV_PROP_RW int numberOfDisparities; CV_PROP_RW int numberOfDisparities;
@ -762,7 +716,8 @@ protected:
}; };
//! filters off speckles (small regions of incorrectly computed disparity) //! filters off speckles (small regions of incorrectly computed disparity)
CV_EXPORTS_W void filterSpeckles( Mat& img, double newVal, int maxSpeckleSize, double maxDiff, Mat& buf ); CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff,
InputOutputArray buf=InputOutputArray() );
//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify()) //! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify())
CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
@ -770,16 +725,20 @@ CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
int SADWindowSize ); int SADWindowSize );
//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm //! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
CV_EXPORTS_W void validateDisparity( Mat& disparity, const Mat& cost, CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, const InputArray& cost,
int minDisparity, int numberOfDisparities, int minDisparity, int numberOfDisparities,
int disp12MaxDisp=1 ); int disp12MaxDisp=1 );
//! reprojects disparity image to 3D: (x,y,d)->(X,Y,Z) using the matrix Q returned by cv::stereoRectify //! reprojects disparity image to 3D: (x,y,d)->(X,Y,Z) using the matrix Q returned by cv::stereoRectify
CV_EXPORTS_W void reprojectImageTo3D( const Mat& disparity, CV_EXPORTS_W void reprojectImageTo3D( const InputArray& disparity,
CV_OUT Mat& _3dImage, const Mat& Q, OutputArray _3dImage, const InputArray& Q,
bool handleMissingValues=false, bool handleMissingValues=false,
int ddepth=-1 ); int ddepth=-1 );
CV_EXPORTS_W int estimateAffine3D(const InputArray& _from, const InputArray& _to,
OutputArray _out, OutputArray _outliers,
double param1=3, double param2=0.99);
} }
#endif #endif

@ -1894,49 +1894,43 @@ cvDrawChessboardCorners( CvArr* _image, CvSize pattern_size,
} }
} }
namespace cv bool cv::findChessboardCorners( const InputArray& _image, Size patternSize,
{ OutputArray corners, int flags )
bool findChessboardCorners( const Mat& image, Size patternSize,
vector<Point2f>& corners, int flags )
{ {
int count = patternSize.area()*2; int count = patternSize.area()*2;
corners.resize(count); vector<Point2f> tmpcorners(count+1);
CvMat _image = image; CvMat c_image = _image.getMat();
bool ok = cvFindChessboardCorners(&_image, patternSize, bool ok = cvFindChessboardCorners(&c_image, patternSize,
(CvPoint2D32f*)&corners[0], &count, flags ) > 0; (CvPoint2D32f*)&tmpcorners[0], &count, flags ) > 0;
if(count >= 0) if( count > 0 )
corners.resize(count); {
tmpcorners.resize(count);
Mat(tmpcorners).copyTo(corners);
}
else
corners.release();
return ok; return ok;
} }
void drawChessboardCorners( Mat& image, Size patternSize, void cv::drawChessboardCorners( InputOutputArray _image, Size patternSize,
const Mat& corners, const InputArray& _corners,
bool patternWasFound ) bool patternWasFound )
{ {
if( corners.cols == 0 || corners.rows == 0 ) Mat corners = _corners.getMat();
if( !corners.empty() )
return; return;
CvMat _image = image; CvMat c_image = _image.getMat();
int nelems = corners.checkVector(2, CV_32F, true); int nelems = corners.checkVector(2, CV_32F, true);
CV_Assert(nelems >= 0); CV_Assert(nelems >= 0);
cvDrawChessboardCorners( &_image, patternSize, (CvPoint2D32f*)corners.data, cvDrawChessboardCorners( &c_image, patternSize, (CvPoint2D32f*)corners.data,
nelems, patternWasFound ); nelems, patternWasFound );
} }
void drawChessboardCorners( Mat& image, Size patternSize, bool cv::findCirclesGrid( const InputArray& _image, Size patternSize,
const vector<Point2f>& corners, OutputArray _centers, int flags )
bool patternWasFound )
{
if( corners.empty() )
return;
CvMat _image = image;
cvDrawChessboardCorners( &_image, patternSize, (CvPoint2D32f*)&corners[0],
(int)corners.size(), patternWasFound );
}
bool findCirclesGrid( const Mat& image, Size patternSize,
vector<Point2f>& centers, int flags )
{ {
Mat image = _image.getMat();
vector<Point2f> centers;
SimpleBlobDetector::Params params; SimpleBlobDetector::Params params;
if(flags & CALIB_CB_WHITE_CIRCLES) if(flags & CALIB_CB_WHITE_CIRCLES)
{ {
@ -1957,6 +1951,7 @@ bool findCirclesGrid( const Mat& image, Size patternSize,
{ {
CirclesGridClusterFinder circlesGridClusterFinder; CirclesGridClusterFinder circlesGridClusterFinder;
circlesGridClusterFinder.findGrid(points, patternSize, centers); circlesGridClusterFinder.findGrid(points, patternSize, centers);
Mat(centers).copyTo(_centers);
return !centers.empty(); return !centers.empty();
} }
@ -2005,10 +2000,10 @@ bool findCirclesGrid( const Mat& image, Size patternSize,
if (i != 0) if (i != 0)
{ {
Mat orgPointsMat; Mat orgPointsMat;
transform(Mat(centers), orgPointsMat, H.inv()); transform(centers, orgPointsMat, H.inv());
convertPointsHomogeneous(orgPointsMat, centers); convertPointsFromHomogeneous(orgPointsMat, centers);
} }
Mat(centers).copyTo(_centers);
return true; return true;
} }
@ -2020,10 +2015,8 @@ bool findCirclesGrid( const Mat& image, Size patternSize,
H = CirclesGridFinder::rectifyGrid(boxFinder.getDetectedGridSize(), centers, points, points); H = CirclesGridFinder::rectifyGrid(boxFinder.getDetectedGridSize(), centers, points, points);
} }
} }
Mat(centers).copyTo(_centers);
return false; return false;
} }
}
/* End of file. */ /* End of file. */

@ -2753,10 +2753,11 @@ CV_IMPL int cvStereoRectifyUncalibrated(
} }
void cv::reprojectImageTo3D( const Mat& disparity, void cv::reprojectImageTo3D( const InputArray& _disparity,
Mat& _3dImage, const Mat& Q, OutputArray __3dImage, const InputArray& _Qmat,
bool handleMissingValues, int dtype ) bool handleMissingValues, int dtype )
{ {
Mat disparity = _disparity.getMat(), Q = _Qmat.getMat();
int stype = disparity.type(); int stype = disparity.type();
CV_Assert( stype == CV_8UC1 || stype == CV_16SC1 || CV_Assert( stype == CV_8UC1 || stype == CV_16SC1 ||
@ -2771,7 +2772,8 @@ void cv::reprojectImageTo3D( const Mat& disparity,
CV_Assert( dtype == CV_16SC3 || dtype == CV_32SC3 || dtype == CV_32FC3 ); CV_Assert( dtype == CV_16SC3 || dtype == CV_32SC3 || dtype == CV_32FC3 );
} }
_3dImage.create(disparity.size(), CV_MAKETYPE(dtype, 3)); __3dImage.create(disparity.size(), CV_MAKETYPE(dtype, 3));
Mat _3dImage = __3dImage.getMat();
const double bigZ = 10000.; const double bigZ = 10000.;
double q[4][4]; double q[4][4];
@ -3092,45 +3094,56 @@ cvDecomposeProjectionMatrix( const CvMat *projMatr, CvMat *calibMatr,
namespace cv namespace cv
{ {
static void collectCalibrationData( const vector<vector<Point3f> >& objectPoints, static void collectCalibrationData( const InputArrayOfArrays& objectPoints,
const vector<vector<Point2f> >& imagePoints, const InputArrayOfArrays& imagePoints1,
const vector<vector<Point2f> >& imagePoints2, const InputArrayOfArrays& imagePoints2,
Mat& objPtMat, Mat& imgPtMat, Mat* imgPtMat2, Mat& objPtMat, Mat& imgPtMat1, Mat* imgPtMat2,
Mat& npoints ) Mat& npoints )
{ {
size_t i, j = 0, ni = 0, nimages = objectPoints.size(), total = 0; int nimages = (int)objectPoints.total();
CV_Assert(nimages > 0 && nimages == imagePoints.size() && int i, j = 0, ni = 0, total = 0;
(!imgPtMat2 || nimages == imagePoints2.size())); CV_Assert(nimages > 0 && nimages == (int)imagePoints1.total() &&
(!imgPtMat2 || nimages == (int)imagePoints2.total()));
for( i = 0; i < nimages; i++ ) for( i = 0; i < nimages; i++ )
{ {
ni = objectPoints[i].size(); ni = objectPoints.getMat(i).checkVector(3, CV_32F);
CV_Assert(ni == imagePoints[i].size() && (!imgPtMat2 || ni == imagePoints2[i].size())); CV_Assert( ni >= 0 );
total += ni; total += ni;
} }
npoints.create(1, (int)nimages, CV_32S); npoints.create(1, (int)nimages, CV_32S);
objPtMat.create(1, (int)total, DataType<Point3f>::type); objPtMat.create(1, (int)total, CV_32FC3);
imgPtMat.create(1, (int)total, DataType<Point2f>::type); imgPtMat1.create(1, (int)total, CV_32FC2);
Point2f* imgPtData2 = 0; Point2f* imgPtData2 = 0;
if( imgPtMat2 ) if( imgPtMat2 )
{ {
imgPtMat2->create(1, (int)total, DataType<Point2f>::type); imgPtMat2->create(1, (int)total, CV_32FC2);
imgPtData2 = imgPtMat2->ptr<Point2f>(); imgPtData2 = imgPtMat2->ptr<Point2f>();
} }
Point3f* objPtData = objPtMat.ptr<Point3f>(); Point3f* objPtData = objPtMat.ptr<Point3f>();
Point2f* imgPtData = imgPtMat.ptr<Point2f>(); Point2f* imgPtData1 = imgPtMat1.ptr<Point2f>();
for( i = 0; i < nimages; i++, j += ni ) for( i = 0; i < nimages; i++, j += ni )
{ {
ni = objectPoints[i].size(); Mat objpt = objectPoints.getMat(i);
((int*)npoints.data)[i] = (int)ni; Mat imgpt1 = imagePoints1.getMat(i);
std::copy(objectPoints[i].begin(), objectPoints[i].end(), objPtData + j); ni = objpt.checkVector(3, CV_32F);
std::copy(imagePoints[i].begin(), imagePoints[i].end(), imgPtData + j); int ni1 = imgpt1.checkVector(2, CV_32F);
if( imgPtMat2 ) CV_Assert( ni > 0 && ni == ni1 );
std::copy(imagePoints2[i].begin(), imagePoints2[i].end(), imgPtData2 + j); npoints.at<int>(i) = ni;
memcpy( objPtData + j, objpt.data, ni*sizeof(objPtData[0]) );
memcpy( imgPtData1 + j, imgpt1.data, ni*sizeof(imgPtData1[0]) );
if( imgPtData2 )
{
Mat imgpt2 = imagePoints2.getMat(i);
int ni2 = imgpt2.checkVector(2, CV_32F);
CV_Assert( ni == ni2 );
memcpy( imgPtData2 + j, imgpt2.data, ni*sizeof(imgPtData2[0]) );
}
} }
} }
@ -3162,126 +3175,153 @@ static Mat prepareDistCoeffs(Mat& distCoeffs0, int rtype)
} }
void cv::Rodrigues(const Mat& src, Mat& dst) void cv::Rodrigues(const InputArray& _src, OutputArray _dst, OutputArray _jacobian)
{ {
Mat src = _src.getMat();
bool v2m = src.cols == 1 || src.rows == 1; bool v2m = src.cols == 1 || src.rows == 1;
dst.create(3, v2m ? 3 : 1, src.depth()); _dst.create(3, v2m ? 3 : 1, src.depth());
CvMat _src = src, _dst = dst; Mat dst = _dst.getMat();
bool ok = cvRodrigues2(&_src, &_dst, 0) > 0; CvMat _csrc = src, _cdst = dst, _cjacobian;
if( _jacobian.needed() )
{
_jacobian.create(v2m ? Size(9, 3) : Size(3, 9), src.depth());
_cjacobian = _jacobian.getMat();
}
bool ok = cvRodrigues2(&_csrc, &_cdst, _jacobian.needed() ? &_cjacobian : 0) > 0;
if( !ok ) if( !ok )
dst = Scalar(0); dst = Scalar(0);
} }
void cv::Rodrigues(const Mat& src, Mat& dst, Mat& jacobian) void cv::matMulDeriv( const InputArray& _Amat, const InputArray& _Bmat,
OutputArray _dABdA, OutputArray _dABdB )
{ {
bool v2m = src.cols == 1 || src.rows == 1; Mat A = _Amat.getMat(), B = _Bmat.getMat();
dst.create(3, v2m ? 3 : 1, src.depth()); _dABdA.create(A.rows*B.cols, A.rows*A.cols, A.type());
jacobian.create(v2m ? Size(9, 3) : Size(3, 9), src.depth()); _dABdB.create(A.rows*B.cols, B.rows*B.cols, A.type());
CvMat _src = src, _dst = dst, _jacobian = jacobian; CvMat matA = A, matB = B, c_dABdA = _dABdA.getMat(), c_dABdB = _dABdB.getMat();
bool ok = cvRodrigues2(&_src, &_dst, &_jacobian) > 0; cvCalcMatMulDeriv(&matA, &matB, &c_dABdA, &c_dABdB);
if( !ok ) }
dst = Scalar(0);
void cv::composeRT( const InputArray& _rvec1, const InputArray& _tvec1,
const InputArray& _rvec2, const InputArray& _tvec2,
OutputArray _rvec3, OutputArray _tvec3,
OutputArray _dr3dr1, OutputArray _dr3dt1,
OutputArray _dr3dr2, OutputArray _dr3dt2,
OutputArray _dt3dr1, OutputArray _dt3dt1,
OutputArray _dt3dr2, OutputArray _dt3dt2 )
{
Mat rvec1 = _rvec1.getMat(), tvec1 = _tvec1.getMat();
Mat rvec2 = _rvec2.getMat(), tvec2 = _tvec2.getMat();
int rtype = rvec1.type();
_rvec3.create(rvec1.size(), rtype);
_tvec3.create(tvec1.size(), rtype);
Mat rvec3 = _rvec3.getMat(), tvec3 = _tvec3.getMat();
CvMat c_rvec1 = rvec1, c_tvec1 = tvec1, c_rvec2 = rvec2,
c_tvec2 = tvec2, c_rvec3 = rvec3, c_tvec3 = tvec3;
CvMat c_dr3dr1, c_dr3dt1, c_dr3dr2, c_dr3dt2, c_dt3dr1, c_dt3dt1, c_dt3dr2, c_dt3dt2;
CvMat *p_dr3dr1=0, *p_dr3dt1=0, *p_dr3dr2=0, *p_dr3dt2=0, *p_dt3dr1=0, *p_dt3dt1=0, *p_dt3dr2=0, *p_dt3dt2=0;
if( _dr3dr1.needed() )
{
_dr3dr1.create(3, 3, rtype);
p_dr3dr1 = &(c_dr3dr1 = _dr3dr1.getMat());
} }
void cv::matMulDeriv( const Mat& A, const Mat& B, Mat& dABdA, Mat& dABdB ) if( _dr3dt1.needed() )
{ {
dABdA.create(A.rows*B.cols, A.rows*A.cols, A.type()); _dr3dt1.create(3, 3, rtype);
dABdB.create(A.rows*B.cols, B.rows*B.cols, A.type()); p_dr3dt1 = &(c_dr3dt1 = _dr3dt1.getMat());
CvMat matA = A, matB = B, _dABdA = dABdA, _dABdB = dABdB;
cvCalcMatMulDeriv(&matA, &matB, &_dABdA, &_dABdB);
} }
void cv::composeRT( const Mat& rvec1, const Mat& tvec1, if( _dr3dr2.needed() )
const Mat& rvec2, const Mat& tvec2,
Mat& rvec3, Mat& tvec3 )
{ {
rvec3.create(rvec1.size(), rvec1.type()); _dr3dr2.create(3, 3, rtype);
tvec3.create(tvec1.size(), tvec1.type()); p_dr3dr2 = &(c_dr3dr2 = _dr3dr2.getMat());
CvMat _rvec1 = rvec1, _tvec1 = tvec1, _rvec2 = rvec2,
_tvec2 = tvec2, _rvec3 = rvec3, _tvec3 = tvec3;
cvComposeRT(&_rvec1, &_tvec1, &_rvec2, &_tvec2, &_rvec3, &_tvec3, 0, 0, 0, 0, 0, 0, 0, 0);
} }
if( _dr3dt2.needed() )
{
_dr3dt2.create(3, 3, rtype);
p_dr3dt2 = &(c_dr3dt2 = _dr3dt2.getMat());
}
void cv::composeRT( const Mat& rvec1, const Mat& tvec1, if( _dt3dr1.needed() )
const Mat& rvec2, const Mat& tvec2,
Mat& rvec3, Mat& tvec3,
Mat& dr3dr1, Mat& dr3dt1,
Mat& dr3dr2, Mat& dr3dt2,
Mat& dt3dr1, Mat& dt3dt1,
Mat& dt3dr2, Mat& dt3dt2 )
{ {
int rtype = rvec1.type(); _dt3dr1.create(3, 3, rtype);
rvec3.create(rvec1.size(), rtype); p_dt3dr1 = &(c_dt3dr1 = _dt3dr1.getMat());
tvec3.create(tvec1.size(), rtype); }
dr3dr1.create(3, 3, rtype); dr3dt1.create(3, 3, rtype);
dr3dr2.create(3, 3, rtype); dr3dt2.create(3, 3, rtype); if( _dt3dt1.needed() )
dt3dr1.create(3, 3, rtype); dt3dt1.create(3, 3, rtype); {
dt3dr2.create(3, 3, rtype); dt3dt2.create(3, 3, rtype); _dt3dt1.create(3, 3, rtype);
p_dt3dt1 = &(c_dt3dt1 = _dt3dt1.getMat());
CvMat _rvec1 = rvec1, _tvec1 = tvec1, _rvec2 = rvec2, }
_tvec2 = tvec2, _rvec3 = rvec3, _tvec3 = tvec3;
CvMat _dr3dr1 = dr3dr1, _dr3dt1 = dr3dt1, _dr3dr2 = dr3dr2, _dr3dt2 = dr3dt2; if( _dt3dr2.needed() )
CvMat _dt3dr1 = dt3dr1, _dt3dt1 = dt3dt1, _dt3dr2 = dt3dr2, _dt3dt2 = dt3dt2; {
cvComposeRT(&_rvec1, &_tvec1, &_rvec2, &_tvec2, &_rvec3, &_tvec3, _dt3dr2.create(3, 3, rtype);
&_dr3dr1, &_dr3dt1, &_dr3dr2, &_dr3dt2, p_dt3dr2 = &(c_dt3dr2 = _dt3dr2.getMat());
&_dt3dr1, &_dt3dt1, &_dt3dr2, &_dt3dt2); }
}
if( _dt3dt2.needed() )
{
void cv::projectPoints( const Mat& opoints, _dt3dt2.create(3, 3, rtype);
const Mat& rvec, const Mat& tvec, p_dt3dt2 = &(c_dt3dt2 = _dt3dt2.getMat());
const Mat& cameraMatrix, }
const Mat& distCoeffs,
vector<Point2f>& ipoints ) cvComposeRT(&c_rvec1, &c_tvec1, &c_rvec2, &c_tvec2, &c_rvec3, &c_tvec3,
{ p_dr3dr1, p_dr3dt1, p_dr3dr2, p_dr3dt2,
CV_Assert(opoints.isContinuous() && opoints.depth() == CV_32F && p_dt3dr1, p_dt3dt1, p_dt3dr2, p_dt3dt2);
((opoints.rows == 1 && opoints.channels() == 3) || }
opoints.cols*opoints.channels() == 3));
ipoints.resize(opoints.cols*opoints.rows*opoints.channels()/3); void cv::projectPoints( const InputArray& _opoints,
CvMat _objectPoints = opoints, _imagePoints = Mat(ipoints); const InputArray& _rvec,
CvMat _rvec = rvec, _tvec = tvec, _cameraMatrix = cameraMatrix, _distCoeffs = distCoeffs; const InputArray& _tvec,
const InputArray& _cameraMatrix,
cvProjectPoints2( &_objectPoints, &_rvec, &_tvec, &_cameraMatrix, const InputArray& _distCoeffs,
distCoeffs.data ? &_distCoeffs : 0, OutputArray _ipoints,
&_imagePoints, 0, 0, 0, 0, 0, 0 ); OutputArray _jacobian,
}
void cv::projectPoints( const Mat& opoints,
const Mat& rvec, const Mat& tvec,
const Mat& cameraMatrix,
const Mat& distCoeffs,
vector<Point2f>& ipoints,
Mat& dpdrot, Mat& dpdt, Mat& dpdf,
Mat& dpdc, Mat& dpddist,
double aspectRatio ) double aspectRatio )
{ {
CV_Assert(opoints.isContinuous() && opoints.depth() == CV_32F && Mat opoints = _opoints.getMat();
((opoints.rows == 1 && opoints.channels() == 3) || int npoints = opoints.checkVector(3), depth = opoints.depth();
opoints.cols*opoints.channels() == 3)); CV_Assert(npoints >= 0 && (depth == CV_32F || depth == CV_64F));
CvMat dpdrot, dpdt, dpdf, dpdc, dpddist;
CvMat *pdpdrot=0, *pdpdt=0, *pdpdf=0, *pdpdc=0, *pdpddist=0;
_ipoints.create(npoints, 1, CV_MAKETYPE(depth, 2), -1, true);
CvMat imagePoints = _ipoints.getMat();
CvMat objectPoints = opoints;
CvMat cameraMatrix = _cameraMatrix.getMat();
CvMat rvec = _rvec.getMat(), tvec = _tvec.getMat();
CvMat distCoeffs = _distCoeffs.getMat();
int ndistCoeffs = distCoeffs.rows + distCoeffs.cols - 1;
int npoints = opoints.cols*opoints.rows*opoints.channels()/3; if( _jacobian.needed() )
ipoints.resize(npoints); {
dpdrot.create(npoints*2, 3, CV_64F); _jacobian.create(npoints*2, 3+3+2+2+ndistCoeffs, CV_64F);
dpdt.create(npoints*2, 3, CV_64F); Mat jacobian = _jacobian.getMat();
dpdf.create(npoints*2, 2, CV_64F); pdpdrot = &(dpdrot = jacobian.colRange(0, 3));
dpdc.create(npoints*2, 2, CV_64F); pdpdt = &(dpdt = jacobian.colRange(3, 6));
dpddist.create(npoints*2, distCoeffs.rows + distCoeffs.cols - 1, CV_64F); pdpdf = &(dpdf = jacobian.colRange(6, 8));
CvMat _objectPoints = opoints, _imagePoints = Mat(ipoints); pdpdc = &(dpdc = jacobian.colRange(8, 10));
CvMat _rvec = rvec, _tvec = tvec, _cameraMatrix = cameraMatrix, _distCoeffs = distCoeffs; pdpddist = &(dpddist = jacobian.colRange(10, 10+ndistCoeffs));
CvMat _dpdrot = dpdrot, _dpdt = dpdt, _dpdf = dpdf, _dpdc = dpdc, _dpddist = dpddist; }
cvProjectPoints2( &_objectPoints, &_rvec, &_tvec, &_cameraMatrix, &_distCoeffs, cvProjectPoints2( &objectPoints, &rvec, &tvec, &cameraMatrix, &distCoeffs,
&_imagePoints, &_dpdrot, &_dpdt, &_dpdf, &_dpdc, &_dpddist, aspectRatio ); &imagePoints, pdpdrot, pdpdt, pdpdf, pdpdc, pdpddist, aspectRatio );
} }
cv::Mat cv::initCameraMatrix2D( const vector<vector<Point3f> >& objectPoints, cv::Mat cv::initCameraMatrix2D( const InputArrayOfArrays& objectPoints,
const vector<vector<Point2f> >& imagePoints, const InputArrayOfArrays& imagePoints,
Size imageSize, double aspectRatio ) Size imageSize, double aspectRatio )
{ {
Mat objPt, imgPt, npoints, cameraMatrix(3, 3, CV_64F); Mat objPt, imgPt, npoints, cameraMatrix(3, 3, CV_64F);
collectCalibrationData( objectPoints, imagePoints, vector<vector<Point2f> >(), collectCalibrationData( objectPoints, imagePoints, InputArrayOfArrays(),
objPt, imgPt, 0, npoints ); objPt, imgPt, 0, npoints );
CvMat _objPt = objPt, _imgPt = imgPt, _npoints = npoints, _cameraMatrix = cameraMatrix; CvMat _objPt = objPt, _imgPt = imgPt, _npoints = npoints, _cameraMatrix = cameraMatrix;
cvInitIntrinsicParams2D( &_objPt, &_imgPt, &_npoints, cvInitIntrinsicParams2D( &_objPt, &_imgPt, &_npoints,
@ -3290,60 +3330,73 @@ cv::Mat cv::initCameraMatrix2D( const vector<vector<Point3f> >& objectPoints,
} }
double cv::calibrateCamera( const vector<vector<Point3f> >& objectPoints, double cv::calibrateCamera( const InputArrayOfArrays& _objectPoints,
const vector<vector<Point2f> >& imagePoints, const InputArrayOfArrays& _imagePoints,
Size imageSize, Mat& cameraMatrix, Mat& distCoeffs, Size imageSize, InputOutputArray _cameraMatrix, InputOutputArray _distCoeffs,
vector<Mat>& rvecs, vector<Mat>& tvecs, int flags ) OutputArray _rvecs, OutputArray _tvecs, int flags )
{ {
int rtype = CV_64F; int rtype = CV_64F;
Mat cameraMatrix = _cameraMatrix.getMat();
cameraMatrix = prepareCameraMatrix(cameraMatrix, rtype); cameraMatrix = prepareCameraMatrix(cameraMatrix, rtype);
Mat distCoeffs = _distCoeffs.getMat();
distCoeffs = prepareDistCoeffs(distCoeffs, rtype); distCoeffs = prepareDistCoeffs(distCoeffs, rtype);
if( !(flags & CALIB_RATIONAL_MODEL) ) if( !(flags & CALIB_RATIONAL_MODEL) )
distCoeffs = distCoeffs.rows == 1 ? distCoeffs.colRange(0, 5) : distCoeffs.rowRange(0, 5); distCoeffs = distCoeffs.rows == 1 ? distCoeffs.colRange(0, 5) : distCoeffs.rowRange(0, 5);
size_t i, nimages = objectPoints.size(); size_t i, nimages = _objectPoints.total();
CV_Assert( nimages > 0 ); CV_Assert( nimages > 0 );
Mat objPt, imgPt, npoints, rvecM((int)nimages, 3, CV_64FC1), tvecM((int)nimages, 3, CV_64FC1); Mat objPt, imgPt, npoints, rvecM((int)nimages, 3, CV_64FC1), tvecM((int)nimages, 3, CV_64FC1);
collectCalibrationData( objectPoints, imagePoints, vector<vector<Point2f> >(), collectCalibrationData( _objectPoints, _imagePoints, InputArrayOfArrays(),
objPt, imgPt, 0, npoints ); objPt, imgPt, 0, npoints );
CvMat _objPt = objPt, _imgPt = imgPt, _npoints = npoints; CvMat c_objPt = objPt, c_imgPt = imgPt, c_npoints = npoints;
CvMat _cameraMatrix = cameraMatrix, _distCoeffs = distCoeffs; CvMat c_cameraMatrix = cameraMatrix, c_distCoeffs = distCoeffs;
CvMat _rvecM = rvecM, _tvecM = tvecM; CvMat c_rvecM = rvecM, c_tvecM = tvecM;
double reprojErr = cvCalibrateCamera2(&_objPt, &_imgPt, &_npoints, imageSize, double reprojErr = cvCalibrateCamera2(&c_objPt, &c_imgPt, &c_npoints, imageSize,
&_cameraMatrix, &_distCoeffs, &_rvecM, &c_cameraMatrix, &c_distCoeffs, &c_rvecM,
&_tvecM, flags ); &c_tvecM, flags );
rvecs.resize(nimages); _rvecs.create(nimages, 1, CV_64FC3);
tvecs.resize(nimages); _tvecs.create(nimages, 1, CV_64FC3);
for( i = 0; i < nimages; i++ ) for( i = 0; i < nimages; i++ )
{ {
rvecM.row((int)i).copyTo(rvecs[i]); _rvecs.create(3, 1, CV_64F, i, true);
tvecM.row((int)i).copyTo(tvecs[i]); _tvecs.create(3, 1, CV_64F, i, true);
Mat rv = _rvecs.getMat(i), tv = _tvecs.getMat(i);
memcpy(rv.data, rvecM.ptr<double>(i), 3*sizeof(double));
memcpy(tv.data, tvecM.ptr<double>(i), 3*sizeof(double));
} }
cameraMatrix.copyTo(_cameraMatrix);
distCoeffs.copyTo(_distCoeffs);
return reprojErr; return reprojErr;
} }
void cv::calibrationMatrixValues( const Mat& cameraMatrix, Size imageSize, void cv::calibrationMatrixValues( const InputArray& _cameraMatrix, Size imageSize,
double apertureWidth, double apertureHeight, double apertureWidth, double apertureHeight,
double& fovx, double& fovy, double& focalLength, double& fovx, double& fovy, double& focalLength,
Point2d& principalPoint, double& aspectRatio ) Point2d& principalPoint, double& aspectRatio )
{ {
CvMat _cameraMatrix = cameraMatrix; CvMat c_cameraMatrix = _cameraMatrix.getMat();
cvCalibrationMatrixValues( &_cameraMatrix, imageSize, apertureWidth, apertureHeight, cvCalibrationMatrixValues( &c_cameraMatrix, imageSize, apertureWidth, apertureHeight,
&fovx, &fovy, &focalLength, (CvPoint2D64f*)&principalPoint, &aspectRatio ); &fovx, &fovy, &focalLength, (CvPoint2D64f*)&principalPoint, &aspectRatio );
} }
double cv::stereoCalibrate( const vector<vector<Point3f> >& objectPoints, double cv::stereoCalibrate( const InputArrayOfArrays& _objectPoints,
const vector<vector<Point2f> >& imagePoints1, const InputArrayOfArrays& _imagePoints1,
const vector<vector<Point2f> >& imagePoints2, const InputArrayOfArrays& _imagePoints2,
Mat& cameraMatrix1, Mat& distCoeffs1, InputOutputArray _cameraMatrix1, InputOutputArray _distCoeffs1,
Mat& cameraMatrix2, Mat& distCoeffs2, InputOutputArray _cameraMatrix2, InputOutputArray _distCoeffs2,
Size imageSize, Mat& R, Mat& T, Size imageSize, OutputArray _Rmat, OutputArray _Tmat,
Mat& E, Mat& F, TermCriteria criteria, OutputArray _Emat, OutputArray _Fmat, TermCriteria criteria,
int flags ) int flags )
{ {
int rtype = CV_64F; int rtype = CV_64F;
Mat cameraMatrix1 = _cameraMatrix1.getMat();
Mat cameraMatrix2 = _cameraMatrix2.getMat();
Mat distCoeffs1 = _distCoeffs1.getMat();
Mat distCoeffs2 = _distCoeffs2.getMat();
cameraMatrix1 = prepareCameraMatrix(cameraMatrix1, rtype); cameraMatrix1 = prepareCameraMatrix(cameraMatrix1, rtype);
cameraMatrix2 = prepareCameraMatrix(cameraMatrix2, rtype); cameraMatrix2 = prepareCameraMatrix(cameraMatrix2, rtype);
distCoeffs1 = prepareDistCoeffs(distCoeffs1, rtype); distCoeffs1 = prepareDistCoeffs(distCoeffs1, rtype);
@ -3355,176 +3408,210 @@ double cv::stereoCalibrate( const vector<vector<Point3f> >& objectPoints,
distCoeffs2 = distCoeffs2.rows == 1 ? distCoeffs2.colRange(0, 5) : distCoeffs2.rowRange(0, 5); distCoeffs2 = distCoeffs2.rows == 1 ? distCoeffs2.colRange(0, 5) : distCoeffs2.rowRange(0, 5);
} }
R.create(3, 3, rtype); _Rmat.create(3, 3, rtype);
T.create(3, 1, rtype); _Tmat.create(3, 1, rtype);
E.create(3, 3, rtype);
F.create(3, 3, rtype);
Mat objPt, imgPt, imgPt2, npoints; Mat objPt, imgPt, imgPt2, npoints;
collectCalibrationData( objectPoints, imagePoints1, imagePoints2, collectCalibrationData( _objectPoints, _imagePoints1, _imagePoints2,
objPt, imgPt, &imgPt2, npoints ); objPt, imgPt, &imgPt2, npoints );
CvMat _objPt = objPt, _imgPt = imgPt, _imgPt2 = imgPt2, _npoints = npoints; CvMat c_objPt = objPt, c_imgPt = imgPt, c_imgPt2 = imgPt2, c_npoints = npoints;
CvMat _cameraMatrix1 = cameraMatrix1, _distCoeffs1 = distCoeffs1; CvMat c_cameraMatrix1 = cameraMatrix1, c_distCoeffs1 = distCoeffs1;
CvMat _cameraMatrix2 = cameraMatrix2, _distCoeffs2 = distCoeffs2; CvMat c_cameraMatrix2 = cameraMatrix2, c_distCoeffs2 = distCoeffs2;
CvMat matR = R, matT = T, matE = E, matF = F; CvMat c_matR = _Rmat.getMat(), c_matT = _Tmat.getMat(), c_matE, c_matF, *p_matE = 0, *p_matF = 0;
return cvStereoCalibrate(&_objPt, &_imgPt, &_imgPt2, &_npoints, &_cameraMatrix1, if( _Emat.needed() )
&_distCoeffs1, &_cameraMatrix2, &_distCoeffs2, imageSize, {
&matR, &matT, &matE, &matF, criteria, flags ); _Emat.create(3, 3, rtype);
p_matE = &(c_matE = _Emat.getMat());
}
if( _Fmat.needed() )
{
_Fmat.create(3, 3, rtype);
p_matF = &(c_matF = _Fmat.getMat());
} }
double err = cvStereoCalibrate(&c_objPt, &c_imgPt, &c_imgPt2, &c_npoints, &c_cameraMatrix1,
&c_distCoeffs1, &c_cameraMatrix2, &c_distCoeffs2, imageSize,
&c_matR, &c_matT, p_matE, p_matF, criteria, flags );
void cv::stereoRectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, cameraMatrix1.copyTo(_cameraMatrix1);
const Mat& cameraMatrix2, const Mat& distCoeffs2, cameraMatrix2.copyTo(_cameraMatrix2);
Size imageSize, const Mat& R, const Mat& T, distCoeffs1.copyTo(_distCoeffs1);
Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, distCoeffs2.copyTo(_distCoeffs2);
int flags )
{ return err;
int rtype = CV_64F; }
R1.create(3, 3, rtype);
R2.create(3, 3, rtype);
P1.create(3, 4, rtype); void cv::stereoRectify( const InputArray& _cameraMatrix1, const InputArray& _distCoeffs1,
P2.create(3, 4, rtype); const InputArray& _cameraMatrix2, const InputArray& _distCoeffs2,
Q.create(4, 4, rtype); Size imageSize, const InputArray& _Rmat, const InputArray& _Tmat,
CvMat _cameraMatrix1 = cameraMatrix1, _distCoeffs1 = distCoeffs1; OutputArray _Rmat1, OutputArray _Rmat2,
CvMat _cameraMatrix2 = cameraMatrix2, _distCoeffs2 = distCoeffs2; OutputArray _Pmat1, OutputArray _Pmat2,
CvMat matR = R, matT = T, _R1 = R1, _R2 = R2, _P1 = P1, _P2 = P2, matQ = Q; OutputArray _Qmat, int flags,
cvStereoRectify( &_cameraMatrix1, &_cameraMatrix2, &_distCoeffs1, &_distCoeffs2,
imageSize, &matR, &matT, &_R1, &_R2, &_P1, &_P2, &matQ, flags );
}
void cv::stereoRectify( const Mat& cameraMatrix1, const Mat& distCoeffs1,
const Mat& cameraMatrix2, const Mat& distCoeffs2,
Size imageSize, const Mat& R, const Mat& T,
Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q,
double alpha, Size newImageSize, double alpha, Size newImageSize,
Rect* validPixROI1, Rect* validPixROI2, Rect* validPixROI1, Rect* validPixROI2 )
int flags )
{ {
CvMat c_cameraMatrix1 = _cameraMatrix1.getMat();
CvMat c_cameraMatrix2 = _cameraMatrix2.getMat();
CvMat c_distCoeffs1 = _distCoeffs1.getMat();
CvMat c_distCoeffs2 = _distCoeffs2.getMat();
CvMat c_R = _Rmat.getMat(), c_T = _Tmat.getMat();
int rtype = CV_64F; int rtype = CV_64F;
R1.create(3, 3, rtype); _Rmat1.create(3, 3, rtype);
R2.create(3, 3, rtype); _Rmat2.create(3, 3, rtype);
P1.create(3, 4, rtype); _Pmat1.create(3, 4, rtype);
P2.create(3, 4, rtype); _Pmat2.create(3, 4, rtype);
Q.create(4, 4, rtype); CvMat c_R1 = _Rmat1.getMat(), c_R2 = _Rmat2.getMat(), c_P1 = _Pmat1.getMat(), c_P2 = _Pmat2.getMat();
CvMat _cameraMatrix1 = cameraMatrix1, _distCoeffs1 = distCoeffs1; CvMat c_Q, *p_Q = 0;
CvMat _cameraMatrix2 = cameraMatrix2, _distCoeffs2 = distCoeffs2;
CvMat matR = R, matT = T, _R1 = R1, _R2 = R2, _P1 = P1, _P2 = P2, matQ = Q; if( _Qmat.needed() )
cvStereoRectify( &_cameraMatrix1, &_cameraMatrix2, &_distCoeffs1, &_distCoeffs2, {
imageSize, &matR, &matT, &_R1, &_R2, &_P1, &_P2, &matQ, flags, _Qmat.create(4, 4, rtype);
alpha, newImageSize, (CvRect*)validPixROI1, (CvRect*)validPixROI2); p_Q = &(c_Q = _Qmat.getMat());
} }
bool cv::stereoRectifyUncalibrated( const Mat& points1, const Mat& points2, cvStereoRectify( &c_cameraMatrix1, &c_cameraMatrix2, &c_distCoeffs1, &c_distCoeffs2,
const Mat& F, Size imgSize, imageSize, &c_R, &c_T, &c_R1, &c_R2, &c_P1, &c_P2, p_Q, flags, alpha,
Mat& H1, Mat& H2, double threshold ) newImageSize, (CvRect*)validPixROI1, (CvRect*)validPixROI2);
}
bool cv::stereoRectifyUncalibrated( const InputArray& _points1, const InputArray& _points2,
const InputArray& _Fmat, Size imgSize,
OutputArray _Hmat1, OutputArray _Hmat2, double threshold )
{ {
int rtype = CV_64F; int rtype = CV_64F;
H1.create(3, 3, rtype); _Hmat1.create(3, 3, rtype);
H2.create(3, 3, rtype); _Hmat2.create(3, 3, rtype);
CvMat _pt1 = points1, _pt2 = points2, matF, *pF=0, _H1 = H1, _H2 = H2; Mat F = _Fmat.getMat();
CvMat c_pt1 = _points1.getMat(), c_pt2 = _points2.getMat();
CvMat c_F, *p_F=0, c_H1 = _Hmat1.getMat(), c_H2 = _Hmat2.getMat();
if( F.size() == Size(3, 3) ) if( F.size() == Size(3, 3) )
pF = &(matF = F); p_F = &(c_F = F);
return cvStereoRectifyUncalibrated(&_pt1, &_pt2, pF, imgSize, &_H1, &_H2, threshold) > 0; return cvStereoRectifyUncalibrated(&c_pt1, &c_pt2, p_F, imgSize, &c_H1, &c_H2, threshold) > 0;
} }
cv::Mat cv::getOptimalNewCameraMatrix( const Mat& cameraMatrix, const Mat& distCoeffs, cv::Mat cv::getOptimalNewCameraMatrix( const InputArray& _cameraMatrix,
const InputArray& _distCoeffs,
Size imgSize, double alpha, Size newImgSize, Size imgSize, double alpha, Size newImgSize,
Rect* validPixROI ) Rect* validPixROI )
{ {
Mat newCameraMatrix(3, 3, cameraMatrix.type()); CvMat c_cameraMatrix = _cameraMatrix.getMat(), c_distCoeffs = _distCoeffs.getMat();
CvMat _cameraMatrix = cameraMatrix,
_distCoeffs = distCoeffs, Mat newCameraMatrix(3, 3, CV_MAT_TYPE(c_cameraMatrix.type));
_newCameraMatrix = newCameraMatrix; CvMat c_newCameraMatrix = newCameraMatrix;
cvGetOptimalNewCameraMatrix(&_cameraMatrix, &_distCoeffs, imgSize,
alpha, &_newCameraMatrix, cvGetOptimalNewCameraMatrix(&c_cameraMatrix, &c_distCoeffs, imgSize,
alpha, &c_newCameraMatrix,
newImgSize, (CvRect*)validPixROI); newImgSize, (CvRect*)validPixROI);
return newCameraMatrix; return newCameraMatrix;
} }
void cv::RQDecomp3x3( const Mat& M, Mat& R, Mat& Q ) cv::Vec3d cv::RQDecomp3x3( const InputArray& _Mmat,
OutputArray _Rmat,
OutputArray _Qmat,
OutputArray _Qx,
OutputArray _Qy,
OutputArray _Qz )
{ {
R.create(3, 3, M.type()); Mat M = _Mmat.getMat();
Q.create(3, 3, M.type()); _Rmat.create(3, 3, M.type());
_Qmat.create(3, 3, M.type());
Vec3d eulerAngles;
CvMat matM = M, matR = R, matQ = Q; CvMat matM = M, matR = _Rmat.getMat(), matQ = _Qmat.getMat(), Qx, Qy, Qz, *pQx=0, *pQy=0, *pQz=0;
cvRQDecomp3x3(&matM, &matR, &matQ, 0, 0, 0, 0); if( _Qx.needed() )
{
_Qx.create(3, 3, M.type());
pQx = &(Qx = _Qx.getMat());
} }
if( _Qy.needed() )
cv::Vec3d cv::RQDecomp3x3( const Mat& M, Mat& R, Mat& Q,
Mat& Qx, Mat& Qy, Mat& Qz )
{ {
R.create(3, 3, M.type()); _Qy.create(3, 3, M.type());
Q.create(3, 3, M.type()); pQy = &(Qy = _Qy.getMat());
Vec3d eulerAngles; }
if( _Qz.needed() )
CvMat matM = M, matR = R, matQ = Q, _Qx = Qx, _Qy = Qy, _Qz = Qz; {
cvRQDecomp3x3(&matM, &matR, &matQ, &_Qx, &_Qy, &_Qz, (CvPoint3D64f*)&eulerAngles[0]); _Qz.create(3, 3, M.type());
pQz = &(Qz = _Qz.getMat());
}
cvRQDecomp3x3(&matM, &matR, &matQ, pQx, pQy, pQz, (CvPoint3D64f*)&eulerAngles[0]);
return eulerAngles; return eulerAngles;
} }
void cv::decomposeProjectionMatrix( const Mat& projMatrix, Mat& cameraMatrix, void cv::decomposeProjectionMatrix( const InputArray& _projMatrix, OutputArray _cameraMatrix,
Mat& rotMatrix, Mat& transVect ) OutputArray _rotMatrix, OutputArray _transVect,
OutputArray _rotMatrixX, OutputArray _rotMatrixY,
OutputArray _rotMatrixZ, OutputArray _eulerAngles )
{ {
Mat projMatrix = _projMatrix.getMat();
int type = projMatrix.type(); int type = projMatrix.type();
cameraMatrix.create(3, 3, type); _cameraMatrix.create(3, 3, type);
rotMatrix.create(3, 3, type); _rotMatrix.create(3, 3, type);
transVect.create(4, 1, type); _transVect.create(4, 1, type);
CvMat _projMatrix = projMatrix, _cameraMatrix = cameraMatrix; CvMat c_projMatrix = projMatrix, c_cameraMatrix = _cameraMatrix.getMat();
CvMat _rotMatrix = rotMatrix, _transVect = transVect; CvMat c_rotMatrix = _rotMatrix.getMat(), c_transVect = _transVect.getMat();
cvDecomposeProjectionMatrix(&_projMatrix, &_cameraMatrix, &_rotMatrix, CvMat c_rotMatrixX, *p_rotMatrixX = 0;
&_transVect, 0, 0, 0, 0); CvMat c_rotMatrixY, *p_rotMatrixY = 0;
} CvMat c_rotMatrixZ, *p_rotMatrixZ = 0;
CvPoint3D64f *p_eulerAngles = 0;
void cv::decomposeProjectionMatrix( const Mat& projMatrix, Mat& cameraMatrix, if( _rotMatrixX.needed() )
Mat& rotMatrix, Mat& transVect,
Mat& rotMatrixX, Mat& rotMatrixY,
Mat& rotMatrixZ, Vec3d& eulerAngles )
{ {
int type = projMatrix.type(); _rotMatrixX.create(3, 3, type);
cameraMatrix.create(3, 3, type); p_rotMatrixX = &(c_rotMatrixX = _rotMatrixX.getMat());
rotMatrix.create(3, 3, type); }
transVect.create(4, 1, type); if( _rotMatrixY.needed() )
rotMatrixX.create(3, 3, type); {
rotMatrixY.create(3, 3, type); _rotMatrixY.create(3, 3, type);
rotMatrixZ.create(3, 3, type); p_rotMatrixY = &(c_rotMatrixY = _rotMatrixY.getMat());
CvMat _projMatrix = projMatrix, _cameraMatrix = cameraMatrix; }
CvMat _rotMatrix = rotMatrix, _transVect = transVect; if( _rotMatrixZ.needed() )
CvMat _rotMatrixX = rotMatrixX, _rotMatrixY = rotMatrixY; {
CvMat _rotMatrixZ = rotMatrixZ; _rotMatrixZ.create(3, 3, type);
cvDecomposeProjectionMatrix(&_projMatrix, &_cameraMatrix, &_rotMatrix, p_rotMatrixZ = &(c_rotMatrixZ = _rotMatrixZ.getMat());
&_transVect, &_rotMatrixX, &_rotMatrixY, }
&_rotMatrixZ, (CvPoint3D64f*)&eulerAngles[0]); if( _eulerAngles.needed() )
{
_eulerAngles.create(3, 1, CV_64F, -1, true);
p_eulerAngles = (CvPoint3D64f*)_eulerAngles.getMat().data;
}
cvDecomposeProjectionMatrix(&c_projMatrix, &c_cameraMatrix, &c_rotMatrix,
&c_transVect, p_rotMatrixX, p_rotMatrixY,
p_rotMatrixZ, p_eulerAngles);
} }
namespace cv namespace cv
{ {
static void adjust3rdMatrix(const vector<vector<Point2f> >& imgpt1_0, static void adjust3rdMatrix(const InputArrayOfArrays& _imgpt1_0,
const vector<vector<Point2f> >& imgpt3_0, const InputArrayOfArrays& _imgpt3_0,
const Mat& cameraMatrix1, const Mat& distCoeffs1, const Mat& cameraMatrix1, const Mat& distCoeffs1,
const Mat& cameraMatrix3, const Mat& distCoeffs3, const Mat& cameraMatrix3, const Mat& distCoeffs3,
const Mat& R1, const Mat& R3, const Mat& P1, Mat& P3 ) const Mat& R1, const Mat& R3, const Mat& P1, Mat& P3 )
{ {
size_t n1 = _imgpt1_0.total(), n3 = _imgpt3_0.total();
vector<Point2f> imgpt1, imgpt3; vector<Point2f> imgpt1, imgpt3;
for( int i = 0; i < (int)std::min(imgpt1_0.size(), imgpt3_0.size()); i++ ) for( int i = 0; i < (int)std::min(n1, n3); i++ )
{
if( !imgpt1_0[i].empty() && !imgpt3_0[i].empty() )
{ {
std::copy(imgpt1_0[i].begin(), imgpt1_0[i].end(), std::back_inserter(imgpt1)); Mat pt1 = _imgpt1_0.getMat(i), pt3 = _imgpt3_0.getMat(i);
std::copy(imgpt3_0[i].begin(), imgpt3_0[i].end(), std::back_inserter(imgpt3)); int ni1 = pt1.checkVector(2, CV_32F), ni3 = pt3.checkVector(2, CV_32F);
} CV_Assert( ni1 > 0 && ni1 == ni3 );
const Point2f* pt1data = pt1.ptr<Point2f>();
const Point2f* pt3data = pt3.ptr<Point2f>();
std::copy(pt1data, pt1data + ni1, std::back_inserter(imgpt1));
std::copy(pt3data, pt3data + ni3, std::back_inserter(imgpt3));
} }
undistortPoints(Mat(imgpt1), imgpt1, cameraMatrix1, distCoeffs1, R1, P1); undistortPoints(imgpt1, imgpt1, cameraMatrix1, distCoeffs1, R1, P1);
undistortPoints(Mat(imgpt3), imgpt3, cameraMatrix3, distCoeffs3, R3, P3); undistortPoints(imgpt3, imgpt3, cameraMatrix3, distCoeffs3, R3, P3);
double y1_ = 0, y2_ = 0, y1y1_ = 0, y1y2_ = 0; double y1_ = 0, y2_ = 0, y1y1_ = 0, y1y2_ = 0;
size_t n = imgpt1.size(); size_t n = imgpt1.size();
@ -3555,20 +3642,31 @@ static void adjust3rdMatrix(const vector<vector<Point2f> >& imgpt1_0,
} }
float cv::rectify3Collinear( const Mat& cameraMatrix1, const Mat& distCoeffs1, float cv::rectify3Collinear( const InputArray& _cameraMatrix1, const InputArray& _distCoeffs1,
const Mat& cameraMatrix2, const Mat& distCoeffs2, const InputArray& _cameraMatrix2, const InputArray& _distCoeffs2,
const Mat& cameraMatrix3, const Mat& distCoeffs3, const InputArray& _cameraMatrix3, const InputArray& _distCoeffs3,
const vector<vector<Point2f> >& imgpt1, const InputArrayOfArrays& _imgpt1,
const vector<vector<Point2f> >& imgpt3, const InputArrayOfArrays& _imgpt3,
Size imageSize, const Mat& R12, const Mat& T12, const Mat& R13, const Mat& T13, Size imageSize, const InputArray& _Rmat12, const InputArray& _Tmat12,
Mat& R1, Mat& R2, Mat& R3, Mat& P1, Mat& P2, Mat& P3, Mat& Q, const InputArray& _Rmat13, const InputArray& _Tmat13,
OutputArray _Rmat1, OutputArray _Rmat2, OutputArray _Rmat3,
OutputArray _Pmat1, OutputArray _Pmat2, OutputArray _Pmat3,
OutputArray _Qmat,
double alpha, Size /*newImgSize*/, double alpha, Size /*newImgSize*/,
Rect* roi1, Rect* roi2, int flags ) Rect* roi1, Rect* roi2, int flags )
{ {
// first, rectify the 1-2 stereo pair // first, rectify the 1-2 stereo pair
stereoRectify( cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, stereoRectify( _cameraMatrix1, _distCoeffs1, _cameraMatrix2, _distCoeffs2,
imageSize, R12, T12, R1, R2, P1, P2, Q, imageSize, _Rmat12, _Tmat12, _Rmat1, _Rmat2, _Pmat1, _Pmat2, _Qmat,
alpha, imageSize, roi1, roi2, flags ); flags, alpha, imageSize, roi1, roi2 );
Mat R12 = _Rmat12.getMat(), R13 = _Rmat13.getMat(), T12 = _Tmat12.getMat(), T13 = _Tmat13.getMat();
_Rmat3.create(3, 3, CV_64F);
_Pmat3.create(3, 4, CV_64F);
Mat P1 = _Pmat1.getMat(), P2 = _Pmat2.getMat();
Mat R3 = _Rmat3.getMat(), P3 = _Pmat3.getMat();
// recompute rectification transforms for cameras 1 & 2. // recompute rectification transforms for cameras 1 & 2.
Mat om, r_r, r_r13; Mat om, r_r, r_r13;
@ -3608,8 +3706,9 @@ float cv::rectify3Collinear( const Mat& cameraMatrix1, const Mat& distCoeffs1,
P3.at<double>(0,3) *= P3.at<double>(0,0); P3.at<double>(0,3) *= P3.at<double>(0,0);
P3.at<double>(1,3) *= P3.at<double>(1,1); P3.at<double>(1,3) *= P3.at<double>(1,1);
if( !imgpt1.empty() && imgpt3.empty() ) if( !_imgpt1.empty() && _imgpt3.empty() )
adjust3rdMatrix(imgpt1, imgpt3, cameraMatrix1, distCoeffs1, cameraMatrix3, distCoeffs3, R1, R3, P1, P3); adjust3rdMatrix(_imgpt1, _imgpt3, _cameraMatrix1.getMat(), _distCoeffs1.getMat(),
_cameraMatrix3.getMat(), _distCoeffs3.getMat(), _Rmat1.getMat(), R3, P1, P3);
return (float)((P3.at<double>(idx,3)/P3.at<double>(idx,idx))/ return (float)((P3.at<double>(idx,3)/P3.at<double>(idx,idx))/
(P2.at<double>(idx,3)/P2.at<double>(idx,idx))); (P2.at<double>(idx,3)/P2.at<double>(idx,idx)));

@ -280,9 +280,9 @@ void CirclesGridClusterFinder::rectifyPatternPoints(const cv::Size &patternSize,
Mat homography = findHomography(Mat(sortedCorners), Mat(idealPoints), 0); Mat homography = findHomography(Mat(sortedCorners), Mat(idealPoints), 0);
Mat rectifiedPointsMat; Mat rectifiedPointsMat;
transform(Mat(patternPoints), rectifiedPointsMat, homography); transform(patternPoints, rectifiedPointsMat, homography);
rectifiedPatternPoints.clear(); rectifiedPatternPoints.clear();
convertPointsHomogeneous(rectifiedPointsMat, rectifiedPatternPoints); convertPointsFromHomogeneous(rectifiedPointsMat, rectifiedPatternPoints);
} }
void CirclesGridClusterFinder::parsePatternPoints(const cv::Size &patternSize, const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &rectifiedPatternPoints, std::vector<cv::Point2f> &centers) void CirclesGridClusterFinder::parsePatternPoints(const cv::Size &patternSize, const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &rectifiedPatternPoints, std::vector<cv::Point2f> &centers)
@ -727,7 +727,7 @@ Mat CirclesGridFinder::rectifyGrid(Size detectedGridSize, const vector<Point2f>&
Mat dstKeypointsMat; Mat dstKeypointsMat;
transform(Mat(srcKeypoints), dstKeypointsMat, H); transform(Mat(srcKeypoints), dstKeypointsMat, H);
vector<Point2f> dstKeypoints; vector<Point2f> dstKeypoints;
convertPointsHomogeneous(dstKeypointsMat, dstKeypoints); convertPointsFromHomogeneous(dstKeypointsMat, dstKeypoints);
warpedKeypoints.clear(); warpedKeypoints.clear();
for (size_t i = 0; i < dstKeypoints.size(); i++) for (size_t i = 0; i < dstKeypoints.size(); i++)
@ -969,7 +969,7 @@ void CirclesGridFinder::findBasis(const vector<Point2f> &samples, vector<Point2f
Mat centers; Mat centers;
const int clustersCount = 4; const int clustersCount = 4;
kmeans(Mat(samples).reshape(1, 0), clustersCount, bestLabels, termCriteria, parameters.kmeansAttempts, kmeans(Mat(samples).reshape(1, 0), clustersCount, bestLabels, termCriteria, parameters.kmeansAttempts,
KMEANS_RANDOM_CENTERS, &centers); KMEANS_RANDOM_CENTERS, centers);
assert( centers.type() == CV_32FC1 ); assert( centers.type() == CV_32FC1 );
vector<int> basisIndices; vector<int> basisIndices;

@ -1044,114 +1044,95 @@ CV_IMPL void cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst )
} }
} }
namespace cv cv::Mat cv::findHomography( const InputArray& _points1, const InputArray& _points2,
int method, double ransacReprojThreshold, OutputArray _mask )
{ {
Mat points1 = _points1.getMat(), points2 = _points2.getMat();
static Mat _findHomography( const Mat& points1, const Mat& points2, int npoints = points1.checkVector(2);
int method, double ransacReprojThreshold, CV_Assert( npoints >= 0 && points2.checkVector(2) == npoints &&
vector<uchar>* mask ) points1.type() == points2.type());
{
CV_Assert(points1.isContinuous() && points2.isContinuous() &&
points1.type() == points2.type() &&
((points1.rows == 1 && points1.channels() == 2) ||
points1.cols*points1.channels() == 2) &&
((points2.rows == 1 && points2.channels() == 2) ||
points2.cols*points2.channels() == 2));
Mat H(3, 3, CV_64F); Mat H(3, 3, CV_64F);
CvMat _pt1 = Mat(points1), _pt2 = Mat(points2); CvMat _pt1 = points1, _pt2 = points2;
CvMat matH = H, _mask, *pmask = 0; CvMat matH = H, c_mask, *p_mask = 0;
if( mask ) if( _mask.needed() )
{ {
mask->resize(points1.cols*points1.rows*points1.channels()/2); _mask.create(npoints, 1, CV_8U, -1, true);
pmask = &(_mask = cvMat(1, (int)mask->size(), CV_8U, (void*)&(*mask)[0])); p_mask = &(c_mask = _mask.getMat());
} }
bool ok = cvFindHomography( &_pt1, &_pt2, &matH, method, ransacReprojThreshold, pmask ) > 0; bool ok = cvFindHomography( &_pt1, &_pt2, &matH, method, ransacReprojThreshold, p_mask ) > 0;
if( !ok ) if( !ok )
H = Scalar(0); H = Scalar(0);
return H; return H;
} }
static Mat _findFundamentalMat( const Mat& points1, const Mat& points2, cv::Mat cv::findFundamentalMat( const InputArray& _points1, const InputArray& _points2,
int method, double param1, double param2, int method, double param1, double param2,
vector<uchar>* mask ) OutputArray _mask )
{ {
CV_Assert(points1.checkVector(2) >= 0 && points2.checkVector(2) >= 0 && Mat points1 = _points1.getMat(), points2 = _points2.getMat();
(points1.depth() == CV_32F || points1.depth() == CV_32S) && int npoints = points1.checkVector(2);
points1.depth() == points2.depth()); CV_Assert( npoints >= 0 && points2.checkVector(2) == npoints &&
points1.type() == points2.type());
Mat F(3, 3, CV_64F); Mat F(3, 3, CV_64F);
CvMat _pt1 = Mat(points1), _pt2 = Mat(points2); CvMat _pt1 = points1, _pt2 = points2;
CvMat matF = F, _mask, *pmask = 0; CvMat matF = F, c_mask, *p_mask = 0;
if( mask ) if( _mask.needed() )
{ {
mask->resize(points1.cols*points1.rows*points1.channels()/2); _mask.create(npoints, 1, CV_8U, -1, true);
pmask = &(_mask = cvMat(1, (int)mask->size(), CV_8U, (void*)&(*mask)[0])); p_mask = &(c_mask = _mask.getMat());
} }
int n = cvFindFundamentalMat( &_pt1, &_pt2, &matF, method, param1, param2, pmask ); int n = cvFindFundamentalMat( &_pt1, &_pt2, &matF, method, param1, param2, p_mask );
if( n <= 0 ) if( n <= 0 )
F = Scalar(0); F = Scalar(0);
return F; return F;
} }
} void cv::computeCorrespondEpilines( const InputArray& _points, int whichImage,
const InputArray& _Fmat, OutputArray _lines )
cv::Mat cv::findHomography( const Mat& srcPoints, const Mat& dstPoints,
vector<uchar>& mask, int method,
double ransacReprojThreshold )
{ {
return _findHomography(srcPoints, dstPoints, method, ransacReprojThreshold, &mask); Mat points = _points.getMat();
} int npoints = points.checkVector(2);
CV_Assert( npoints >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S));
cv::Mat cv::findHomography( const Mat& srcPoints, const Mat& dstPoints, _lines.create(npoints, 1, CV_32FC3, -1, true);
int method, double ransacReprojThreshold ) CvMat c_points = points, c_lines = _lines.getMat(), c_F = _Fmat.getMat();
{ cvComputeCorrespondEpilines(&c_points, whichImage, &c_F, &c_lines);
return _findHomography(srcPoints, dstPoints, method, ransacReprojThreshold, 0);
} }
void cv::convertPointsFromHomogeneous( const InputArray& _src, OutputArray _dst )
cv::Mat cv::findFundamentalMat( const Mat& points1, const Mat& points2,
vector<uchar>& mask, int method, double param1, double param2 )
{ {
return _findFundamentalMat( points1, points2, method, param1, param2, &mask ); Mat src = _src.getMat();
} int npoints = src.checkVector(3), cn = 3;
if( npoints < 0 )
cv::Mat cv::findFundamentalMat( const Mat& points1, const Mat& points2,
int method, double param1, double param2 )
{ {
return _findFundamentalMat( points1, points2, method, param1, param2, 0 ); npoints = src.checkVector(4);
if( npoints >= 0 )
cn = 4;
} }
CV_Assert( npoints >= 0 && (src.depth() == CV_32F || src.depth() == CV_32S));
void cv::computeCorrespondEpilines( const Mat& points, int whichImage, _dst.create(npoints, 1, CV_MAKETYPE(CV_32F, cn-1));
const Mat& F, vector<Vec3f>& lines ) CvMat c_src = src, c_dst = _dst.getMat();
{ cvConvertPointsHomogeneous(&c_src, &c_dst);
CV_Assert(points.checkVector(2) >= 0 &&
(points.depth() == CV_32F || points.depth() == CV_32S));
lines.resize(points.cols*points.rows*points.channels()/2);
CvMat _points = points, _lines = Mat(lines), matF = F;
cvComputeCorrespondEpilines(&_points, whichImage, &matF, &_lines);
} }
void cv::convertPointsHomogeneous( const Mat& src, vector<Point3f>& dst ) void cv::convertPointsToHomogeneous( const InputArray& _src, OutputArray _dst )
{ {
int srccn = src.checkVector(2) >= 0 ? 2 : src.checkVector(4) >= 0 ? 4 : -1; Mat src = _src.getMat();
CV_Assert( srccn > 0 && (src.depth() == CV_32F || src.depth() == CV_32S)); int npoints = src.checkVector(2), cn = 2;
if( npoints < 0 )
dst.resize(src.cols*src.rows*src.channels()/srccn);
CvMat _src = src, _dst = Mat(dst);
cvConvertPointsHomogeneous(&_src, &_dst);
}
void cv::convertPointsHomogeneous( const Mat& src, vector<Point2f>& dst )
{ {
CV_Assert(src.checkVector(3) >= 0 && npoints = src.checkVector(3);
(src.depth() == CV_32F || src.depth() == CV_32S)); if( npoints >= 0 )
cn = 3;
}
CV_Assert( npoints >= 0 && (src.depth() == CV_32F || src.depth() == CV_32S));
dst.resize(src.cols*src.rows*src.channels()/3); _dst.create(npoints, 1, CV_MAKETYPE(CV_32F, cn+1));
CvMat _src = Mat(src), _dst = Mat(dst); CvMat c_src = src, c_dst = _dst.getMat();
cvConvertPointsHomogeneous(&_src, &_dst); cvConvertPointsHomogeneous(&c_src, &c_dst);
} }
/* End of file. */ /* End of file. */

@ -452,30 +452,30 @@ bool cv::Affine3DEstimator::checkSubset( const CvMat* ms1, int count )
return j == i; return j == i;
} }
int cv::estimateAffine3D(const Mat& from, const Mat& to, Mat& out, vector<uchar>& outliers, double param1, double param2) int cv::estimateAffine3D(const InputArray& _from, const InputArray& _to,
OutputArray _out, OutputArray _outliers,
double param1, double param2)
{ {
int count = from.cols*from.rows*from.channels()/3; Mat from = _from.getMat(), to = _to.getMat();
int count = from.checkVector(3, CV_32F);
CV_Assert( count >= 4 && from.isContinuous() && to.isContinuous() && CV_Assert( count >= 0 && to.checkVector(3, CV_32F) == count );
from.depth() == CV_32F && to.depth() == CV_32F &&
((from.rows == 1 && from.channels() == 3) || from.cols*from.channels() == 3) &&
((to.rows == 1 && to.channels() == 3) || to.cols*to.channels() == 3) &&
count == to.cols*to.rows*to.channels()/3);
out.create(3, 4, CV_64F); _out.create(3, 4, CV_64F);
outliers.resize(count); Mat out = _out.getMat();
fill(outliers.begin(), outliers.end(), (uchar)1);
vector<Point3d> dFrom; _outliers.create(count, 1, CV_8U, -1, true);
vector<Point3d> dTo; Mat outliers = _outliers.getMat();
outliers = Scalar::all(1);
copy(from.ptr<Point3f>(), from.ptr<Point3f>() + count, back_inserter(dFrom)); Mat dFrom, dTo;
copy(to.ptr<Point3f>(), to.ptr<Point3f>() + count, back_inserter(dTo)); from.convertTo(dFrom, CV_64F);
to.convertTo(dTo, CV_64F);
CvMat F3x4 = out; CvMat F3x4 = out;
CvMat mask = cvMat( 1, count, CV_8U, &outliers[0] ); CvMat mask = outliers;
CvMat m1 = cvMat( 1, count, CV_64FC3, &dFrom[0] ); CvMat m1 = dFrom;
CvMat m2 = cvMat( 1, count, CV_64FC3, &dTo[0] ); CvMat m2 = dTo;
const double epsilon = numeric_limits<double>::epsilon(); const double epsilon = numeric_limits<double>::epsilon();
param1 = param1 <= 0 ? 3 : param1; param1 = param1 <= 0 ? 3 : param1;

@ -224,8 +224,14 @@ int segment_hist_max(const Mat& hist, int& low_thresh, int& high_thresh)
} }
} }
bool find4QuadCornerSubpix(const Mat& img, std::vector<Point2f>& corners, Size region_size) }
bool cv::find4QuadCornerSubpix(const InputArray& _img, InputOutputArray _corners, Size region_size)
{ {
Mat img = _img.getMat(), cornersM = _corners.getMat();
int ncorners = cornersM.checkVector(2, CV_32F);
CV_Assert( ncorners >= 0 );
Point2f* corners = cornersM.ptr<Point2f>();
const int nbins = 256; const int nbins = 256;
float ranges[] = {0, 256}; float ranges[] = {0, 256};
const float* _ranges = ranges; const float* _ranges = ranges;
@ -238,7 +244,7 @@ bool find4QuadCornerSubpix(const Mat& img, std::vector<Point2f>& corners, Size r
Mat black_comp, white_comp; Mat black_comp, white_comp;
for(size_t i = 0; i < corners.size(); i++) for(int i = 0; i < ncorners; i++)
{ {
int channels = 0; int channels = 0;
Rect roi(cvRound(corners[i].x - region_size.width), cvRound(corners[i].y - region_size.height), Rect roi(cvRound(corners[i].x - region_size.width), cvRound(corners[i].y - region_size.height),
@ -362,5 +368,3 @@ bool find4QuadCornerSubpix(const Mat& img, std::vector<Point2f>& corners, Size r
return true; return true;
} }
}; // namespace std

@ -43,25 +43,22 @@
#include "precomp.hpp" #include "precomp.hpp"
using namespace cv; using namespace cv;
void cv::solvePnP( const Mat& opoints, const Mat& ipoints, void cv::solvePnP( const InputArray& _opoints, const InputArray& _ipoints,
const Mat& cameraMatrix, const Mat& distCoeffs, const InputArray& _cameraMatrix, const InputArray& _distCoeffs,
Mat& rvec, Mat& tvec, bool useExtrinsicGuess ) OutputArray _rvec, OutputArray _tvec, bool useExtrinsicGuess )
{ {
CV_Assert(opoints.isContinuous() && opoints.depth() == CV_32F && Mat opoints = _opoints.getMat(), ipoints = _ipoints.getMat();
((opoints.rows == 1 && opoints.channels() == 3) || int npoints = opoints.checkVector(3, CV_32F);
opoints.cols*opoints.channels() == 3) && CV_Assert( npoints >= 0 && npoints == ipoints.checkVector(2, CV_32F) );
ipoints.isContinuous() && ipoints.depth() == CV_32F &&
((ipoints.rows == 1 && ipoints.channels() == 2) || _rvec.create(3, 1, CV_64F);
ipoints.cols*ipoints.channels() == 2)); _tvec.create(3, 1, CV_64F);
CvMat c_objectPoints = opoints, c_imagePoints = ipoints;
rvec.create(3, 1, CV_64F); CvMat c_cameraMatrix = _cameraMatrix.getMat(), c_distCoeffs = _distCoeffs.getMat();
tvec.create(3, 1, CV_64F); CvMat c_rvec = _rvec.getMat(), c_tvec = _tvec.getMat();
CvMat _objectPoints = opoints, _imagePoints = ipoints; cvFindExtrinsicCameraParams2(&c_objectPoints, &c_imagePoints, &c_cameraMatrix,
CvMat _cameraMatrix = cameraMatrix, _distCoeffs = distCoeffs; c_distCoeffs.rows*c_distCoeffs.cols ? &c_distCoeffs : 0,
CvMat _rvec = rvec, _tvec = tvec; &c_rvec, &c_tvec, useExtrinsicGuess );
cvFindExtrinsicCameraParams2(&_objectPoints, &_imagePoints, &_cameraMatrix,
distCoeffs.data ? &_distCoeffs : 0,
&_rvec, &_tvec, useExtrinsicGuess );
} }
namespace cv namespace cv
@ -172,7 +169,7 @@ namespace cv
project3dPoints(objectPoints, localRvec, localTvec, rotatedPoints); project3dPoints(objectPoints, localRvec, localTvec, rotatedPoints);
vector<int> localInliers; vector<int> localInliers;
for (size_t i = 0; i < objectPoints.cols; i++) for (int i = 0; i < objectPoints.cols; i++)
{ {
Point2f p(imagePoints.at<Vec2f>(0, i)[0], imagePoints.at<Vec2f>(0, i)[1]); Point2f p(imagePoints.at<Vec2f>(0, i)[0], imagePoints.at<Vec2f>(0, i)[1]);
if ((norm(p - projected_points[i]) < params.reprojectionError) if ((norm(p - projected_points[i]) < params.reprojectionError)
@ -203,7 +200,7 @@ namespace cv
{ {
vector<char> pointsMask(objectPoints.cols, 0); vector<char> pointsMask(objectPoints.cols, 0);
memset(&pointsMask[0], 1, MIN_POINTS_COUNT ); memset(&pointsMask[0], 1, MIN_POINTS_COUNT );
for( size_t i=r.begin(); i!=r.end(); ++i ) for( int i=r.begin(); i!=r.end(); ++i )
{ {
generateVar(pointsMask); generateVar(pointsMask);
pnpTask(pointsMask, objectPoints, imagePoints, parameters, pnpTask(pointsMask, objectPoints, imagePoints, parameters,
@ -230,8 +227,8 @@ namespace cv
const Mat& objectPoints; const Mat& objectPoints;
const Mat& imagePoints; const Mat& imagePoints;
const Parameters& parameters; const Parameters& parameters;
vector<int>& inliers;
Mat &rvec, &tvec; Mat &rvec, &tvec;
vector<int>& inliers;
Mat initRvec, initTvec; Mat initRvec, initTvec;
static RNG generator; static RNG generator;
@ -257,10 +254,14 @@ namespace cv
} }
} }
void cv::solvePnPRansac(const Mat& opoints, const Mat& ipoints, void cv::solvePnPRansac(const InputArray& _opoints, const InputArray& _ipoints,
const Mat& cameraMatrix, const Mat& distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess, const InputArray& _cameraMatrix, const InputArray& _distCoeffs,
int iterationsCount, float reprojectionError, int minInliersCount, vector<int>* inliers) OutputArray _rvec, OutputArray _tvec, bool useExtrinsicGuess,
int iterationsCount, float reprojectionError, int minInliersCount,
OutputArray _inliers)
{ {
Mat opoints = _opoints.getMat(), ipoints = _ipoints.getMat();
Mat cameraMatrix = _cameraMatrix.getMat(), distCoeffs = _distCoeffs.getMat();
CV_Assert(opoints.isContinuous()); CV_Assert(opoints.isContinuous());
CV_Assert(opoints.depth() == CV_32F); CV_Assert(opoints.depth() == CV_32F);
@ -269,8 +270,10 @@ void cv::solvePnPRansac(const Mat& opoints, const Mat& ipoints,
CV_Assert(ipoints.depth() == CV_32F); CV_Assert(ipoints.depth() == CV_32F);
CV_Assert((ipoints.rows == 1 && ipoints.channels() == 2) || ipoints.cols*ipoints.channels() == 2); CV_Assert((ipoints.rows == 1 && ipoints.channels() == 2) || ipoints.cols*ipoints.channels() == 2);
rvec.create(3, 1, CV_64FC1); _rvec.create(3, 1, CV_64FC1);
tvec.create(3, 1, CV_64FC1); _tvec.create(3, 1, CV_64FC1);
Mat rvec = _rvec.getMat();
Mat tvec = _tvec.getMat();
Mat objectPoints = opoints.reshape(3, 1), imagePoints = ipoints.reshape(2, 1); Mat objectPoints = opoints.reshape(3, 1), imagePoints = ipoints.reshape(2, 1);
@ -294,7 +297,7 @@ void cv::solvePnPRansac(const Mat& opoints, const Mat& ipoints,
localRvec, localTvec, localInliers)); localRvec, localTvec, localInliers));
} }
if (localInliers.size() >= pnpransac::MIN_POINTS_COUNT) if (localInliers.size() >= (size_t)pnpransac::MIN_POINTS_COUNT)
{ {
size_t pointsCount = localInliers.size(); size_t pointsCount = localInliers.size();
Mat inlierObjectPoints(1, pointsCount, CV_32FC3), inlierImagePoints(1, pointsCount, CV_32FC2); Mat inlierObjectPoints(1, pointsCount, CV_32FC3), inlierImagePoints(1, pointsCount, CV_32FC2);
@ -310,14 +313,16 @@ void cv::solvePnPRansac(const Mat& opoints, const Mat& ipoints,
solvePnP(inlierObjectPoints, inlierImagePoints, params.camera.intrinsics, params.camera.distortion, localRvec, localTvec, true); solvePnP(inlierObjectPoints, inlierImagePoints, params.camera.intrinsics, params.camera.distortion, localRvec, localTvec, true);
localRvec.copyTo(rvec); localRvec.copyTo(rvec);
localTvec.copyTo(tvec); localTvec.copyTo(tvec);
if (inliers) if (_inliers.needed())
*inliers = localInliers; Mat(localInliers).copyTo(_inliers);
} }
else else
{ {
tvec.setTo(Scalar(0)); tvec.setTo(Scalar(0));
Mat R = Mat::ones(3, 3, CV_64F); Mat R = Mat::eye(3, 3, CV_64F);
Rodrigues(R, rvec); Rodrigues(R, rvec);
if( _inliers.needed() )
_inliers.release();
} }
return; return;
} }

@ -920,10 +920,13 @@ void StereoBM::init(int _preset, int _ndisparities, int _SADWindowSize)
state->SADWindowSize = _SADWindowSize; state->SADWindowSize = _SADWindowSize;
} }
void StereoBM::operator()( const Mat& left, const Mat& right, Mat& disparity, int disptype ) void StereoBM::operator()( const InputArray& _left, const InputArray& _right,
OutputArray _disparity, int disptype )
{ {
Mat left = _left.getMat(), right = _right.getMat();
CV_Assert( disptype == CV_16S || disptype == CV_32F ); CV_Assert( disptype == CV_16S || disptype == CV_32F );
disparity.create(left.size(), disptype); _disparity.create(left.size(), disptype);
Mat disparity = _disparity.getMat();
findStereoCorrespondenceBM(left, right, disparity, state); findStereoCorrespondenceBM(left, right, disparity, state);
} }

@ -819,8 +819,49 @@ static void computeDisparitySGBM( const Mat& img1, const Mat& img2,
typedef cv::Point_<short> Point2s; typedef cv::Point_<short> Point2s;
void filterSpeckles( Mat& img, double _newval, int maxSpeckleSize, double _maxDiff, Mat& _buf ) void StereoSGBM::operator ()( const InputArray& _left, const InputArray& _right,
OutputArray _disp )
{ {
Mat left = _left.getMat(), right = _right.getMat();
CV_Assert( left.size() == right.size() && left.type() == right.type() &&
left.depth() == DataType<PixType>::depth );
_disp.create( left.size(), CV_16S );
Mat disp = _disp.getMat();
computeDisparitySGBM( left, right, disp, *this, buffer );
medianBlur(disp, disp, 3);
if( speckleWindowSize > 0 )
filterSpeckles(disp, (minDisparity - 1)*DISP_SCALE, speckleWindowSize, DISP_SCALE*speckleRange, buffer);
}
Rect getValidDisparityROI( Rect roi1, Rect roi2,
int minDisparity,
int numberOfDisparities,
int SADWindowSize )
{
int SW2 = SADWindowSize/2;
int minD = minDisparity, maxD = minDisparity + numberOfDisparities - 1;
int xmin = max(roi1.x, roi2.x + maxD) + SW2;
int xmax = min(roi1.x + roi1.width, roi2.x + roi2.width - minD) - SW2;
int ymin = max(roi1.y, roi2.y) + SW2;
int ymax = min(roi1.y + roi1.height, roi2.y + roi2.height) - SW2;
Rect r(xmin, ymin, xmax - xmin, ymax - ymin);
return r.width > 0 && r.height > 0 ? r : Rect();
}
}
void cv::filterSpeckles( InputOutputArray _img, double _newval, int maxSpeckleSize,
double _maxDiff, InputOutputArray __buf )
{
Mat img = _img.getMat();
Mat temp, &_buf = __buf.needed() ? __buf.getMatRef() : temp;
CV_Assert( img.type() == CV_16SC1 ); CV_Assert( img.type() == CV_16SC1 );
int newVal = cvRound(_newval); int newVal = cvRound(_newval);
@ -917,43 +958,10 @@ void filterSpeckles( Mat& img, double _newval, int maxSpeckleSize, double _maxDi
} }
} }
void cv::validateDisparity( InputOutputArray _disp, const InputArray& _cost, int minDisparity,
void StereoSGBM::operator ()( const Mat& left, const Mat& right, Mat& disp ) int numberOfDisparities, int disp12MaxDiff )
{
CV_Assert( left.size() == right.size() && left.type() == right.type() &&
left.depth() == DataType<PixType>::depth );
disp.create( left.size(), CV_16S );
computeDisparitySGBM( left, right, disp, *this, buffer );
medianBlur(disp, disp, 3);
if( speckleWindowSize > 0 )
filterSpeckles(disp, (minDisparity - 1)*DISP_SCALE, speckleWindowSize, DISP_SCALE*speckleRange, buffer);
}
Rect getValidDisparityROI( Rect roi1, Rect roi2,
int minDisparity,
int numberOfDisparities,
int SADWindowSize )
{
int SW2 = SADWindowSize/2;
int minD = minDisparity, maxD = minDisparity + numberOfDisparities - 1;
int xmin = max(roi1.x, roi2.x + maxD) + SW2;
int xmax = min(roi1.x + roi1.width, roi2.x + roi2.width - minD) - SW2;
int ymin = max(roi1.y, roi2.y) + SW2;
int ymax = min(roi1.y + roi1.height, roi2.y + roi2.height) - SW2;
Rect r(xmin, ymin, xmax - xmin, ymax - ymin);
return r.width > 0 && r.height > 0 ? r : Rect();
}
void validateDisparity( Mat& disp, const Mat& cost, int minDisparity, int numberOfDisparities, int disp12MaxDiff )
{ {
Mat disp = _disp.getMat(), cost = _cost.getMat();
int cols = disp.cols, rows = disp.rows; int cols = disp.cols, rows = disp.rows;
int minD = minDisparity, maxD = minDisparity + numberOfDisparities; int minD = minDisparity, maxD = minDisparity + numberOfDisparities;
int x, minX1 = max(maxD, 0), maxX1 = cols + min(minD, 0); int x, minX1 = max(maxD, 0), maxX1 = cols + min(minD, 0);
@ -1031,8 +1039,6 @@ void validateDisparity( Mat& disp, const Mat& cost, int minDisparity, int number
} }
} }
}
CvRect cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity, CvRect cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity,
int numberOfDisparities, int SADWindowSize ) int numberOfDisparities, int SADWindowSize )
{ {

@ -1244,8 +1244,13 @@ void CV_ProjectPointsTest_CPP::project( const Mat& objectPoints, const Mat& rvec
const Mat& cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints, const Mat& cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints,
Mat& dpdrot, Mat& dpdt, Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio) Mat& dpdrot, Mat& dpdt, Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio)
{ {
projectPoints( objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, Mat J;
dpdrot, dpdt, dpdf, dpdc, dpddist, aspectRatio ); projectPoints( objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, J, aspectRatio);
J.colRange(0, 3).copyTo(dpdrot);
J.colRange(3, 6).copyTo(dpdt);
J.colRange(6, 8).copyTo(dpdf);
J.colRange(8, 10).copyTo(dpdc);
J.colRange(10, J.cols).copyTo(dpddist);
} }
///////////////////////////////// Stereo Calibration ///////////////////////////////////// ///////////////////////////////// Stereo Calibration /////////////////////////////////////
@ -1696,7 +1701,7 @@ void CV_StereoCalibrationTest_CPP::rectify( const Mat& cameraMatrix1, const Mat&
Rect* validPixROI1, Rect* validPixROI2, int flags ) Rect* validPixROI1, Rect* validPixROI2, int flags )
{ {
stereoRectify( cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, stereoRectify( cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2,
imageSize, R, T, R1, R2, P1, P2, Q, alpha, newImageSize,validPixROI1, validPixROI2, flags ); imageSize, R, T, R1, R2, P1, P2, Q, flags, alpha, newImageSize,validPixROI1, validPixROI2 );
} }
bool CV_StereoCalibrationTest_CPP::rectifyUncalibrated( const Mat& points1, bool CV_StereoCalibrationTest_CPP::rectifyUncalibrated( const Mat& points1,

@ -104,8 +104,8 @@ protected:
Mat rvec, tvec; Mat rvec, tvec;
vector<int> inliers; vector<int> inliers;
solvePnPRansac(Mat(points), Mat(points1), intrinsics, dist_coeffs, rvec, tvec, solvePnPRansac(points, points1, intrinsics, dist_coeffs, rvec, tvec,
false, 1000, 2.0, -1, &inliers); false, 1000, 2.0, -1, inliers);
bool isTestSuccess = inliers.size() == 475; bool isTestSuccess = inliers.size() == 475;

@ -14,7 +14,7 @@
// For Open Source Computer Vision Library // For Open Source Computer Vision Library
// //
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners. // Third party copyrights are property of their respective owners.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -641,6 +641,8 @@ typedef Vec<ushort, 4> Vec4w;
typedef Vec<int, 2> Vec2i; typedef Vec<int, 2> Vec2i;
typedef Vec<int, 3> Vec3i; typedef Vec<int, 3> Vec3i;
typedef Vec<int, 4> Vec4i; typedef Vec<int, 4> Vec4i;
typedef Vec<int, 6> Vec6i;
typedef Vec<int, 8> Vec8i;
typedef Vec<float, 2> Vec2f; typedef Vec<float, 2> Vec2f;
typedef Vec<float, 3> Vec3f; typedef Vec<float, 3> Vec3f;
@ -1252,10 +1254,90 @@ public:
protected: protected:
_Tp* obj; //< the object pointer. _Tp* obj; //< the object pointer.
int* refcount; //< the associated bbbbbbbbbbbbbbbbbb reference counter int* refcount; //< the associated reference counter
}; };
//////////////////////////////// Mat ////////////////////////////////
//////////////////////// 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, 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 };
InputArray();
InputArray(const Mat& m);
InputArray(const MatExpr& expr);
template<typename _Tp> InputArray(const vector<_Tp>& vec);
template<typename _Tp> InputArray(const vector<vector<_Tp> >& vec);
InputArray(const vector<Mat>& vec);
template<typename _Tp, int m, int n> InputArray(const Matx<_Tp, m, n>& matx);
InputArray(const double& val);
Mat getMat(int i=-1) const;
void getMatVector(vector<Mat>& mv) const;
int kind() const;
Size size(int i=-1) 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 empty() const;
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<typename _Tp> OutputArray(vector<_Tp>& vec);
template<typename _Tp> OutputArray(vector<vector<_Tp> >& vec);
OutputArray(vector<Mat>& vec);
template<typename _Tp, int m, int n> OutputArray(Matx<_Tp, m, n>& matx);
bool fixedSize() const;
bool fixedType() const;
bool needed() const;
Mat& getMatRef(int i=-1);
void create(Size sz, int type, int i=-1, bool allocateVector=false, int fixedDepthMask=0);
void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0);
void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0);
void release();
void clear();
};
typedef InputArray InputArrayOfArrays;
typedef OutputArray OutputArrayOfArrays;
typedef OutputArray InputOutputArray;
/////////////////////////////////////// Mat ///////////////////////////////////////////
enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 }; enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 };
@ -1563,19 +1645,18 @@ public:
Mat clone() const; Mat clone() const;
//! copies the matrix content to "m". //! copies the matrix content to "m".
// It calls m.create(this->size(), this->type()). // It calls m.create(this->size(), this->type()).
void copyTo( Mat& m ) const; void copyTo( OutputArray m ) const;
template<typename _Tp> void copyTo( vector<_Tp>& v ) const;
//! copies those matrix elements to "m" that are marked with non-zero mask elements. //! copies those matrix elements to "m" that are marked with non-zero mask elements.
void copyTo( Mat& m, const Mat& mask ) const; void copyTo( OutputArray m, const InputArray& mask ) const;
//! converts matrix to another datatype with optional scalng. See cvConvertScale. //! converts matrix to another datatype with optional scalng. See cvConvertScale.
void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
void assignTo( Mat& m, int type=-1 ) const; void assignTo( Mat& m, int type=-1 ) const;
//! sets every matrix element to s //! sets every matrix element to s
Mat& operator = (const Scalar& s); Mat& operator = (const Scalar& s);
//! sets some of the matrix elements to s, according to the mask //! sets some of the matrix elements to s, according to the mask
Mat& setTo(const Scalar& s, const Mat& mask=Mat()); Mat& setTo(const Scalar& s, const InputArray& mask=InputArray());
//! creates alternative matrix header for the same data, with different //! creates alternative matrix header for the same data, with different
// number of channels and/or different number of rows. see cvReshape. // number of channels and/or different number of rows. see cvReshape.
Mat reshape(int _cn, int _rows=0) const; Mat reshape(int _cn, int _rows=0) const;
@ -1586,13 +1667,13 @@ public:
//! matrix inversion by means of matrix expressions //! matrix inversion by means of matrix expressions
MatExpr inv(int method=DECOMP_LU) const; MatExpr inv(int method=DECOMP_LU) const;
//! per-element matrix multiplication by means of matrix expressions //! per-element matrix multiplication by means of matrix expressions
MatExpr mul(const Mat& m, double scale=1) const; MatExpr mul(const InputArray& m, double scale=1) const;
MatExpr mul(const MatExpr& m, double scale=1) const; MatExpr mul(const MatExpr& m, double scale=1) const;
//! computes cross-product of 2 3D vectors //! computes cross-product of 2 3D vectors
Mat cross(const Mat& m) const; Mat cross(const InputArray& m) const;
//! computes dot-product //! computes dot-product
double dot(const Mat& m) const; double dot(const InputArray& m) const;
//! Matlab-style matrix initialization //! Matlab-style matrix initialization
static MatExpr zeros(int rows, int cols, int type); static MatExpr zeros(int rows, int cols, int type);
@ -1842,7 +1923,7 @@ public:
float uniform(float a, float b); float uniform(float a, float b);
//! returns uniformly distributed double-precision floating-point random number from [a,b) range //! returns uniformly distributed double-precision floating-point random number from [a,b) range
double uniform(double a, double b); double uniform(double a, double b);
void fill( Mat& mat, int distType, const Scalar& a, const Scalar& b ); void fill( InputOutputArray mat, int distType, const InputArray& a, const InputArray& b );
//! returns Gaussian random variate with mean zero. //! returns Gaussian random variate with mean zero.
double gaussian(double sigma); double gaussian(double sigma);
@ -1850,8 +1931,6 @@ public:
}; };
/*! /*!
Termination criteria in iterative algorithms Termination criteria in iterative algorithms
*/ */
@ -1879,6 +1958,7 @@ public:
double epsilon; // the desired accuracy double epsilon; // the desired accuracy
}; };
//! swaps two matrices //! swaps two matrices
CV_EXPORTS void swap(Mat& a, Mat& b); CV_EXPORTS void swap(Mat& a, Mat& b);
@ -1886,79 +1966,75 @@ CV_EXPORTS void swap(Mat& a, Mat& b);
CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
bool allowND=true, int coiMode=0); bool allowND=true, int coiMode=0);
//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
CV_EXPORTS void extractImageCOI(const CvArr* arr, CV_OUT Mat& coiimg, int coi=-1); CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
CV_EXPORTS void insertImageCOI(const Mat& coiimg, CvArr* arr, int coi=-1); CV_EXPORTS void insertImageCOI(const InputArray& coiimg, CvArr* arr, int coi=-1);
//! adds one matrix to another (dst = src1 + src2) //! adds one matrix to another (dst = src1 + src2)
CV_EXPORTS_W void add(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask CV_WRAP_DEFAULT(Mat())); CV_EXPORTS_W void add(const InputArray& src1, const InputArray& src2, OutputArray dst,
const InputArray& mask=InputArray(), int dtype=-1);
//! subtracts one matrix from another (dst = src1 - src2) //! subtracts one matrix from another (dst = src1 - src2)
CV_EXPORTS_W void subtract(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask CV_WRAP_DEFAULT(Mat())); CV_EXPORTS_W void subtract(const InputArray& src1, const InputArray& src2, OutputArray dst,
//! adds one matrix to another (dst = src1 + src2) const InputArray& mask=InputArray(), int dtype=-1);
CV_EXPORTS void add(const Mat& src1, const Mat& src2, CV_OUT Mat& dst);
//! subtracts one matrix from another (dst = src1 - src2)
CV_EXPORTS void subtract(const Mat& src1, const Mat& src2, CV_OUT Mat& dst);
//! adds scalar to a matrix (dst = src1 + src2)
CV_EXPORTS_W void add(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! subtracts scalar from a matrix (dst = src1 - src2)
CV_EXPORTS_W void subtract(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! subtracts matrix from scalar (dst = src1 - src2)
CV_EXPORTS_W void subtract(const Scalar& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! computes element-wise weighted product of the two arrays (dst = scale*src1*src2) //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2)
CV_EXPORTS_W void multiply(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, double scale=1); CV_EXPORTS_W void multiply(const InputArray& src1, const InputArray& src2,
OutputArray dst, double scale=1, int dtype=-1);
//! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2) //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2)
CV_EXPORTS_W void divide(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, double scale=1); CV_EXPORTS_W void divide(const InputArray& src1, const InputArray& src2, OutputArray dst,
double scale=1, int dtype=-1);
//! computes element-wise weighted reciprocal of an array (dst = scale/src2) //! computes element-wise weighted reciprocal of an array (dst = scale/src2)
CV_EXPORTS_W void divide(double scale, const Mat& src2, CV_OUT Mat& dst); CV_EXPORTS_W void divide(double scale, const InputArray& src2,
OutputArray dst, int dtype=-1);
//! adds scaled array to another one (dst = alpha*src1 + src2) //! adds scaled array to another one (dst = alpha*src1 + src2)
CV_EXPORTS_W void scaleAdd(const Mat& src1, double alpha, const Mat& src2, CV_OUT Mat& dst); CV_EXPORTS_W void scaleAdd(const InputArray& src1, double alpha, const InputArray& src2, OutputArray dst);
//! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
CV_EXPORTS_W void addWeighted(const Mat& src1, double alpha, const Mat& src2, CV_EXPORTS_W void addWeighted(const InputArray& src1, double alpha, const InputArray& src2,
double beta, double gamma, CV_OUT Mat& dst); 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_cast<uchar>abs(src(i)*alpha+beta) //! scales array elements, computes absolute values and converts the results to 8-bit unsigned integers: dst(i)=saturate_cast<uchar>abs(src(i)*alpha+beta)
CV_EXPORTS_W void convertScaleAbs(const Mat& src, CV_OUT Mat& dst, double alpha=1, double beta=0); CV_EXPORTS_W void convertScaleAbs(const InputArray& src, OutputArray dst,
//! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i)) double alpha=1, double beta=0);
CV_EXPORTS_W void LUT(const Mat& src, const Mat& lut, CV_OUT Mat& dst); //! transforms array of numbers using a lookup table: dst(i)=lut(src(i))
CV_EXPORTS_W void LUT(const InputArray& src, const InputArray& lut, OutputArray dst,
int interpolation=0);
//! computes sum of array elements //! computes sum of array elements
CV_EXPORTS_W Scalar sum(const Mat& src); CV_EXPORTS_W Scalar sum(const InputArray& src);
//! computes the number of nonzero array elements //! computes the number of nonzero array elements
CV_EXPORTS_W int countNonZero( const Mat& src ); CV_EXPORTS_W int countNonZero( const InputArray& src );
//! computes mean value of array elements
CV_EXPORTS Scalar mean(const Mat& src);
//! computes mean value of selected array elements //! computes mean value of selected array elements
CV_EXPORTS_W Scalar mean(const Mat& src, const Mat& mask CV_WRAP_DEFAULT(Mat())); CV_EXPORTS_W Scalar mean(const InputArray& src, const InputArray& mask=InputArray());
//! computes mean value and standard deviation of all or selected array elements //! computes mean value and standard deviation of all or selected array elements
CV_EXPORTS_W void meanStdDev(const Mat& src, CV_OUT Scalar& mean, CV_OUT Scalar& stddev, const Mat& mask=Mat()); CV_EXPORTS_W void meanStdDev(const InputArray& src, OutputArray mean, OutputArray stddev,
//! computes norm of array const InputArray& mask=InputArray());
CV_EXPORTS double norm(const Mat& src1, int normType=NORM_L2);
//! computes norm of the difference between two arrays
CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType=NORM_L2);
//! computes norm of the selected array part //! computes norm of the selected array part
CV_EXPORTS_W double norm(const Mat& src1, int normType, const Mat& mask CV_WRAP_DEFAULT(Mat())); CV_EXPORTS_W double norm(const InputArray& src1, int normType=NORM_L2, const InputArray& mask=InputArray());
//! computes norm of selected part of the difference between two arrays //! computes norm of selected part of the difference between two arrays
CV_EXPORTS_W double norm(const Mat& src1, const Mat& src2, CV_EXPORTS_W double norm(const InputArray& src1, const InputArray& src2,
int normType, const Mat& mask CV_WRAP_DEFAULT(Mat())); int normType=NORM_L2, const InputArray& mask=InputArray());
//! 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 //! 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( const Mat& src, CV_OUT Mat& dst, double alpha=1, double beta=0, CV_EXPORTS_W void normalize( const InputArray& src, OutputArray dst, double alpha=1, double beta=0,
int norm_type=NORM_L2, int rtype=-1, const Mat& mask=Mat()); int norm_type=NORM_L2, int dtype=-1, const InputArray& mask=InputArray());
//! finds global minimum and maximum array elements and returns their values and their locations //! finds global minimum and maximum array elements and returns their values and their locations
CV_EXPORTS_W void minMaxLoc(const Mat& src, CV_OUT double* minVal, CV_EXPORTS_W void minMaxLoc(const InputArray& src, CV_OUT double* minVal,
CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0, CV_OUT double* maxVal=0, CV_OUT Point* minLoc=0,
CV_OUT Point* maxLoc=0, const Mat& mask=Mat()); CV_OUT Point* maxLoc=0, const InputArray& mask=InputArray());
CV_EXPORTS void minMaxIdx(const Mat& src, double* minVal, double* maxVal, CV_EXPORTS void minMaxIdx(const InputArray& src, double* minVal, double* maxVal,
int* minIdx=0, int* maxIdx=0, const Mat& mask=Mat()); int* minIdx=0, int* maxIdx=0, const InputArray& mask=InputArray());
//! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows //! 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(const Mat& src, CV_OUT Mat& dst, int dim, int rtype, int dtype=-1); CV_EXPORTS_W void reduce(const InputArray& src, OutputArray dst, int dim, int rtype, int dtype=-1);
//! makes multi-channel array out of several single-channel arrays //! makes multi-channel array out of several single-channel arrays
CV_EXPORTS void merge(const Mat* mv, size_t count, CV_OUT Mat& dst); CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
//! makes multi-channel array out of several single-channel arrays //! makes multi-channel array out of several single-channel arrays
CV_EXPORTS_W void merge(const vector<Mat>& mv, Mat& dst); CV_EXPORTS_W void merge(const vector<Mat>& mv, OutputArray dst);
//! copies each plane of a multi-channel array to a dedicated array //! 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& src, Mat* mvbegin);
@ -1969,133 +2045,131 @@ CV_EXPORTS_W void split(const Mat& m, vector<Mat>& mv);
CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
const int* fromTo, size_t npairs); const int* fromTo, size_t npairs);
CV_EXPORTS void mixChannels(const vector<Mat>& src, vector<Mat>& dst, CV_EXPORTS void mixChannels(const vector<Mat>& src, vector<Mat>& dst,
const int* fromTo, int npairs); const int* fromTo, size_t npairs);
//! reverses the order of the rows, columns or both in a matrix //! reverses the order of the rows, columns or both in a matrix
CV_EXPORTS_W void flip(const Mat& src, CV_OUT Mat& dst, int flipCode); CV_EXPORTS_W void flip(const InputArray& src, OutputArray dst, int flipCode);
//! replicates the input matrix the specified number of times in the horizontal and/or vertical direction //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction
CV_EXPORTS_W void repeat(const Mat& src, int ny, int nx, CV_OUT Mat& dst); CV_EXPORTS_W void repeat(const InputArray& src, int ny, int nx, OutputArray dst);
CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx); CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, Mat& dst); CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
CV_EXPORTS void hconcat(const Mat& src1, const Mat& src2, Mat& dst); CV_EXPORTS void hconcat(const InputArray& src1, const InputArray& src2, OutputArray dst);
CV_EXPORTS_W void hconcat(const vector<Mat>& src, CV_OUT Mat& dst); CV_EXPORTS_W void hconcat(const InputArray& src, OutputArray dst);
CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, Mat& dst); CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
CV_EXPORTS void vconcat(const Mat& src1, const Mat& src2, Mat& dst); CV_EXPORTS void vconcat(const InputArray& src1, const InputArray& src2, OutputArray dst);
CV_EXPORTS_W void vconcat(const vector<Mat>& src, CV_OUT Mat& dst); CV_EXPORTS_W void vconcat(const InputArray& src, OutputArray dst);
//! computes bitwise conjunction of the two arrays (dst = src1 & src2) //! computes bitwise conjunction of the two arrays (dst = src1 & src2)
CV_EXPORTS_W void bitwise_and(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask=Mat()); CV_EXPORTS_W void bitwise_and(const InputArray& src1, const InputArray& src2,
OutputArray dst, const InputArray& mask=InputArray());
//! computes bitwise disjunction of the two arrays (dst = src1 | src2) //! computes bitwise disjunction of the two arrays (dst = src1 | src2)
CV_EXPORTS_W void bitwise_or(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask=Mat()); CV_EXPORTS_W void bitwise_or(const InputArray& src1, const InputArray& src2,
OutputArray dst, const InputArray& mask=InputArray());
//! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2) //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2)
CV_EXPORTS_W void bitwise_xor(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, const Mat& mask=Mat()); CV_EXPORTS_W void bitwise_xor(const InputArray& src1, const InputArray& src2,
//! computes bitwise conjunction of an array and scalar (dst = src1 & src2) OutputArray dst, const InputArray& mask=InputArray());
CV_EXPORTS_W void bitwise_and(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! computes bitwise disjunction of an array and scalar (dst = src1 | src2)
CV_EXPORTS_W void bitwise_or(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! computes bitwise exclusive-or of an array and scalar (dst = src1 ^ src2)
CV_EXPORTS_W void bitwise_xor(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst, const Mat& mask=Mat());
//! inverts each bit of array (dst = ~src) //! inverts each bit of array (dst = ~src)
CV_EXPORTS_W void bitwise_not(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void bitwise_not(const InputArray& src, OutputArray dst,
const InputArray& mask=InputArray());
//! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2)) //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
CV_EXPORTS_W void absdiff(const Mat& src1, const Mat& src2, CV_OUT Mat& dst); CV_EXPORTS_W void absdiff(const InputArray& src1, const InputArray& src2, OutputArray dst);
//! computes element-wise absolute difference of array and scalar (dst = abs(src1 - src2))
CV_EXPORTS_W void absdiff(const Mat& src1, const Scalar& src2, CV_OUT Mat& dst);
//! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) //! 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(const Mat& src, const Mat& lowerb, CV_EXPORTS_W void inRange(const InputArray& src, const InputArray& lowerb,
const Mat& upperb, CV_OUT Mat& dst); const InputArray& upperb, OutputArray dst);
//! set mask elements for those array elements which are within the fixed bounding box (dst = lowerb <= src && src < upperb)
CV_EXPORTS_W void inRange(const Mat& src, const Scalar& lowerb,
const Scalar& upperb, CV_OUT Mat& dst);
//! compares elements of two arrays (dst = src1 <cmpop> src2) //! compares elements of two arrays (dst = src1 <cmpop> src2)
CV_EXPORTS_W void compare(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, int cmpop); CV_EXPORTS_W void compare(const InputArray& src1, const InputArray& src2, OutputArray dst, int cmpop);
//! compares elements of array with scalar (dst = src1 <cmpop> src2) //! computes per-element minimum of two arrays (dst = min(src1, src2))
CV_EXPORTS_W void compare(const Mat& src1, double s, CV_OUT Mat& dst, int cmpop); CV_EXPORTS_W void min(const InputArray& src1, const InputArray& src2, OutputArray dst);
//! computes per-element maximum of two arrays (dst = max(src1, src2))
CV_EXPORTS_W void max(const InputArray& src1, const InputArray& src2, OutputArray dst);
//! computes per-element minimum of two arrays (dst = min(src1, src2)) //! computes per-element minimum of two arrays (dst = min(src1, src2))
CV_EXPORTS_W void min(const Mat& src1, const Mat& src2, CV_OUT Mat& dst); CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
//! computes per-element minimum of array and scalar (dst = min(src1, src2)) //! computes per-element minimum of array and scalar (dst = min(src1, src2))
CV_EXPORTS_W void min(const Mat& src1, double src2, CV_OUT Mat& dst); CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst);
//! computes per-element maximum of two arrays (dst = max(src1, src2)) //! computes per-element maximum of two arrays (dst = max(src1, src2))
CV_EXPORTS_W void max(const Mat& src1, const Mat& src2, CV_OUT Mat& dst); CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
//! computes per-element maximum of array and scalar (dst = max(src1, src2)) //! computes per-element maximum of array and scalar (dst = max(src1, src2))
CV_EXPORTS_W void max(const Mat& src1, double src2, CV_OUT Mat& dst); CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst);
//! computes square root of each matrix element (dst = src**0.5) //! computes square root of each matrix element (dst = src**0.5)
CV_EXPORTS_W void sqrt(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void sqrt(const InputArray& src, OutputArray dst);
//! raises the input matrix elements to the specified power (b = a**power) //! raises the input matrix elements to the specified power (b = a**power)
CV_EXPORTS_W void pow(const Mat& src, double power, CV_OUT Mat& dst); CV_EXPORTS_W void pow(const InputArray& src, double power, OutputArray dst);
//! computes exponent of each matrix element (dst = e**src) //! computes exponent of each matrix element (dst = e**src)
CV_EXPORTS_W void exp(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void exp(const InputArray& src, OutputArray dst);
//! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src)) //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
CV_EXPORTS_W void log(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void log(const InputArray& src, OutputArray dst);
//! computes cube root of the argument //! computes cube root of the argument
CV_EXPORTS_W float cubeRoot(float val); CV_EXPORTS_W float cubeRoot(float val);
//! computes the angle in degrees (0..360) of the vector (x,y) //! computes the angle in degrees (0..360) of the vector (x,y)
CV_EXPORTS_W float fastAtan2(float y, float x); CV_EXPORTS_W float fastAtan2(float y, float x);
//! converts polar coordinates to Cartesian //! converts polar coordinates to Cartesian
CV_EXPORTS_W void polarToCart(const Mat& magnitude, const Mat& angle, CV_EXPORTS_W void polarToCart(const InputArray& magnitude, const InputArray& angle,
CV_OUT Mat& x, CV_OUT Mat& y, bool angleInDegrees=false); OutputArray x, OutputArray y, bool angleInDegrees=false);
//! converts Cartesian coordinates to polar //! converts Cartesian coordinates to polar
CV_EXPORTS_W void cartToPolar(const Mat& x, const Mat& y, CV_EXPORTS_W void cartToPolar(const InputArray& x, const InputArray& y,
CV_OUT Mat& magnitude, CV_OUT Mat& angle, OutputArray magnitude, OutputArray angle,
bool angleInDegrees=false); bool angleInDegrees=false);
//! computes angle (angle(i)) of each (x(i), y(i)) vector //! computes angle (angle(i)) of each (x(i), y(i)) vector
CV_EXPORTS_W void phase(const Mat& x, const Mat& y, CV_OUT Mat& angle, CV_EXPORTS_W void phase(const InputArray& x, const InputArray& y, OutputArray angle,
bool angleInDegrees=false); bool angleInDegrees=false);
//! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector
CV_EXPORTS_W void magnitude(const Mat& x, const Mat& y, CV_OUT Mat& magnitude); CV_EXPORTS_W void magnitude(const InputArray& x, const InputArray& y, OutputArray magnitude);
//! checks that each matrix element is within the specified range. //! checks that each matrix element is within the specified range.
CV_EXPORTS_W bool checkRange(const Mat& a, bool quiet=true, CV_OUT Point* pt=0, CV_EXPORTS_W bool checkRange(const InputArray& a, bool quiet=true, CV_OUT Point* pt=0,
double minVal=-DBL_MAX, double maxVal=DBL_MAX); double minVal=-DBL_MAX, double maxVal=DBL_MAX);
//! implements generalized matrix product algorithm GEMM from BLAS //! implements generalized matrix product algorithm GEMM from BLAS
CV_EXPORTS_W void gemm(const Mat& src1, const Mat& src2, double alpha, CV_EXPORTS_W void gemm(const InputArray& src1, const InputArray& src2, double alpha,
const Mat& src3, double gamma, CV_OUT Mat& dst, int flags=0); const InputArray& src3, double gamma, OutputArray dst, int flags=0);
//! multiplies matrix by its transposition from the left or from the right //! multiplies matrix by its transposition from the left or from the right
CV_EXPORTS_W void mulTransposed( const Mat& src, CV_OUT Mat& dst, bool aTa, CV_EXPORTS_W void mulTransposed( const InputArray& src, OutputArray dst, bool aTa,
const Mat& delta=Mat(), const InputArray& delta=InputArray(),
double scale=1, int rtype=-1 ); double scale=1, int dtype=-1 );
//! transposes the matrix //! transposes the matrix
CV_EXPORTS_W void transpose(const Mat& src, CV_OUT Mat& dst); CV_EXPORTS_W void transpose(const InputArray& src, OutputArray dst);
//! performs affine transformation of each element of multi-channel input matrix //! performs affine transformation of each element of multi-channel input matrix
CV_EXPORTS_W void transform(const Mat& src, CV_OUT Mat& dst, const Mat& m ); CV_EXPORTS_W void transform(const InputArray& src, OutputArray dst, const InputArray& m );
//! performs perspective transformation of each element of multi-channel input matrix //! performs perspective transformation of each element of multi-channel input matrix
CV_EXPORTS_W void perspectiveTransform(const Mat& src, CV_OUT Mat& dst, const Mat& m ); CV_EXPORTS_W void perspectiveTransform(const InputArray& src, OutputArray dst, const InputArray& m );
//! extends the symmetrical matrix from the lower half or from the upper half //! extends the symmetrical matrix from the lower half or from the upper half
CV_EXPORTS_W void completeSymm(Mat& mtx, bool lowerToUpper=false); CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false);
//! initializes scaled identity matrix //! initializes scaled identity matrix
CV_EXPORTS_W void setIdentity(Mat& mtx, const Scalar& s=Scalar(1)); CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1));
//! computes determinant of a square matrix //! computes determinant of a square matrix
CV_EXPORTS_W double determinant(const Mat& mtx); CV_EXPORTS_W double determinant(const InputArray& mtx);
//! computes trace of a matrix //! computes trace of a matrix
CV_EXPORTS_W Scalar trace(const Mat& mtx); CV_EXPORTS_W Scalar trace(const InputArray& mtx);
//! computes inverse or pseudo-inverse matrix //! computes inverse or pseudo-inverse matrix
CV_EXPORTS_W double invert(const Mat& src, CV_OUT Mat& dst, int flags=DECOMP_LU); CV_EXPORTS_W double invert(const InputArray& src, OutputArray dst, int flags=DECOMP_LU);
//! solves linear system or a least-square problem //! solves linear system or a least-square problem
CV_EXPORTS_W bool solve(const Mat& src1, const Mat& src2, CV_OUT Mat& dst, int flags=DECOMP_LU); CV_EXPORTS_W bool solve(const InputArray& src1, const InputArray& src2,
OutputArray dst, int flags=DECOMP_LU);
//! sorts independently each matrix row or each matrix column //! sorts independently each matrix row or each matrix column
CV_EXPORTS_W void sort(const Mat& src, CV_OUT Mat& dst, int flags); CV_EXPORTS_W void sort(const InputArray& src, OutputArray dst, int flags);
//! sorts independently each matrix row or each matrix column //! sorts independently each matrix row or each matrix column
CV_EXPORTS_W void sortIdx(const Mat& src, CV_OUT Mat& dst, int flags); CV_EXPORTS_W void sortIdx(const InputArray& src, OutputArray dst, int flags);
//! finds real roots of a cubic polynomial //! finds real roots of a cubic polynomial
CV_EXPORTS_W int solveCubic(const Mat& coeffs, CV_OUT Mat& roots); CV_EXPORTS_W int solveCubic(const InputArray& coeffs, OutputArray roots);
//! finds real and complex roots of a polynomial //! finds real and complex roots of a polynomial
CV_EXPORTS_W double solvePoly(const Mat& coeffs, CV_OUT Mat& roots, int maxIters=300); CV_EXPORTS_W double solvePoly(const InputArray& coeffs, OutputArray roots, int maxIters=300);
//! finds eigenvalues of a symmetric matrix //! finds eigenvalues of a symmetric matrix
CV_EXPORTS bool eigen(const Mat& src, CV_OUT Mat& eigenvalues, int lowindex=-1, CV_EXPORTS bool eigen(const InputArray& src, OutputArray eigenvalues, int lowindex=-1,
int highindex=-1); int highindex=-1);
//! finds eigenvalues and eigenvectors of a symmetric matrix //! finds eigenvalues and eigenvectors of a symmetric matrix
CV_EXPORTS bool eigen(const Mat& src, CV_OUT Mat& eigenvalues, CV_OUT Mat& eigenvectors, CV_EXPORTS bool eigen(const InputArray& src, OutputArray eigenvalues,
OutputArray eigenvectors,
int lowindex=-1, int highindex=-1); int lowindex=-1, int highindex=-1);
//! computes covariation matrix of a set of samples //! computes covariation matrix of a set of samples
CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
int flags, int ctype=CV_64F); int flags, int ctype=CV_64F);
//! computes covariation matrix of a set of samples //! computes covariation matrix of a set of samples
CV_EXPORTS_W void calcCovarMatrix( const Mat& samples, CV_OUT Mat& covar, CV_OUT Mat& mean, CV_EXPORTS_W void calcCovarMatrix( const InputArray& samples, OutputArray covar,
int flags, int ctype=CV_64F); OutputArray mean, int flags, int ctype=CV_64F);
/*! /*!
Principal Component Analysis Principal Component Analysis
@ -2157,17 +2231,17 @@ public:
//! default constructor //! default constructor
PCA(); PCA();
//! the constructor that performs PCA //! the constructor that performs PCA
PCA(const Mat& data, const Mat& mean, int flags, int maxComponents=0); PCA(const InputArray& data, const InputArray& mean, int flags, int maxComponents=0);
//! operator that performs PCA. The previously stored data, if any, is released //! operator that performs PCA. The previously stored data, if any, is released
PCA& operator()(const Mat& data, const Mat& mean, int flags, int maxComponents=0); PCA& operator()(const InputArray& data, const InputArray& mean, int flags, int maxComponents=0);
//! projects vector from the original space to the principal components subspace //! projects vector from the original space to the principal components subspace
Mat project(const Mat& vec) const; Mat project(const InputArray& vec) const;
//! projects vector from the original space to the principal components subspace //! projects vector from the original space to the principal components subspace
void project(const Mat& vec, CV_OUT Mat& result) const; void project(const InputArray& vec, OutputArray result) const;
//! reconstructs the original vector from the projection //! reconstructs the original vector from the projection
Mat backProject(const Mat& vec) const; Mat backProject(const InputArray& vec) const;
//! reconstructs the original vector from the projection //! reconstructs the original vector from the projection
void backProject(const Mat& vec, CV_OUT Mat& result) const; void backProject(const InputArray& vec, OutputArray result) const;
Mat eigenvectors; //!< eigenvectors of the covariation matrix Mat eigenvectors; //!< eigenvectors of the covariation matrix
Mat eigenvalues; //!< eigenvalues of the covariation matrix Mat eigenvalues; //!< eigenvalues of the covariation matrix
@ -2194,17 +2268,19 @@ public:
//! the default constructor //! the default constructor
SVD(); SVD();
//! the constructor that performs SVD //! the constructor that performs SVD
SVD( const Mat& src, int flags=0 ); SVD( const InputArray& src, int flags=0 );
//! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released. //! the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released.
SVD& operator ()( const Mat& src, int flags=0 ); SVD& operator ()( const InputArray& src, int flags=0 );
//! decomposes matrix and stores the results to user-provided matrices //! decomposes matrix and stores the results to user-provided matrices
static void compute( const Mat& src, CV_OUT Mat& w, CV_OUT Mat& u, CV_OUT Mat& vt, int flags=0 ); static void compute( const InputArray& src, OutputArray w,
OutputArray u, OutputArray vt, int flags=0 );
//! computes singular values of a matrix //! computes singular values of a matrix
static void compute( const Mat& src, CV_OUT Mat& w, int flags=0 ); static void compute( const InputArray& src, OutputArray w, int flags=0 );
//! performs back substitution //! performs back substitution
static void backSubst( const Mat& w, const Mat& u, const Mat& vt, static void backSubst( const InputArray& w, const InputArray& u,
const Mat& rhs, CV_OUT Mat& dst ); const InputArray& vt, const InputArray& rhs,
OutputArray dst );
template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a, template<typename _Tp, int m, int n, int nm> static void compute( const Matx<_Tp, m, n>& a,
Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
@ -2214,28 +2290,28 @@ public:
const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); 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| //! finds dst = arg min_{|dst|=1} |m*dst|
static void solveZ( const Mat& src, CV_OUT Mat& dst ); static void solveZ( const 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 //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix
void backSubst( const Mat& rhs, CV_OUT Mat& dst ) const; void backSubst( const InputArray& rhs, OutputArray dst ) const;
Mat u, w, vt; Mat u, w, vt;
}; };
//! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix //! computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix
CV_EXPORTS_W double Mahalanobis(const Mat& v1, const Mat& v2, const Mat& icovar); CV_EXPORTS_W double Mahalanobis(const InputArray& v1, const InputArray& v2, const InputArray& icovar);
//! a synonym for Mahalanobis //! a synonym for Mahalanobis
CV_EXPORTS double Mahalonobis(const Mat& v1, const Mat& v2, const Mat& icovar); CV_EXPORTS double Mahalonobis(const InputArray& v1, const InputArray& v2, const InputArray& icovar);
//! performs forward or inverse 1D or 2D Discrete Fourier Transformation //! performs forward or inverse 1D or 2D Discrete Fourier Transformation
CV_EXPORTS_W void dft(const Mat& src, CV_OUT Mat& dst, int flags=0, int nonzeroRows=0); CV_EXPORTS_W void dft(const InputArray& src, OutputArray dst, int flags=0, int nonzeroRows=0);
//! performs inverse 1D or 2D Discrete Fourier Transformation //! performs inverse 1D or 2D Discrete Fourier Transformation
CV_EXPORTS_W void idft(const Mat& src, CV_OUT Mat& dst, int flags=0, int nonzeroRows=0); CV_EXPORTS_W void idft(const InputArray& src, OutputArray dst, int flags=0, int nonzeroRows=0);
//! performs forward or inverse 1D or 2D Discrete Cosine Transformation //! performs forward or inverse 1D or 2D Discrete Cosine Transformation
CV_EXPORTS_W void dct(const Mat& src, CV_OUT Mat& dst, int flags=0); CV_EXPORTS_W void dct(const InputArray& src, OutputArray dst, int flags=0);
//! performs inverse 1D or 2D Discrete Cosine Transformation //! performs inverse 1D or 2D Discrete Cosine Transformation
CV_EXPORTS_W void idct(const Mat& src, CV_OUT Mat& dst, int flags=0); CV_EXPORTS_W void idct(const 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 //! computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication
CV_EXPORTS_W void mulSpectrums(const Mat& a, const Mat& b, CV_OUT Mat& c, CV_EXPORTS_W void mulSpectrums(const InputArray& a, const InputArray& b, OutputArray c,
int flags, bool conjB=false); 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 //! 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); CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
@ -2250,9 +2326,9 @@ enum
KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization KMEANS_USE_INITIAL_LABELS=1 // Uses the user-provided labels for K-Means initialization
}; };
//! clusters the input data using k-Means algorithm //! clusters the input data using k-Means algorithm
CV_EXPORTS_W double kmeans( const Mat& data, int K, CV_OUT Mat& bestLabels, CV_EXPORTS_W double kmeans( const InputArray& data, int K, CV_OUT InputOutputArray bestLabels,
TermCriteria criteria, int attempts, TermCriteria criteria, int attempts,
int flags, CV_OUT Mat* centers=0 ); int flags, OutputArray centers=OutputArray() );
//! returns the thread-local Random number generator //! returns the thread-local Random number generator
CV_EXPORTS RNG& theRNG(); CV_EXPORTS RNG& theRNG();
@ -2261,13 +2337,13 @@ CV_EXPORTS RNG& theRNG();
template<typename _Tp> static inline _Tp randu() { return (_Tp)theRNG(); } template<typename _Tp> static inline _Tp randu() { return (_Tp)theRNG(); }
//! fills array with uniformly-distributed random numbers from the range [low, high) //! fills array with uniformly-distributed random numbers from the range [low, high)
CV_EXPORTS_W void randu(CV_OUT Mat& dst, const Scalar& low, const Scalar& high); CV_EXPORTS_W void randu(CV_IN_OUT OutputArray dst, const InputArray& low, const InputArray& high);
//! fills array with normally-distributed random numbers with the specified mean and the standard deviation //! fills array with normally-distributed random numbers with the specified mean and the standard deviation
CV_EXPORTS_W void randn(CV_OUT Mat& dst, const Scalar& mean, const Scalar& stddev); CV_EXPORTS_W void randn(CV_IN_OUT OutputArray dst, const InputArray& mean, const InputArray& stddev);
//! shuffles the input array elements //! shuffles the input array elements
CV_EXPORTS void randShuffle(Mat& dst, double iterFactor=1., RNG* rng=0); CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0);
//! draws the line segment (pt1, pt2) in the image //! draws the line segment (pt1, pt2) in the image
CV_EXPORTS_W void line(Mat& img, Point pt1, Point pt2, const Scalar& color, CV_EXPORTS_W void line(Mat& img, Point pt1, Point pt2, const Scalar& color,
@ -2828,6 +2904,7 @@ template<typename _Tp, size_t fixed_size=4096/sizeof(_Tp)+8> class CV_EXPORTS Au
{ {
public: public:
typedef _Tp value_type; typedef _Tp value_type;
enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) };
//! the default contructor //! the default contructor
AutoBuffer(); AutoBuffer();
@ -2851,7 +2928,7 @@ protected:
//! size of the real buffer //! size of the real buffer
size_t size; size_t size;
//! pre-allocated buffer //! pre-allocated buffer
_Tp buf[fixed_size]; _Tp buf[fixed_size+buffer_padding];
}; };
/////////////////////////// multi-dimensional dense matrix ////////////////////////// /////////////////////////// multi-dimensional dense matrix //////////////////////////
@ -2912,9 +2989,11 @@ public:
//! the default constructor //! the default constructor
NAryMatIterator(); NAryMatIterator();
//! the full constructor taking arbitrary number of n-dim matrices //! 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); NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
//! the separate iterator initialization method //! the separate iterator initialization method
void init(const Mat** arrays, Mat* planes, int narrays=-1); void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
//! proceeds to the next plane of every iterated matrix //! proceeds to the next plane of every iterated matrix
NAryMatIterator& operator ++(); NAryMatIterator& operator ++();
@ -2925,12 +3004,17 @@ public:
const Mat** arrays; const Mat** arrays;
//! the current planes //! the current planes
Mat* planes; Mat* planes;
//! data pointers
uchar** ptrs;
//! the number of arrays //! the number of arrays
int narrays; int narrays;
//! the number of planes in each array //! the number of hyper-planes that the iterator steps through
int nplanes; size_t nplanes;
//! the size of each segment (in elements)
size_t size;
protected: protected:
int iterdepth, idx; int iterdepth;
size_t idx;
}; };
//typedef NAryMatIterator NAryMatNDIterator; //typedef NAryMatIterator NAryMatNDIterator;
@ -3081,7 +3165,7 @@ public:
\param try1d if true and m is a single-column matrix (Nx1), \param try1d if true and m is a single-column matrix (Nx1),
then the sparse matrix will be 1-dimensional. then the sparse matrix will be 1-dimensional.
*/ */
SparseMat(const Mat& m); explicit SparseMat(const Mat& m);
//! converts old-style sparse matrix to the new-style. All the data is copied //! converts old-style sparse matrix to the new-style. All the data is copied
SparseMat(const CvSparseMat* m); SparseMat(const CvSparseMat* m);
//! the destructor //! the destructor
@ -3563,39 +3647,30 @@ public:
//! the default constructor //! the default constructor
CV_WRAP KDTree(); CV_WRAP KDTree();
//! the full constructor that builds the search tree //! the full constructor that builds the search tree
CV_WRAP KDTree(const Mat& _points, bool copyAndReorderPoints=false); CV_WRAP KDTree(const InputArray& points, bool copyAndReorderPoints=false);
//! the full constructor that builds the search tree //! the full constructor that builds the search tree
CV_WRAP KDTree(const Mat& _points, const Mat& _labels, bool copyAndReorderPoints=false); CV_WRAP KDTree(const InputArray& points, const InputArray& _labels,
bool copyAndReorderPoints=false);
//! builds the search tree //! builds the search tree
CV_WRAP void build(const Mat& _points, bool copyAndReorderPoints=false); CV_WRAP void build(const InputArray& points, bool copyAndReorderPoints=false);
//! builds the search tree //! builds the search tree
CV_WRAP void build(const Mat& _points, const Mat& _labels, bool copyAndReorderPoints=false); CV_WRAP void build(const InputArray& points, const InputArray& labels,
bool copyAndReorderPoints=false);
//! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves //! finds the K nearest neighbors of "vec" while looking at Emax (at most) leaves
int findNearest(const float* vec, CV_WRAP int findNearest(const InputArray& vec, int K, int Emax,
int K, int Emax, int* neighborsIdx, OutputArray neighborsIdx,
Mat* neighbors=0, float* dist=0, int* labels=0) const; OutputArray neighbors=OutputArray(),
//! finds the K nearest neighbors while looking at Emax (at most) leaves OutputArray dist=OutputArray(),
int findNearest(const float* vec, int K, int Emax, OutputArray labels=OutputArray()) const;
vector<int>* neighborsIdx,
Mat* neighbors=0,
vector<float>* dist=0,
vector<int>* labels=0) const;
CV_WRAP int findNearest(const vector<float>& vec, int K, int Emax,
CV_OUT vector<int>* neighborsIdx,
CV_OUT Mat* neighbors=0,
CV_OUT vector<float>* dist=0,
CV_OUT vector<int>* labels=0) const;
//! finds all the points from the initial set that belong to the specified box //! finds all the points from the initial set that belong to the specified box
void findOrthoRange(const float* minBounds, const float* maxBounds, CV_WRAP void findOrthoRange(const InputArray& minBounds,
vector<int>* neighborsIdx, Mat* neighbors=0, const InputArray& maxBounds,
vector<int>* labels=0) const; OutputArray neighborsIdx,
CV_WRAP void findOrthoRange(const vector<float>& minBounds, const vector<float>& maxBounds, OutputArray neighbors=OutputArray(),
CV_OUT vector<int>* neighborsIdx, CV_OUT Mat* neighbors=0, OutputArray labels=OutputArray()) const;
CV_OUT vector<int>* labels=0) const;
//! returns vectors with the specified indices //! returns vectors with the specified indices
void getPoints(const int* idx, size_t nidx, Mat& pts, vector<int>* labels=0) const; CV_WRAP void getPoints(const InputArray& idx, OutputArray pts,
//! returns vectors with the specified indices OutputArray labels=OutputArray()) const;
CV_WRAP void getPoints(const vector<int>& idxs, Mat& pts, CV_OUT vector<int>* labels=0) const;
//! return a vector with the specified index //! return a vector with the specified index
const float* getPoint(int ptidx, int* label=0) const; const float* getPoint(int ptidx, int* label=0) const;
//! returns the search space dimensionality //! returns the search space dimensionality
@ -4042,7 +4117,7 @@ public:
int index; int index;
}; };
#if 0
class CV_EXPORTS AlgorithmImpl; class CV_EXPORTS AlgorithmImpl;
/*! /*!
@ -4088,7 +4163,6 @@ protected:
Ptr<AlgorithmImpl> impl; Ptr<AlgorithmImpl> impl;
}; };
#endif
} }

@ -608,21 +608,6 @@ template<typename _Tp> inline MatIterator_<_Tp> Mat::end()
return it; return it;
} }
template<typename _Tp> inline void Mat::copyTo(vector<_Tp>& v) const
{
int n = checkVector(DataType<_Tp>::channels);
if( empty() || n == 0 )
{
v.clear();
return;
}
CV_Assert( n > 0 );
v.resize(n);
Mat temp(dims, size.p, DataType<_Tp>::type, &v[0]);
convertTo(temp, DataType<_Tp>::type);
}
template<typename _Tp> inline Mat::operator vector<_Tp>() const template<typename _Tp> inline Mat::operator vector<_Tp>() const
{ {
vector<_Tp> v; vector<_Tp> v;
@ -726,10 +711,12 @@ static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMod
///////////////////////////////////////////// SVD ////////////////////////////////////////////////////// ///////////////////////////////////////////// SVD //////////////////////////////////////////////////////
inline SVD::SVD() {} inline SVD::SVD() {}
inline SVD::SVD( const Mat& m, int flags ) { operator ()(m, flags); } inline SVD::SVD( const InputArray& m, int flags ) { operator ()(m, flags); }
inline void SVD::solveZ( const Mat& m, Mat& dst ) inline void SVD::solveZ( const InputArray& m, OutputArray _dst )
{ {
SVD svd(m); SVD svd(m);
_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); svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst);
} }
@ -1075,6 +1062,22 @@ process( const Mat_<T1>& m1, const Mat_<T2>& m2, Mat_<T3>& m3, Op op )
} }
} }
/////////////////////////////// Input/Output Arrays /////////////////////////////////
template<typename _Tp> InputArray::InputArray(const vector<_Tp>& vec)
: flags(STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {}
template<typename _Tp> InputArray::InputArray(const vector<vector<_Tp> >& vec)
: flags(STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {}
template<typename _Tp, int m, int n> InputArray::InputArray(const Matx<_Tp, m, n>& mtx)
: flags(MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m) {}
template<typename _Tp> OutputArray::OutputArray(vector<_Tp>& vec) : InputArray(vec) {}
template<typename _Tp> OutputArray::OutputArray(vector<vector<_Tp> >& vec) : InputArray(vec) {}
template<typename _Tp, int m, int n> OutputArray::OutputArray(Matx<_Tp, m, n>& mtx) : InputArray(mtx) {}
//////////////////////////////////// Matrix Expressions ///////////////////////////////////////// //////////////////////////////////// Matrix Expressions /////////////////////////////////////////
class CV_EXPORTS MatOp class CV_EXPORTS MatOp
@ -1113,6 +1116,9 @@ public:
virtual void transpose(const MatExpr& expr, MatExpr& res) const; virtual void transpose(const MatExpr& expr, MatExpr& res) const;
virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
virtual Size size(const MatExpr& expr) const;
virtual int type(const MatExpr& expr) const;
}; };
@ -1152,6 +1158,9 @@ public:
MatExpr mul(const MatExpr& e, double scale=1) const; MatExpr mul(const MatExpr& e, double scale=1) const;
MatExpr mul(const Mat& m, double scale=1) const; MatExpr mul(const Mat& m, double scale=1) const;
Size size() const;
int type() const;
const MatOp* op; const MatOp* op;
int flags; int flags;

@ -2298,10 +2298,17 @@ inline Point LineIterator::pos() const
/////////////////////////////// AutoBuffer //////////////////////////////////////// /////////////////////////////// AutoBuffer ////////////////////////////////////////
template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::AutoBuffer() template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::AutoBuffer()
: ptr(buf), size(fixed_size) {} {
ptr = alignPtr(buf, 16);
size = fixed_size;
}
template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
: ptr(buf), size(fixed_size) { allocate(_size); } {
ptr = alignPtr(buf, 16);
size = fixed_size;
allocate(_size);
}
template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::~AutoBuffer() template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
{ deallocate(); } { deallocate(); }
@ -2320,10 +2327,11 @@ template<typename _Tp, size_t fixed_size> inline void AutoBuffer<_Tp, fixed_size
template<typename _Tp, size_t fixed_size> inline void AutoBuffer<_Tp, fixed_size>::deallocate() template<typename _Tp, size_t fixed_size> inline void AutoBuffer<_Tp, fixed_size>::deallocate()
{ {
if( ptr != buf ) _Tp* buf0 = alignPtr(buf, 16);
if( ptr != buf0 )
{ {
cv::deallocate<_Tp>(ptr, size); cv::deallocate<_Tp>(ptr, size);
ptr = buf; ptr = buf0;
size = fixed_size; size = fixed_size;
} }
} }
@ -3550,7 +3558,6 @@ template<typename _Tp> static inline std::ostream& operator << (std::ostream& ou
return out; return out;
} }
#if 0
template<typename _Tp> struct AlgorithmParamType {}; template<typename _Tp> struct AlgorithmParamType {};
template<> struct AlgorithmParamType<int> { enum { type = CV_PARAM_TYPE_INT }; }; template<> struct AlgorithmParamType<int> { enum { type = CV_PARAM_TYPE_INT }; };
template<> struct AlgorithmParamType<double> { enum { type = CV_PARAM_TYPE_REAL }; }; template<> struct AlgorithmParamType<double> { enum { type = CV_PARAM_TYPE_REAL }; };
@ -3594,7 +3601,6 @@ template<typename _Tp> void Algorithm::setParamRange(int propId, const _Tp& minV
{ {
setParamRange_(propId, AlgorithmParamType<_Tp>::type, &minVal, &maxVal); setParamRange_(propId, AlgorithmParamType<_Tp>::type, &minVal, &maxVal);
} }
#endif
} }

File diff suppressed because it is too large Load Diff

@ -722,10 +722,10 @@ icvGetNodePtr( CvSparseMat* mat, const int* idx, int* _type,
node->hashval = hashval; node->hashval = hashval;
node->next = (CvSparseNode*)mat->hashtable[tabidx]; node->next = (CvSparseNode*)mat->hashtable[tabidx];
mat->hashtable[tabidx] = node; mat->hashtable[tabidx] = node;
CV_MEMCPY_INT( CV_NODE_IDX(mat,node), idx, mat->dims ); memcpy(CV_NODE_IDX(mat,node), idx, mat->dims*sizeof(idx[0]));
ptr = (uchar*)CV_NODE_VAL(mat,node); ptr = (uchar*)CV_NODE_VAL(mat,node);
if( create_node > 0 ) if( create_node > 0 )
CV_ZERO_CHAR( ptr, CV_ELEM_SIZE(mat->type)); memset( ptr, 0, CV_ELEM_SIZE(mat->type));
} }
if( _type ) if( _type )
@ -1512,7 +1512,7 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
do do
{ {
offset -= pix_size; offset -= pix_size;
CV_MEMCPY_AUTO( (char*)data + offset, data, pix_size ); memcpy((char*)data + offset, data, pix_size);
} }
while( offset > pix_size ); while( offset > pix_size );
} }
@ -2358,7 +2358,7 @@ cvClearND( CvArr* arr, const int* idx )
uchar* ptr; uchar* ptr;
ptr = cvPtrND( arr, idx, &type ); ptr = cvPtrND( arr, idx, &type );
if( ptr ) if( ptr )
CV_ZERO_CHAR( ptr, CV_ELEM_SIZE(type) ); memset( ptr, 0, CV_ELEM_SIZE(type) );
} }
else else
icvDeleteNode( (CvSparseMat*)arr, idx, 0 ); icvDeleteNode( (CvSparseMat*)arr, idx, 0 );

File diff suppressed because it is too large Load Diff

@ -11,7 +11,7 @@
// For Open Source Computer Vision Library // For Open Source Computer Vision Library
// //
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners. // Third party copyrights are property of their respective owners.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -52,18 +52,12 @@ namespace cv
{ {
template<typename T> static void template<typename T> static void
copyMask_(const Mat& srcmat, Mat& dstmat, const Mat& maskmat) copyMask_(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size)
{ {
const uchar* mask = maskmat.data; for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep )
size_t sstep = srcmat.step;
size_t dstep = dstmat.step;
size_t mstep = maskmat.step;
Size size = getContinuousSize(srcmat, dstmat, maskmat);
for( int y = 0; y < size.height; y++, mask += mstep )
{ {
const T* src = (const T*)(srcmat.data + sstep*y); const T* src = (const T*)_src;
T* dst = (T*)(dstmat.data + dstep*y); T* dst = (T*)_dst;
int x = 0; int x = 0;
for( ; x <= size.width - 4; x += 4 ) for( ; x <= size.width - 4; x += 4 )
{ {
@ -82,389 +76,397 @@ copyMask_(const Mat& srcmat, Mat& dstmat, const Mat& maskmat)
} }
} }
template<typename T> static void static void
setMask_(const void* _scalar, Mat& dstmat, const Mat& maskmat) copyMaskGeneric(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size, void* _esz)
{ {
T scalar = *(T*)_scalar; size_t k, esz = *(size_t*)_esz;
const uchar* mask = maskmat.data; for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep )
size_t dstep = dstmat.step; {
size_t mstep = maskmat.step; const uchar* src = _src;
Size size = dstmat.size(); uchar* dst = _dst;
int x = 0;
if( dstmat.isContinuous() && maskmat.isContinuous() ) for( ; x < size.width; x++, src += esz, dst += esz )
{ {
size.width *= size.height; if( !mask[x] )
size.height = 1; continue;
for( k = 0; k < esz; k++ )
dst[k] = src[k];
}
}
} }
for( int y = 0; y < size.height; y++, mask += mstep ) template<typename T> static void
setMask_(T value, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size)
{ {
T* dst = (T*)(dstmat.data + dstep*y); for( ; size.height--; mask += mstep, _dst += dstep )
{
T* dst = (T*)_dst;
int x = 0; int x = 0;
for( ; x <= size.width - 4; x += 4 ) for( ; x <= size.width - 4; x += 4 )
{ {
if( mask[x] ) if( mask[x] )
dst[x] = scalar; dst[x] = value;
if( mask[x+1] ) if( mask[x+1] )
dst[x+1] = scalar; dst[x+1] = value;
if( mask[x+2] ) if( mask[x+2] )
dst[x+2] = scalar; dst[x+2] = value;
if( mask[x+3] ) if( mask[x+3] )
dst[x+3] = scalar; dst[x+3] = value;
} }
for( ; x < size.width; x++ ) for( ; x < size.width; x++ )
if( mask[x] ) if( mask[x] )
dst[x] = scalar; dst[x] = value;
}
} }
static void
setMaskGeneric(const uchar* value, size_t, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size, void* _esz)
{
size_t k, esz = *(size_t*)_esz;
for( ; size.height--; mask += mstep, _dst += dstep )
{
uchar* dst = _dst;
int x = 0;
for( ; x < size.width; x++, dst += esz )
{
if( !mask[x] )
continue;
for( k = 0; k < esz; k++ )
dst[k] = value[k];
} }
}
}
#define DEF_COPY_SET_MASK(suffix, type) \
static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \
uchar* dst, size_t dstep, Size size, void*) \
{ \
copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \
} \
static void setMask##suffix( const uchar* src, size_t, const uchar* mask, size_t mstep, \
uchar* dst, size_t dstep, Size size, void*) \
{ \
setMask_<type>(*(const type*)src, mask, mstep, dst, dstep, size); \
}
typedef void (*SetMaskFunc)(const void* scalar, Mat& dst, const Mat& mask); DEF_COPY_SET_MASK(8u, uchar);
DEF_COPY_SET_MASK(16u, ushort);
DEF_COPY_SET_MASK(8uC3, Vec3b);
DEF_COPY_SET_MASK(32s, int);
DEF_COPY_SET_MASK(16uC3, Vec3s);
DEF_COPY_SET_MASK(32sC2, Vec2i);
DEF_COPY_SET_MASK(32sC3, Vec3i);
DEF_COPY_SET_MASK(32sC4, Vec4i);
DEF_COPY_SET_MASK(32sC6, Vec6i);
DEF_COPY_SET_MASK(32sC8, Vec8i);
CopyMaskFunc g_copyMaskFuncTab[] = BinaryFunc copyMaskTab[] =
{ {
0, 0,
copyMask_<uchar>, // 1 copyMask8u,
copyMask_<ushort>, // 2 copyMask16u,
copyMask_<Vec<uchar,3> >, // 3 copyMask8uC3,
copyMask_<int>, // 4 copyMask32s,
0, 0,
copyMask_<Vec<ushort,3> >, // 6 copyMask16uC3,
0, 0,
copyMask_<Vec<int,2> >, // 8 copyMask32sC2,
0, 0, 0, 0, 0, 0,
copyMask_<Vec<int,3> >, // 12 copyMask32sC3,
0, 0, 0, 0, 0, 0,
copyMask_<Vec<int,4> >, // 16 copyMask32sC4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
copyMask_<Vec<int,6> >, // 24 copyMask32sC6,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
copyMask_<Vec<int,8> > // 32 copyMask32sC8
}; };
static SetMaskFunc setMaskFuncTab[] = BinaryFunc setMaskTab[] =
{ {
0, 0,
setMask_<uchar>, // 1 setMask8u,
setMask_<ushort>, // 2 setMask16u,
setMask_<Vec<uchar,3> >, // 3 setMask8uC3,
setMask_<int>, // 4 setMask32s,
0, 0,
setMask_<Vec<ushort,3> >, // 6 setMask16uC3,
0, 0,
setMask_<Vec<int,2> >, // 8 setMask32sC2,
0, 0, 0, 0, 0, 0,
setMask_<Vec<int,3> >, // 12 setMask32sC3,
0, 0, 0, 0, 0, 0,
setMask_<Vec<int,4> >, // 16 setMask32sC4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
setMask_<Vec<int,6> >, // 24 setMask32sC6,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
setMask_<Vec<int,8> > // 32 setMask32sC8
}; };
BinaryFunc getCopyMaskFunc(size_t esz)
{
return esz <= 32 && copyMaskTab[esz] ? copyMaskTab[esz] : copyMaskGeneric;
}
/* dst = src */ /* dst = src */
void Mat::copyTo( Mat& dst ) const void Mat::copyTo( OutputArray _dst ) const
{
int dtype = _dst.type();
if( _dst.fixedType() && dtype != type() )
{ {
if( data == dst.data && data != 0 ) convertTo( _dst, dtype );
return; return;
}
if( dims > 2 ) if( empty() )
{
dst.create( dims, size, type() );
if( total() != 0 )
{ {
const Mat* arrays[] = { this, &dst, 0 }; _dst.release();
Mat planes[2];
NAryMatIterator it(arrays, planes);
CV_DbgAssert(it.planes[0].isContinuous() &&
it.planes[1].isContinuous());
size_t planeSize = it.planes[0].elemSize()*it.planes[0].rows*it.planes[0].cols;
for( int i = 0; i < it.nplanes; i++, ++it )
memcpy(it.planes[1].data, it.planes[0].data, planeSize);
}
return; return;
} }
dst.create( rows, cols, type() ); if( dims <= 2 )
Size sz = size(); {
_dst.create( rows, cols, type() );
Mat dst = _dst.getMat();
if( data == dst.data )
return;
if( rows > 0 && cols > 0 ) if( rows > 0 && cols > 0 )
{ {
const uchar* sptr = data; const uchar* sptr = data;
uchar* dptr = dst.data; uchar* dptr = dst.data;
size_t width = sz.width*elemSize(); Size sz = getContinuousSize(*this, dst, (int)elemSize());
if( isContinuous() && dst.isContinuous() ) for( ; sz.height--; sptr += step, dptr += dst.step )
{ memcpy( dptr, sptr, sz.width );
width *= sz.height; }
sz.height = 1; return;
} }
for( ; sz.height--; sptr += step, dptr += dst.step ) _dst.create( dims, size, type() );
memcpy( dptr, sptr, width ); Mat dst = _dst.getMat();
if( data == dst.data )
return;
if( total() != 0 )
{
const Mat* arrays[] = { this, &dst };
uchar* ptrs[2];
NAryMatIterator it(arrays, ptrs, 2);
size_t size = it.size*elemSize();
for( size_t i = 0; i < it.nplanes; i++, ++it )
memcpy(ptrs[1], ptrs[0], size);
} }
} }
void Mat::copyTo( Mat& dst, const Mat& mask ) const void Mat::copyTo( OutputArray _dst, const InputArray& _mask ) const
{ {
Mat mask = _mask.getMat();
if( !mask.data ) if( !mask.data )
{ {
copyTo(dst); copyTo(_dst);
return; return;
} }
if( dims > 2 ) CV_Assert( mask.type() == CV_8U );
{
dst.create( dims, size, type() );
const Mat* arrays[] = { this, &dst, &mask, 0 };
Mat planes[3];
NAryMatIterator it(arrays, planes);
for( int i = 0; i < it.nplanes; i++, ++it ) size_t esz = elemSize();
it.planes[0].copyTo(it.planes[1], it.planes[2]); BinaryFunc copymask = getCopyMaskFunc(esz);
return;
} uchar* data0 = _dst.getMat().data;
_dst.create( dims, size, type() );
Mat dst = _dst.getMat();
uchar* data0 = dst.data;
dst.create( size(), type() );
if( dst.data != data0 ) // do not leave dst uninitialized if( dst.data != data0 ) // do not leave dst uninitialized
dst = Scalar(0); dst = Scalar(0);
getCopyMaskFunc((int)elemSize())(*this, dst, mask);
}
Mat& Mat::operator = (const Scalar& s) if( dims <= 2 )
{ {
if( dims > 2 ) Size sz = getContinuousSize(*this, dst, mask);
{ copymask(data, step, mask.data, mask.step, dst.data, dst.step, sz, &esz);
const Mat* arrays[] = { this, 0 }; return;
Mat planes[1];
NAryMatIterator it(arrays, planes);
for( int i = 0; i < it.nplanes; i++, ++it )
it.planes[0] = s;
return *this;
} }
Size sz = size(); const Mat* arrays[] = { this, &dst, &mask, 0 };
uchar* dst = data; uchar* ptrs[3];
NAryMatIterator it(arrays, ptrs);
Size sz((int)it.size, 1);
sz.width *= (int)elemSize(); for( size_t i = 0; i < it.nplanes; i++, ++it )
if( isContinuous() ) copymask(ptrs[0], 0, ptrs[2], 0, ptrs[1], 0, sz, &esz);
{
sz.width *= sz.height;
sz.height = 1;
} }
Mat& Mat::operator = (const Scalar& s)
{
const Mat* arrays[] = { this };
uchar* ptr;
NAryMatIterator it(arrays, &ptr, 1);
size_t size = it.size*elemSize();
if( s[0] == 0 && s[1] == 0 && s[2] == 0 && s[3] == 0 ) if( s[0] == 0 && s[1] == 0 && s[2] == 0 && s[3] == 0 )
{ {
for( ; sz.height--; dst += step ) for( size_t i = 0; i < it.nplanes; i++, ++it )
memset( dst, 0, sz.width ); memset( ptr, 0, size );
} }
else else
{ {
int t = type(), esz1 = (int)elemSize1(); if( it.nplanes > 0 )
{
double scalar[12]; double scalar[12];
scalarToRawData(s, scalar, t, 12); scalarToRawData(s, scalar, type(), 12);
int copy_len = 12*esz1; size_t blockSize = 12*elemSize1();
uchar* dst_limit = dst + sz.width;
if( sz.height-- ) for( size_t j = 0; j < size; j += blockSize )
{ {
while( dst + copy_len <= dst_limit ) size_t sz = std::min(blockSize, size - j);
{ memcpy( ptr + j, scalar, sz );
memcpy( dst, scalar, copy_len );
dst += copy_len;
} }
memcpy( dst, scalar, dst_limit - dst );
} }
if( sz.height > 0 ) for( size_t i = 1; i < it.nplanes; i++ )
{ {
dst = dst_limit - sz.width + step; ++it;
for( ; sz.height--; dst += step ) memcpy( ptr, data, size );
memcpy( dst, data, sz.width );
} }
} }
return *this; return *this;
} }
Mat& Mat::setTo(const Scalar& s, const Mat& mask) Mat& Mat::setTo(const Scalar& s, const InputArray& _mask)
{ {
Mat mask = _mask.getMat();
if( !mask.data ) if( !mask.data )
*this = s; *this = s;
else else
{ {
CV_Assert( channels() <= 4 ); CV_Assert( channels() <= 4 && mask.type() == CV_8U );
SetMaskFunc func = setMaskFuncTab[elemSize()]; size_t esz = elemSize();
CV_Assert( func != 0 ); BinaryFunc func = esz <= 32 ? setMaskTab[esz] : setMaskGeneric;
double buf[4]; double buf[4];
scalarToRawData(s, buf, type(), 0); scalarToRawData(s, buf, type(), 0);
if( dims > 2 )
{
const Mat* arrays[] = { this, &mask, 0 }; const Mat* arrays[] = { this, &mask, 0 };
Mat planes[2]; uchar* ptrs[2];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, ptrs);
Size sz((int)it.size, 1);
for( int i = 0; i < it.nplanes; i++, ++it ) for( size_t i = 0; i < it.nplanes; i++, ++it )
func(buf, it.planes[0], it.planes[1]); func((const uchar*)buf, 0, ptrs[1], 0, ptrs[0], 0, sz, &esz);
}
else
func(buf, *this, mask);
} }
return *this; return *this;
} }
template<typename T> static void static void
flipHoriz_( const Mat& srcmat, Mat& dstmat, bool flipv ) flipHoriz( const uchar* src, size_t sstep, uchar* dst, size_t dstep, Size size, size_t esz )
{ {
uchar* dst0 = dstmat.data; int i, j, limit = ((size.width + 1)/2)*esz;
size_t srcstep = srcmat.step; AutoBuffer<int> _tab(size.width*esz);
int dststep = (int)dstmat.step; int* tab = _tab;
Size size = srcmat.size();
if( flipv ) for( i = 0; i < size.width; i++ )
{ for( size_t k = 0; k < esz; k++ )
dst0 += (size.height - 1)*dststep; tab[i*esz + k] = (size.width - i - 1)*esz + k;
dststep = -dststep;
}
for( int y = 0; y < size.height; y++ ) for( ; size.height--; src += sstep, dst += dstep )
{ {
const T* src = (const T*)(srcmat.data + srcstep*y); for( i = 0; i < limit; i++ )
T* dst = (T*)(dst0 + dststep*y);
for( int i = 0; i < (size.width + 1)/2; i++ )
{ {
T t0 = src[i], t1 = src[size.width - i - 1]; j = tab[i];
dst[i] = t1; dst[size.width - i - 1] = t0; uchar t0 = src[i], t1 = src[j];
dst[i] = t1; dst[j] = t0;
} }
} }
} }
typedef void (*FlipHorizFunc)( const Mat& src, Mat& dst, bool flipv );
static void static void
flipVert( const Mat& srcmat, Mat& dstmat ) flipVert( const uchar* src0, size_t sstep, uchar* dst0, size_t dstep, Size size, size_t esz )
{ {
const uchar* src = srcmat.data; const uchar* src1 = src0 + (size.height - 1)*sstep;
uchar* dst = dstmat.data; uchar* dst1 = dst0 + (size.height - 1)*dstep;
size_t srcstep = srcmat.step, dststep = dstmat.step; size.width *= (int)esz;
Size size = srcmat.size();
const uchar* src1 = src + (size.height - 1)*srcstep;
uchar* dst1 = dst + (size.height - 1)*dststep;
size.width *= (int)srcmat.elemSize();
for( int y = 0; y < (size.height + 1)/2; y++, src += srcstep, src1 -= srcstep, for( int y = 0; y < (size.height + 1)/2; y++, src0 += sstep, src1 -= sstep,
dst += dststep, dst1 -= dststep ) dst0 += dstep, dst1 -= dstep )
{ {
int i = 0; int i = 0;
if( ((size_t)(src)|(size_t)(dst)|(size_t)src1|(size_t)dst1) % sizeof(int) == 0 ) if( ((size_t)src0|(size_t)dst0|(size_t)src1|(size_t)dst1) % sizeof(int) == 0 )
{ {
for( ; i <= size.width - 16; i += 16 ) for( ; i <= size.width - 16; i += 16 )
{ {
int t0 = ((int*)(src + i))[0]; int t0 = ((int*)(src0 + i))[0];
int t1 = ((int*)(src1 + i))[0]; int t1 = ((int*)(src1 + i))[0];
((int*)(dst + i))[0] = t1; ((int*)(dst0 + i))[0] = t1;
((int*)(dst1 + i))[0] = t0; ((int*)(dst1 + i))[0] = t0;
t0 = ((int*)(src + i))[1]; t0 = ((int*)(src0 + i))[1];
t1 = ((int*)(src1 + i))[1]; t1 = ((int*)(src1 + i))[1];
((int*)(dst + i))[1] = t1; ((int*)(dst0 + i))[1] = t1;
((int*)(dst1 + i))[1] = t0; ((int*)(dst1 + i))[1] = t0;
t0 = ((int*)(src + i))[2]; t0 = ((int*)(src0 + i))[2];
t1 = ((int*)(src1 + i))[2]; t1 = ((int*)(src1 + i))[2];
((int*)(dst + i))[2] = t1; ((int*)(dst0 + i))[2] = t1;
((int*)(dst1 + i))[2] = t0; ((int*)(dst1 + i))[2] = t0;
t0 = ((int*)(src + i))[3]; t0 = ((int*)(src0 + i))[3];
t1 = ((int*)(src1 + i))[3]; t1 = ((int*)(src1 + i))[3];
((int*)(dst + i))[3] = t1; ((int*)(dst0 + i))[3] = t1;
((int*)(dst1 + i))[3] = t0; ((int*)(dst1 + i))[3] = t0;
} }
for( ; i <= size.width - 4; i += 4 ) for( ; i <= size.width - 4; i += 4 )
{ {
int t0 = ((int*)(src + i))[0]; int t0 = ((int*)(src0 + i))[0];
int t1 = ((int*)(src1 + i))[0]; int t1 = ((int*)(src1 + i))[0];
((int*)(dst + i))[0] = t1; ((int*)(dst0 + i))[0] = t1;
((int*)(dst1 + i))[0] = t0; ((int*)(dst1 + i))[0] = t0;
} }
} }
for( ; i < size.width; i++ ) for( ; i < size.width; i++ )
{ {
uchar t0 = src[i]; uchar t0 = src0[i];
uchar t1 = src1[i]; uchar t1 = src1[i];
dst[i] = t1; dst0[i] = t1;
dst1[i] = t0; dst1[i] = t0;
} }
} }
} }
void flip( const Mat& src, Mat& dst, int flip_mode ) void flip( const InputArray& _src, OutputArray _dst, int flip_mode )
{
static FlipHorizFunc tab[] =
{ {
0, Mat src = _src.getMat();
flipHoriz_<uchar>, // 1
flipHoriz_<ushort>, // 2
flipHoriz_<Vec<uchar,3> >, // 3
flipHoriz_<int>, // 4
0,
flipHoriz_<Vec<ushort,3> >, // 6
0,
flipHoriz_<Vec<int,2> >, // 8
0, 0, 0,
flipHoriz_<Vec<int,3> >, // 12
0, 0, 0,
flipHoriz_<Vec<int,4> >, // 16
0, 0, 0, 0, 0, 0, 0,
flipHoriz_<Vec<int,6> >, // 24
0, 0, 0, 0, 0, 0, 0,
flipHoriz_<Vec<int,8> > // 32
};
CV_Assert( src.dims <= 2 ); CV_Assert( src.dims <= 2 );
dst.create( src.size(), src.type() ); _dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();
size_t esz = src.elemSize();
if( flip_mode == 0 ) if( flip_mode <= 0 )
flipVert( src, dst ); flipVert( src.data, src.step, dst.data, dst.step, src.size(), esz );
else
{
int esz = (int)src.elemSize();
CV_Assert( esz <= 32 );
FlipHorizFunc func = tab[esz];
CV_Assert( func != 0 );
if( flip_mode > 0 )
func( src, dst, false );
else if( src.data != dst.data )
func( src, dst, true );
else else
{ flipHoriz( src.data, src.step, dst.data, dst.step, src.size(), esz );
func( dst, dst, false );
flipVert( dst, dst ); if( flip_mode < 0 )
} flipHoriz( dst.data, dst.step, dst.data, dst.step, dst.size(), esz );
}
} }
void repeat(const Mat& src, int ny, int nx, Mat& dst) void repeat(const InputArray& _src, int ny, int nx, OutputArray _dst)
{ {
Mat src = _src.getMat();
CV_Assert( src.dims <= 2 ); CV_Assert( src.dims <= 2 );
dst.create(src.rows*ny, src.cols*nx, src.type()); _dst.create(src.rows*ny, src.cols*nx, src.type());
Mat dst = _dst.getMat();
Size ssize = src.size(), dsize = dst.size(); Size ssize = src.size(), dsize = dst.size();
int esz = (int)src.elemSize(); int esz = (int)src.elemSize();
int x, y; int x, y;
@ -524,7 +526,7 @@ cvCopy( const void* srcarr, void* dstarr, const void* maskarr )
{ {
CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap ); CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap );
int tabidx = node->hashval & (dst1->hashsize - 1); int tabidx = node->hashval & (dst1->hashsize - 1);
CV_MEMCPY_AUTO( node_copy, node, dst1->heap->elem_size ); memcpy( node_copy, node, dst1->heap->elem_size );
node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx]; node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx];
dst1->hashtable[tabidx] = node_copy; dst1->hashtable[tabidx] = node_copy;
} }

@ -1146,7 +1146,7 @@ cvSeqPush( CvSeq *seq, const void *element )
} }
if( element ) if( element )
CV_MEMCPY_AUTO( ptr, element, elem_size ); memcpy( ptr, element, elem_size );
seq->first->prev->count++; seq->first->prev->count++;
seq->total++; seq->total++;
seq->ptr = ptr + elem_size; seq->ptr = ptr + elem_size;
@ -1171,7 +1171,7 @@ cvSeqPop( CvSeq *seq, void *element )
seq->ptr = ptr = seq->ptr - elem_size; seq->ptr = ptr = seq->ptr - elem_size;
if( element ) if( element )
CV_MEMCPY_AUTO( element, ptr, elem_size ); memcpy( element, ptr, elem_size );
seq->ptr = ptr; seq->ptr = ptr;
seq->total--; seq->total--;
@ -1208,7 +1208,7 @@ cvSeqPushFront( CvSeq *seq, const void *element )
ptr = block->data -= elem_size; ptr = block->data -= elem_size;
if( element ) if( element )
CV_MEMCPY_AUTO( ptr, element, elem_size ); memcpy( ptr, element, elem_size );
block->count++; block->count++;
block->start_index--; block->start_index--;
seq->total++; seq->total++;
@ -1233,7 +1233,7 @@ cvSeqPopFront( CvSeq *seq, void *element )
block = seq->first; block = seq->first;
if( element ) if( element )
CV_MEMCPY_AUTO( element, block->data, elem_size ); memcpy( element, block->data, elem_size );
block->data += elem_size; block->data += elem_size;
block->start_index++; block->start_index++;
seq->total--; seq->total--;
@ -1708,7 +1708,7 @@ cvSeqRemoveSlice( CvSeq* seq, CvSlice slice )
for( i = 0; i < count; i++ ) for( i = 0; i < count; i++ )
{ {
CV_MEMCPY_AUTO( reader_to.ptr, reader_from.ptr, elem_size ); memcpy( reader_to.ptr, reader_from.ptr, elem_size );
CV_NEXT_SEQ_ELEM( elem_size, reader_to ); CV_NEXT_SEQ_ELEM( elem_size, reader_to );
CV_NEXT_SEQ_ELEM( elem_size, reader_from ); CV_NEXT_SEQ_ELEM( elem_size, reader_from );
} }
@ -1726,7 +1726,7 @@ cvSeqRemoveSlice( CvSeq* seq, CvSlice slice )
CV_PREV_SEQ_ELEM( elem_size, reader_to ); CV_PREV_SEQ_ELEM( elem_size, reader_to );
CV_PREV_SEQ_ELEM( elem_size, reader_from ); CV_PREV_SEQ_ELEM( elem_size, reader_from );
CV_MEMCPY_AUTO( reader_to.ptr, reader_from.ptr, elem_size ); memcpy( reader_to.ptr, reader_from.ptr, elem_size );
} }
cvSeqPopMulti( seq, 0, slice.end_index - slice.start_index, 1 ); cvSeqPopMulti( seq, 0, slice.end_index - slice.start_index, 1 );
@ -1796,7 +1796,7 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
for( i = 0; i < index; i++ ) for( i = 0; i < index; i++ )
{ {
CV_MEMCPY_AUTO( reader_to.ptr, reader_from.ptr, elem_size ); memcpy( reader_to.ptr, reader_from.ptr, elem_size );
CV_NEXT_SEQ_ELEM( elem_size, reader_to ); CV_NEXT_SEQ_ELEM( elem_size, reader_to );
CV_NEXT_SEQ_ELEM( elem_size, reader_from ); CV_NEXT_SEQ_ELEM( elem_size, reader_from );
} }
@ -1814,7 +1814,7 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
{ {
CV_PREV_SEQ_ELEM( elem_size, reader_to ); CV_PREV_SEQ_ELEM( elem_size, reader_to );
CV_PREV_SEQ_ELEM( elem_size, reader_from ); CV_PREV_SEQ_ELEM( elem_size, reader_from );
CV_MEMCPY_AUTO( reader_to.ptr, reader_from.ptr, elem_size ); memcpy( reader_to.ptr, reader_from.ptr, elem_size );
} }
} }
@ -1823,7 +1823,7 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
for( i = 0; i < from_total; i++ ) for( i = 0; i < from_total; i++ )
{ {
CV_MEMCPY_AUTO( reader_to.ptr, reader_from.ptr, elem_size ); memcpy( reader_to.ptr, reader_from.ptr, elem_size );
CV_NEXT_SEQ_ELEM( elem_size, reader_to ); CV_NEXT_SEQ_ELEM( elem_size, reader_to );
CV_NEXT_SEQ_ELEM( elem_size, reader_from ); CV_NEXT_SEQ_ELEM( elem_size, reader_from );
} }
@ -2525,7 +2525,7 @@ cvSetAdd( CvSet* set, CvSetElem* element, CvSetElem** inserted_element )
id = free_elem->flags & CV_SET_ELEM_IDX_MASK; id = free_elem->flags & CV_SET_ELEM_IDX_MASK;
if( element ) if( element )
CV_MEMCPY_INT( free_elem, element, (size_t)set->elem_size/sizeof(int) ); memcpy( free_elem, element, set->elem_size );
free_elem->flags = id; free_elem->flags = id;
set->active_count++; set->active_count++;
@ -2616,8 +2616,7 @@ cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* _vertex, CvGraphVtx** _inserted
if( vertex ) if( vertex )
{ {
if( _vertex ) if( _vertex )
CV_MEMCPY_INT( vertex + 1, _vertex + 1, memcpy( vertex + 1, _vertex + 1, graph->elem_size - sizeof(CvGraphVtx) );
(size_t)(graph->elem_size - sizeof(CvGraphVtx))/sizeof(int) );
vertex->first = 0; vertex->first = 0;
index = vertex->flags; index = vertex->flags;
} }
@ -2784,17 +2783,17 @@ cvGraphAddEdgeByPtr( CvGraph* graph,
edge->next[1] = end_vtx->first; edge->next[1] = end_vtx->first;
start_vtx->first = end_vtx->first = edge; start_vtx->first = end_vtx->first = edge;
delta = (graph->edges->elem_size - sizeof(*edge))/sizeof(int); delta = graph->edges->elem_size - sizeof(*edge);
if( _edge ) if( _edge )
{ {
if( delta > 0 ) if( delta > 0 )
CV_MEMCPY_INT( edge + 1, _edge + 1, delta ); memcpy( edge + 1, _edge + 1, delta );
edge->weight = _edge->weight; edge->weight = _edge->weight;
} }
else else
{ {
if( delta > 0 ) if( delta > 0 )
CV_ZERO_INT( edge + 1, delta ); memset( edge + 1, 0, delta );
edge->weight = 1.f; edge->weight = 1.f;
} }
@ -3548,14 +3547,14 @@ KDTree::KDTree()
normType = NORM_L2; normType = NORM_L2;
} }
KDTree::KDTree(const Mat& _points, bool _copyData) KDTree::KDTree(const InputArray& _points, bool _copyData)
{ {
maxDepth = -1; maxDepth = -1;
normType = NORM_L2; normType = NORM_L2;
build(_points, _copyData); build(_points, _copyData);
} }
KDTree::KDTree(const Mat& _points, const Mat& _labels, bool _copyData) KDTree::KDTree(const InputArray& _points, const InputArray& _labels, bool _copyData)
{ {
maxDepth = -1; maxDepth = -1;
normType = NORM_L2; normType = NORM_L2;
@ -3638,14 +3637,15 @@ computeSums( const Mat& points, const size_t* ofs, int a, int b, double* sums )
} }
void KDTree::build(const Mat& _points, bool _copyData) void KDTree::build(const InputArray& _points, bool _copyData)
{ {
build(_points, Mat(), _copyData); build(_points, InputArray(), _copyData);
} }
void KDTree::build(const Mat& _points, const Mat& _labels, bool _copyData) void KDTree::build(const InputArray& __points, const InputArray& __labels, bool _copyData)
{ {
Mat _points = __points.getMat(), _labels = __labels.getMat();
CV_Assert(_points.type() == CV_32F && !_points.empty()); CV_Assert(_points.type() == CV_32F && !_points.empty());
vector<KDTree::Node>().swap(nodes); vector<KDTree::Node>().swap(nodes);
@ -3744,57 +3744,6 @@ void KDTree::build(const Mat& _points, const Mat& _labels, bool _copyData)
} }
int KDTree::findNearest(const float* vec, int K, int emax,
vector<int>* neighborsIdx,
Mat* neighbors,
vector<float>* dist,
vector<int>* labels) const
{
K = std::min(K, points.rows);
CV_Assert(K > 0);
if(neighborsIdx)
neighborsIdx->resize(K);
if(dist)
dist->resize(K);
if(labels)
labels->resize(K);
K = findNearest(vec, K, emax, neighborsIdx ? &(*neighborsIdx)[0] : 0,
neighbors, dist ? &(*dist)[0] : 0, labels ? &(*labels)[0] : 0);
if(neighborsIdx)
neighborsIdx->resize(K);
if(dist)
dist->resize(K);
if(labels)
labels->resize(K);
return K;
}
int KDTree::findNearest(const vector<float>& vec, int K, int emax,
vector<int>* neighborsIdx,
Mat* neighbors,
vector<float>* dist,
vector<int>* labels) const
{
CV_Assert((int)vec.size() == points.cols);
K = std::min(K, points.rows);
CV_Assert(K > 0);
if(neighborsIdx)
neighborsIdx->resize(K);
if(dist)
dist->resize(K);
if(labels)
labels->resize(K);
K = findNearest(&vec[0], K, emax, neighborsIdx ? &(*neighborsIdx)[0] : 0,
neighbors, dist ? &(*dist)[0] : 0, labels ? &(*labels)[0] : 0);
if(neighborsIdx)
neighborsIdx->resize(K);
if(dist)
dist->resize(K);
if(labels)
labels->resize(K);
return K;
}
struct PQueueElem struct PQueueElem
{ {
PQueueElem() : dist(0), idx(0) {} PQueueElem() : dist(0), idx(0) {}
@ -3804,11 +3753,14 @@ struct PQueueElem
}; };
int KDTree::findNearest(const float* vec, int K, int emax, int KDTree::findNearest(const InputArray& _vec, int K, int emax,
int* _neighborsIdx, Mat* _neighbors, OutputArray _neighborsIdx, OutputArray _neighbors,
float* _dist, int* _labels) const OutputArray _dist, OutputArray _labels) const
{ {
Mat vecmat = _vec.getMat();
CV_Assert( vecmat.isContinuous() && vecmat.type() == CV_32F && vecmat.total() == (size_t)points.cols );
const float* vec = vecmat.ptr<float>();
K = std::min(K, points.rows); K = std::min(K, points.rows);
int dims = points.cols; int dims = points.cols;
@ -3929,42 +3881,43 @@ int KDTree::findNearest(const float* vec, int K, int emax,
} }
K = std::min(K, ncount); K = std::min(K, ncount);
if( _neighborsIdx ) if( _neighborsIdx.needed() )
{
for( i = 0; i < K; i++ )
_neighborsIdx[i] = idx[i];
}
if( _dist )
{
for( i = 0; i < K; i++ )
_dist[i] = std::sqrt(dist[i]);
}
if( _labels )
{ {
for( i = 0; i < K; i++ ) _neighborsIdx.create(K, 1, CV_32S, -1, true);
_labels[i] = labels[idx[i]]; Mat nidx = _neighborsIdx.getMat();
Mat(nidx.size(), CV_32S, &idx[0]).copyTo(nidx);
} }
if( _dist.needed() )
sqrt(Mat(K, 1, CV_32F, dist), _dist);
if( _neighbors ) if( _neighbors.needed() || _labels.needed() )
getPoints(idx, K, *_neighbors); getPoints(Mat(K, 1, CV_32S, idx), _neighbors, _labels);
return K; return K;
} }
void KDTree::findOrthoRange(const float* L, const float* R, void KDTree::findOrthoRange(const InputArray& _lowerBound,
vector<int>* neighborsIdx, const InputArray& _upperBound,
Mat* neighbors, vector<int>* _labels) const OutputArray _neighborsIdx,
OutputArray _neighbors,
OutputArray _labels ) const
{ {
int dims = points.cols; int dims = points.cols;
Mat lowerBound = _lowerBound.getMat(), upperBound = _upperBound.getMat();
CV_Assert( L && R ); CV_Assert( lowerBound.size == upperBound.size &&
lowerBound.isContinuous() &&
vector<int> _idx, *idx = neighborsIdx ? neighborsIdx : &_idx; upperBound.isContinuous() &&
lowerBound.type() == upperBound.type() &&
lowerBound.type() == CV_32F &&
lowerBound.total() == (size_t)dims );
const float* L = lowerBound.ptr<float>();
const float* R = upperBound.ptr<float>();
vector<int> idx;
AutoBuffer<int> _stack(MAX_TREE_DEPTH*2 + 1); AutoBuffer<int> _stack(MAX_TREE_DEPTH*2 + 1);
int* stack = _stack; int* stack = _stack;
int top = 0; int top = 0;
idx->clear();
stack[top++] = 0; stack[top++] = 0;
while( --top >= 0 ) while( --top >= 0 )
@ -3981,7 +3934,7 @@ void KDTree::findOrthoRange(const float* L, const float* R,
if( row[j] < L[j] || row[j] >= R[j] ) if( row[j] < L[j] || row[j] >= R[j] )
break; break;
if( j == dims ) if( j == dims )
idx->push_back(i); idx.push_back(i);
continue; continue;
} }
if( L[n.idx] <= n.boundary ) if( L[n.idx] <= n.boundary )
@ -3990,55 +3943,57 @@ void KDTree::findOrthoRange(const float* L, const float* R,
stack[top++] = n.right; stack[top++] = n.right;
} }
if( neighbors ) if( _neighborsIdx.needed() )
getPoints( &(*idx)[0], idx->size(), *neighbors, _labels );
}
void KDTree::findOrthoRange(const vector<float>& L, const vector<float>& R,
vector<int>* neighborsIdx, Mat* neighbors, vector<int>* _labels) const
{ {
size_t dims = points.cols; _neighborsIdx.create(idx.size(), 1, CV_32S, -1, true);
CV_Assert(L.size() == dims && R.size() == dims); Mat nidx = _neighborsIdx.getMat();
findOrthoRange(&L[0], &R[0], neighborsIdx, neighbors, _labels); Mat(nidx.size(), CV_32S, &idx[0]).copyTo(nidx);
}
getPoints( idx, _neighbors, _labels );
} }
void KDTree::getPoints(const int* idx, size_t nidx, Mat& pts, vector<int>* _labels) const void KDTree::getPoints(const InputArray& _idx, OutputArray _pts, OutputArray _labels) const
{ {
int dims = points.cols, n = (int)nidx; Mat idxmat = _idx.getMat(), pts, labelsmat;
pts.create( n, dims, points.type()); CV_Assert( idxmat.isContinuous() && idxmat.type() == CV_32S &&
if(_labels) (idxmat.cols == 1 || idxmat.rows == 1) );
_labels->resize(nidx); const int* idx = idxmat.ptr<int>();
int* dstlabels = 0;
for( int i = 0; i < n; i++ ) int dims = points.cols;
int i, nidx = (int)idxmat.total();
if( nidx == 0 )
{ {
int k = idx[i]; _pts.release();
CV_Assert( (unsigned)k < (unsigned)points.rows ); _labels.release();
const float* src = points.ptr<float>(k); return;
std::copy(src, src + dims, pts.ptr<float>(i));
if(_labels)
(*_labels)[i] = labels[k];
}
} }
if( _pts.needed() )
void KDTree::getPoints(const vector<int>& idx, Mat& pts, vector<int>* _labels) const
{ {
int dims = points.cols; _pts.create( nidx, dims, points.type());
int i, nidx = (int)idx.size(); pts = _pts.getMat();
pts.create( nidx, dims, points.type()); }
if(_labels) if(_labels.needed())
_labels->resize(nidx); {
_labels.create(nidx, 1, CV_32S, -1, true);
labelsmat = _labels.getMat();
CV_Assert( labelsmat.isContinuous() );
dstlabels = labelsmat.ptr<int>();
}
const int* srclabels = !labels.empty() ? &labels[0] : 0;
for( i = 0; i < nidx; i++ ) for( i = 0; i < nidx; i++ )
{ {
int k = idx[i]; int k = idx[i];
CV_Assert( (unsigned)k < (unsigned)points.rows ); CV_Assert( (unsigned)k < (unsigned)points.rows );
const float* src = points.ptr<float>(k); const float* src = points.ptr<float>(k);
if( pts.data )
std::copy(src, src + dims, pts.ptr<float>(i)); std::copy(src, src + dims, pts.ptr<float>(i));
if(_labels) (*_labels)[i] = labels[k]; if( dstlabels )
dstlabels[i] = srclabels ? srclabels[k] : k;
} }
} }
@ -4047,7 +4002,7 @@ const float* KDTree::getPoint(int ptidx, int* label) const
{ {
CV_Assert( (unsigned)ptidx < (unsigned)points.rows); CV_Assert( (unsigned)ptidx < (unsigned)points.rows);
if(label) if(label)
*label = label[ptidx]; *label = labels[ptidx];
return points.ptr<float>(ptidx); return points.ptr<float>(ptidx);
} }

@ -235,7 +235,7 @@ LineIterator::LineIterator(const Mat& img, Point pt1, Point pt2,
static void static void
Line( Mat& img, Point pt1, Point pt2, Line( Mat& img, Point pt1, Point pt2,
const void* color, int connectivity = 8 ) const void* _color, int connectivity = 8 )
{ {
if( connectivity == 0 ) if( connectivity == 0 )
connectivity = 8; connectivity = 8;
@ -245,10 +245,21 @@ Line( Mat& img, Point pt1, Point pt2,
LineIterator iterator(img, pt1, pt2, connectivity, true); LineIterator iterator(img, pt1, pt2, connectivity, true);
int i, count = iterator.count; int i, count = iterator.count;
int pix_size = (int)img.elemSize(); int pix_size = (int)img.elemSize();
const uchar* color = (const uchar*)_color;
for( i = 0; i < count; i++, ++iterator ) for( i = 0; i < count; i++, ++iterator )
{ {
CV_MEMCPY_AUTO( *iterator, color, pix_size ); uchar* ptr = *iterator;
if( pix_size == 1 )
ptr[0] = color[0];
else if( pix_size == 3 )
{
ptr[0] = color[0];
ptr[1] = color[1];
ptr[2] = color[2];
}
else
memcpy( *iterator, color, pix_size );
} }
} }
@ -1317,7 +1328,7 @@ Circle( Mat& img, Point center, int radius, const void* color, int fill )
center.y >= radius && center.y < size.height - radius; center.y >= radius && center.y < size.height - radius;
#define ICV_PUT_POINT( ptr, x ) \ #define ICV_PUT_POINT( ptr, x ) \
CV_MEMCPY_CHAR( ptr + (x)*pix_size, color, pix_size ); memcpy( ptr + (x)*pix_size, color, pix_size );
while( dx >= dy ) while( dx >= dy )
{ {

@ -1449,27 +1449,25 @@ static void CCSIDFT_64f( const double* src, double* dst, int n, int nf, int* fac
CCSIDFT( src, dst, n, nf, factors, itab, wave, tab_size, spec, buf, flags, scale); CCSIDFT( src, dst, n, nf, factors, itab, wave, tab_size, spec, buf, flags, scale);
} }
}
void dft( const Mat& src0, Mat& dst, int flags, int nonzero_rows )
{
static DFTFunc dft_tbl[6];
static int inittab = 0;
if( !inittab ) void cv::dft( const InputArray& _src0, OutputArray _dst, int flags, int nonzero_rows )
{ {
dft_tbl[0] = (DFTFunc)DFT_32f; static DFTFunc dft_tbl[6] =
dft_tbl[1] = (DFTFunc)RealDFT_32f; {
dft_tbl[2] = (DFTFunc)CCSIDFT_32f; (DFTFunc)DFT_32f,
dft_tbl[3] = (DFTFunc)DFT_64f; (DFTFunc)RealDFT_32f,
dft_tbl[4] = (DFTFunc)RealDFT_64f; (DFTFunc)CCSIDFT_32f,
dft_tbl[5] = (DFTFunc)CCSIDFT_64f; (DFTFunc)DFT_64f,
inittab = 1; (DFTFunc)RealDFT_64f,
} (DFTFunc)CCSIDFT_64f
};
AutoBuffer<uchar> buf; AutoBuffer<uchar> buf;
void *spec = 0; void *spec = 0;
Mat src = src0; Mat src0 = _src0.getMat(), src = src0;
int prev_len = 0, stage = 0; int prev_len = 0, stage = 0;
bool inv = (flags & DFT_INVERSE) != 0; bool inv = (flags & DFT_INVERSE) != 0;
int nf = 0, real_transform = src.channels() == 1 || (inv && (flags & DFT_REAL_OUTPUT)!=0); int nf = 0, real_transform = src.channels() == 1 || (inv && (flags & DFT_REAL_OUTPUT)!=0);
@ -1485,11 +1483,13 @@ void dft( const Mat& src0, Mat& dst, int flags, int nonzero_rows )
CV_Assert( type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2 ); CV_Assert( type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2 );
if( !inv && src.channels() == 1 && (flags & DFT_COMPLEX_OUTPUT) ) if( !inv && src.channels() == 1 && (flags & DFT_COMPLEX_OUTPUT) )
dst.create( src.size(), CV_MAKETYPE(depth, 2) ); _dst.create( src.size(), CV_MAKETYPE(depth, 2) );
else if( inv && src.channels() == 2 && (flags & DFT_REAL_OUTPUT) ) else if( inv && src.channels() == 2 && (flags & DFT_REAL_OUTPUT) )
dst.create( src.size(), depth ); _dst.create( src.size(), depth );
else else
dst.create( src.size(), type ); _dst.create( src.size(), type );
Mat dst = _dst.getMat();
if( !real_transform ) if( !real_transform )
elem_size = complex_elem_size; elem_size = complex_elem_size;
@ -1840,14 +1840,15 @@ void dft( const Mat& src0, Mat& dst, int flags, int nonzero_rows )
} }
void idft( const Mat& src, Mat& dst, int flags, int nonzero_rows ) void cv::idft( const InputArray& src, OutputArray dst, int flags, int nonzero_rows )
{ {
dft( src, dst, flags | DFT_INVERSE, nonzero_rows ); dft( src, dst, flags | DFT_INVERSE, nonzero_rows );
} }
void mulSpectrums( const Mat& srcA, const Mat& srcB, void cv::mulSpectrums( const InputArray& _srcA, const InputArray& _srcB,
Mat& dst, int flags, bool conjB ) OutputArray _dst, int flags, bool conjB )
{ {
Mat srcA = _srcA.getMat(), srcB = _srcB.getMat();
int depth = srcA.depth(), cn = srcA.channels(), type = srcA.type(); int depth = srcA.depth(), cn = srcA.channels(), type = srcA.type();
int rows = srcA.rows, cols = srcA.cols; int rows = srcA.rows, cols = srcA.cols;
int j, k; int j, k;
@ -1855,7 +1856,8 @@ void mulSpectrums( const Mat& srcA, const Mat& srcB,
CV_Assert( type == srcB.type() && srcA.size() == srcB.size() ); CV_Assert( type == srcB.type() && srcA.size() == srcB.size() );
CV_Assert( type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2 ); CV_Assert( type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2 );
dst.create( srcA.rows, srcA.cols, type ); _dst.create( srcA.rows, srcA.cols, type );
Mat dst = _dst.getMat();
bool is_1d = (flags & DFT_ROWS) || (rows == 1 || (cols == 1 && bool is_1d = (flags & DFT_ROWS) || (rows == 1 || (cols == 1 &&
srcA.isContinuous() && srcB.isContinuous() && dst.isContinuous())); srcA.isContinuous() && srcB.isContinuous() && dst.isContinuous()));
@ -2008,6 +2010,9 @@ void mulSpectrums( const Mat& srcA, const Mat& srcB,
Discrete Cosine Transform Discrete Cosine Transform
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
/* DCT is calculated using DFT, as described here: /* DCT is calculated using DFT, as described here:
http://www.ece.utexas.edu/~bevans/courses/ee381k/lectures/09_DCT/lecture9/: http://www.ece.utexas.edu/~bevans/courses/ee381k/lectures/09_DCT/lecture9/:
*/ */
@ -2211,22 +2216,20 @@ static void IDCT_64f(const double* src, int src_step, double* dft_src, double* d
n, nf, factors, itab, dft_wave, dct_wave, spec, buf); n, nf, factors, itab, dft_wave, dct_wave, spec, buf);
} }
void dct( const Mat& src0, Mat& dst, int flags ) }
{
static DCTFunc dct_tbl[4];
static int inittab = 0;
if( !inittab ) void cv::dct( const InputArray& _src0, OutputArray _dst, int flags )
{ {
dct_tbl[0] = (DCTFunc)DCT_32f; static DCTFunc dct_tbl[4] =
dct_tbl[1] = (DCTFunc)IDCT_32f; {
dct_tbl[2] = (DCTFunc)DCT_64f; (DCTFunc)DCT_32f,
dct_tbl[3] = (DCTFunc)IDCT_64f; (DCTFunc)IDCT_32f,
inittab = 1; (DCTFunc)DCT_64f,
} (DCTFunc)IDCT_64f
};
bool inv = (flags & DCT_INVERSE) != 0; bool inv = (flags & DCT_INVERSE) != 0;
Mat src = src0; Mat src0 = _src0.getMat(), src = src0;
int type = src.type(), depth = src.depth(); int type = src.type(), depth = src.depth();
void /* *spec_dft = 0, */ *spec = 0; void /* *spec_dft = 0, */ *spec = 0;
@ -2242,7 +2245,8 @@ void dct( const Mat& src0, Mat& dst, int flags )
AutoBuffer<uchar> buf; AutoBuffer<uchar> buf;
CV_Assert( type == CV_32FC1 || type == CV_64FC1 ); CV_Assert( type == CV_32FC1 || type == CV_64FC1 );
dst.create( src.rows, src.cols, type ); _dst.create( src.rows, src.cols, type );
Mat dst = _dst.getMat();
DCTFunc dct_func = dct_tbl[inv + (depth == CV_64F)*2]; DCTFunc dct_func = dct_tbl[inv + (depth == CV_64F)*2];
@ -2369,11 +2373,14 @@ void dct( const Mat& src0, Mat& dst, int flags )
} }
void idct( const Mat& src, Mat& dst, int flags ) void cv::idct( const InputArray& src, OutputArray dst, int flags )
{ {
dct( src, dst, flags | DCT_INVERSE ); dct( src, dst, flags | DCT_INVERSE );
} }
namespace cv
{
static const int optimalDFTSizeTab[] = { static const int optimalDFTSizeTab[] = {
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48,
50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160,
@ -2555,8 +2562,9 @@ static const int optimalDFTSizeTab[] = {
2097152000, 2099520000, 2109375000, 2123366400, 2125764000 2097152000, 2099520000, 2109375000, 2123366400, 2125764000
}; };
int }
getOptimalDFTSize( int size0 )
int cv::getOptimalDFTSize( int size0 )
{ {
int a = 0, b = sizeof(optimalDFTSizeTab)/sizeof(optimalDFTSizeTab[0]) - 1; int a = 0, b = sizeof(optimalDFTSizeTab)/sizeof(optimalDFTSizeTab[0]) - 1;
if( (unsigned)size0 >= (unsigned)optimalDFTSizeTab[b] ) if( (unsigned)size0 >= (unsigned)optimalDFTSizeTab[b] )
@ -2574,8 +2582,6 @@ getOptimalDFTSize( int size0 )
return optimalDFTSizeTab[b]; return optimalDFTSizeTab[b];
} }
}
CV_IMPL void CV_IMPL void
cvDFT( const CvArr* srcarr, CvArr* dstarr, int flags, int nonzero_rows ) cvDFT( const CvArr* srcarr, CvArr* dstarr, int flags, int nonzero_rows )
{ {

@ -213,6 +213,8 @@ bool Cholesky(double* A, int m, double* b, int n)
return CholImpl(A, m, b, n); return CholImpl(A, m, b, n);
} }
}
/****************************************************************************************\ /****************************************************************************************\
* Determinant of the matrix * * Determinant of the matrix *
\****************************************************************************************/ \****************************************************************************************/
@ -222,8 +224,9 @@ bool Cholesky(double* A, int m, double* b, int n)
m(0,1)*((double)m(1,0)*m(2,2) - (double)m(1,2)*m(2,0)) + \ m(0,1)*((double)m(1,0)*m(2,2) - (double)m(1,2)*m(2,0)) + \
m(0,2)*((double)m(1,0)*m(2,1) - (double)m(1,1)*m(2,0))) m(0,2)*((double)m(1,0)*m(2,1) - (double)m(1,1)*m(2,0)))
double determinant( const Mat& mat ) double cv::determinant( const InputArray& _mat )
{ {
Mat mat = _mat.getMat();
double result = 0; double result = 0;
int type = mat.type(), rows = mat.rows; int type = mat.type(), rows = mat.rows;
size_t step = mat.step; size_t step = mat.step;
@ -325,12 +328,15 @@ double determinant( const Mat& mat )
#define Df( y, x ) ((float*)(dstdata + y*dststep))[x] #define Df( y, x ) ((float*)(dstdata + y*dststep))[x]
#define Dd( y, x ) ((double*)(dstdata + y*dststep))[x] #define Dd( y, x ) ((double*)(dstdata + y*dststep))[x]
double invert( const Mat& src, Mat& dst, int method ) double cv::invert( const InputArray& _src, OutputArray _dst, int method )
{ {
double result = 0; double result = 0;
Mat src = _src.getMat();
int type = src.type(); int type = src.type();
CV_Assert( method == DECOMP_LU || method == DECOMP_CHOLESKY || method == DECOMP_SVD ); CV_Assert( method == DECOMP_LU || method == DECOMP_CHOLESKY || method == DECOMP_SVD );
_dst.create( src.cols, src.rows, type );
Mat dst = _dst.getMat();
if( method == DECOMP_SVD ) if( method == DECOMP_SVD )
{ {
@ -346,7 +352,6 @@ double invert( const Mat& src, Mat& dst, int method )
} }
CV_Assert( src.rows == src.cols && (type == CV_32F || type == CV_64F)); CV_Assert( src.rows == src.cols && (type == CV_32F || type == CV_64F));
dst.create( src.rows, src.cols, type );
if( src.rows <= 3 ) if( src.rows <= 3 )
{ {
@ -572,9 +577,10 @@ double invert( const Mat& src, Mat& dst, int method )
* Solving a linear system * * Solving a linear system *
\****************************************************************************************/ \****************************************************************************************/
bool solve( const Mat& src, const Mat& _src2, Mat& dst, int method ) bool cv::solve( const InputArray& _src, const InputArray& _src2arg, OutputArray _dst, int method )
{ {
bool result = true; bool result = true;
Mat src = _src.getMat(), _src2 = _src2arg.getMat();
int type = src.type(); int type = src.type();
bool is_normal = (method & DECOMP_NORMAL) != 0; bool is_normal = (method & DECOMP_NORMAL) != 0;
@ -588,7 +594,8 @@ bool solve( const Mat& src, const Mat& _src2, Mat& dst, int method )
if( (method == DECOMP_LU || method == DECOMP_CHOLESKY) && if( (method == DECOMP_LU || method == DECOMP_CHOLESKY) &&
src.rows <= 3 && src.rows == src.cols && _src2.cols == 1 ) src.rows <= 3 && src.rows == src.cols && _src2.cols == 1 )
{ {
dst.create( src.cols, _src2.cols, src.type() ); _dst.create( src.cols, _src2.cols, src.type() );
Mat dst = _dst.getMat();
#define bf(y) ((float*)(bdata + y*src2step))[0] #define bf(y) ((float*)(bdata + y*src2step))[0]
#define bd(y) ((double*)(bdata + y*src2step))[0] #define bd(y) ((double*)(bdata + y*src2step))[0]
@ -729,7 +736,8 @@ bool solve( const Mat& src, const Mat& _src2, Mat& dst, int method )
char N[] = {'N', '\0'}, L[] = {'L', '\0'}; char N[] = {'N', '\0'}, L[] = {'L', '\0'};
Mat src2 = _src2; Mat src2 = _src2;
dst.create( src.cols, src2.cols, src.type() ); _dst.create( src.cols, src2.cols, src.type() );
Mat dst = _dst.getMat();
if( m <= n ) if( m <= n )
is_normal = false; is_normal = false;
@ -905,6 +913,9 @@ bool solve( const Mat& src, const Mat& _src2, Mat& dst, int method )
/////////////////// finding eigenvalues and eigenvectors of a symmetric matrix /////////////// /////////////////// finding eigenvalues and eigenvectors of a symmetric matrix ///////////////
namespace cv
{
template<typename Real> static inline Real hypot(Real a, Real b) template<typename Real> static inline Real hypot(Real a, Real b)
{ {
a = std::abs(a); a = std::abs(a);
@ -1077,9 +1088,10 @@ template<typename Real> bool jacobi(const Mat& _S0, Mat& _e, Mat& matE, bool com
} }
static bool eigen( const Mat& src, Mat& evals, Mat& evects, bool computeEvects, static bool eigen( const InputArray& _src, OutputArray _evals, OutputArray _evects, bool computeEvects,
int lowindex, int highindex ) int lowindex, int highindex )
{ {
Mat src = _src.getMat();
int type = src.type(); int type = src.type();
integer n = src.rows; integer n = src.rows;
@ -1094,9 +1106,14 @@ static bool eigen( const Mat& src, Mat& evals, Mat& evects, bool computeEvects,
CV_Assert( src.rows == src.cols ); CV_Assert( src.rows == src.cols );
CV_Assert (type == CV_32F || type == CV_64F); CV_Assert (type == CV_32F || type == CV_64F);
// allow for 1xn eigenvalue matrix too _evals.create(n, 1, type, -1, true);
if( !(evals.rows == 1 && evals.cols == n && evals.type() == type) ) Mat evals = _evals.getMat(), evects;
evals.create(n, 1, type);
if( computeEvects )
{
_evects.create(n, n, type);
evects = _evects.getMat();
}
if( n <= 20 ) if( n <= 20 )
{ {
@ -1122,10 +1139,7 @@ static bool eigen( const Mat& src, Mat& evals, Mat& evects, bool computeEvects,
lda = (int)(src.step/elem_size); lda = (int)(src.step/elem_size);
if( computeEvects ) if( computeEvects )
{
evects.create(n, n, type);
ldv = (int)(evects.step/elem_size); ldv = (int)(evects.step/elem_size);
}
bool copy_evals = !evals.isContinuous(); bool copy_evals = !evals.isContinuous();
@ -1211,19 +1225,21 @@ static bool eigen( const Mat& src, Mat& evals, Mat& evects, bool computeEvects,
return result; return result;
} }
bool eigen( const Mat& src, Mat& evals, int lowindex, int highindex ) }
bool cv::eigen( const InputArray& src, OutputArray evals, int lowindex, int highindex )
{ {
Mat evects; return eigen(src, evals, OutputArray(), false, lowindex, highindex);
return eigen(src, evals, evects, false, lowindex, highindex);
} }
bool eigen( const Mat& src, Mat& evals, Mat& evects, int lowindex, bool cv::eigen( const InputArray& src, OutputArray evals, OutputArray evects,
int highindex ) int lowindex, int highindex )
{ {
return eigen(src, evals, evects, true, lowindex, highindex); return eigen(src, evals, evects, true, lowindex, highindex);
} }
namespace cv
{
/* y[0:m,0:n] += diag(a[0:1,0:m]) * x[0:m,0:n] */ /* y[0:m,0:n] += diag(a[0:1,0:m]) * x[0:m,0:n] */
template<typename T1, typename T2, typename T3> static void template<typename T1, typename T2, typename T3> static void
@ -1316,29 +1332,33 @@ SVBkSb( int m, int n, const T* w, int incw,
} }
static void _SVDcompute( const Mat& a, Mat& w, Mat* u, Mat* vt, int flags ) static void _SVDcompute( const InputArray& _aarr, OutputArray _w,
OutputArray _u, OutputArray _vt, int flags )
{ {
Mat a = _aarr.getMat(), u, vt;
integer m = a.rows, n = a.cols, mn = std::max(m, n), nm = std::min(m, n); integer m = a.rows, n = a.cols, mn = std::max(m, n), nm = std::min(m, n);
int type = a.type(), elem_size = (int)a.elemSize(); int type = a.type(), elem_size = (int)a.elemSize();
bool compute_uv = u && vt; bool compute_uv = _u.needed() || _vt.needed();
if( flags & SVD::NO_UV ) if( flags & SVD::NO_UV )
{ {
if(u) u->release(); _u.release();
if(vt) vt->release(); _vt.release();
u = vt = 0;
compute_uv = false; compute_uv = false;
} }
if( compute_uv ) if( compute_uv )
{ {
u->create( (int)m, (int)((flags & SVD::FULL_UV) ? m : nm), type ); _u.create( (int)m, (int)((flags & SVD::FULL_UV) ? m : nm), type );
vt->create( (int)((flags & SVD::FULL_UV) ? n : nm), n, type ); _vt.create( (int)((flags & SVD::FULL_UV) ? n : nm), n, type );
u = _u.getMat();
vt = _vt.getMat();
} }
w.create(nm, 1, type); _w.create(nm, 1, type, -1, true);
Mat _a = a; Mat _a = a, w = _w.getMat();
CV_Assert( w.isContinuous() );
int a_ofs = 0, work_ofs=0, iwork_ofs=0, buf_size = 0; int a_ofs = 0, work_ofs=0, iwork_ofs=0, buf_size = 0;
bool temp_a = false; bool temp_a = false;
double u1=0, v1=0, work1=0; double u1=0, v1=0, work1=0;
@ -1353,7 +1373,7 @@ static void _SVDcompute( const Mat& a, Mat& w, Mat* u, Mat* vt, int flags )
{ {
if( mode[0] == 'N' || mode[0] == 'A' ) if( mode[0] == 'N' || mode[0] == 'A' )
temp_a = true; temp_a = true;
else if( compute_uv && (a.size() == vt->size() || a.size() == u->size()) && mode[0] == 'S' ) else if( compute_uv && (a.size() == vt.size() || a.size() == u.size()) && mode[0] == 'S' )
mode[0] = 'O'; mode[0] = 'O';
} }
@ -1396,59 +1416,67 @@ static void _SVDcompute( const Mat& a, Mat& w, Mat* u, Mat* vt, int flags )
if( !(flags & SVD::MODIFY_A) && !temp_a ) if( !(flags & SVD::MODIFY_A) && !temp_a )
{ {
if( compute_uv && a.size() == vt->size() ) if( compute_uv && a.size() == vt.size() )
{ {
a.copyTo(*vt); a.copyTo(vt);
_a = *vt; _a = vt;
} }
else if( compute_uv && a.size() == u->size() ) else if( compute_uv && a.size() == u.size() )
{ {
a.copyTo(*u); a.copyTo(u);
_a = *u; _a = u;
} }
} }
if( compute_uv ) if( compute_uv )
{ {
ldv = (int)(vt->step ? vt->step/elem_size : vt->cols); ldv = (int)(vt.step ? vt.step/elem_size : vt.cols);
ldu = (int)(u->step ? u->step/elem_size : u->cols); ldu = (int)(u.step ? u.step/elem_size : u.cols);
} }
lda = (int)(_a.step ? _a.step/elem_size : _a.cols); lda = (int)(_a.step ? _a.step/elem_size : _a.cols);
if( type == CV_32F ) if( type == CV_32F )
{ {
sgesdd_(mode, &n, &m, (float*)_a.data, &lda, (float*)w.data, sgesdd_(mode, &n, &m, _a.ptr<float>(), &lda, w.ptr<float>(),
vt ? (float*)vt->data : (float*)&v1, &ldv, u ? (float*)u->data : (float*)&u1, &ldu, vt.data ? vt.ptr<float>() : (float*)&v1, &ldv,
(float*)(buffer + work_ofs), &lwork, (integer*)(buffer + iwork_ofs), &info ); u.data ? u.ptr<float>() : (float*)&u1, &ldu,
(float*)(buffer + work_ofs), &lwork,
(integer*)(buffer + iwork_ofs), &info );
} }
else else
{ {
dgesdd_(mode, &n, &m, (double*)_a.data, &lda, (double*)w.data, dgesdd_(mode, &n, &m, _a.ptr<double>(), &lda, w.ptr<double>(),
vt ? (double*)vt->data : &v1, &ldv, u ? (double*)u->data : &u1, &ldu, vt.data ? vt.ptr<double>() : &v1, &ldv,
(double*)(buffer + work_ofs), &lwork, (integer*)(buffer + iwork_ofs), &info ); u.data ? u.ptr<double>() : &u1, &ldu,
(double*)(buffer + work_ofs), &lwork,
(integer*)(buffer + iwork_ofs), &info );
} }
CV_Assert(info >= 0); CV_Assert(info >= 0);
if(info != 0) if(info != 0)
{ {
*u = Scalar(0.); if( u.data )
*vt = Scalar(0.); u = Scalar(0.);
if( vt.data )
vt = Scalar(0.);
w = Scalar(0.); w = Scalar(0.);
} }
} }
void SVD::compute( const Mat& a, Mat& w, Mat& u, Mat& vt, int flags ) void SVD::compute( const InputArray& a, OutputArray w, OutputArray u, OutputArray vt, int flags )
{ {
_SVDcompute(a, w, &u, &vt, flags); _SVDcompute(a, w, u, vt, flags);
} }
void SVD::compute( const Mat& a, Mat& w, int flags ) void SVD::compute( const InputArray& a, OutputArray w, int flags )
{ {
_SVDcompute(a, w, 0, 0, flags); _SVDcompute(a, w, OutputArray(), OutputArray(), flags);
} }
void SVD::backSubst( const Mat& w, const Mat& u, const Mat& vt, const Mat& rhs, Mat& dst ) void SVD::backSubst( const InputArray& _w, const InputArray& _u, const InputArray& _vt,
const InputArray& _rhs, OutputArray _dst )
{ {
Mat w = _w.getMat(), u = _u.getMat(), vt = _vt.getMat(), rhs = _rhs.getMat();
int type = w.type(), esz = (int)w.elemSize(); int type = w.type(), esz = (int)w.elemSize();
int m = u.rows, n = vt.cols, nb = rhs.data ? rhs.cols : m; int m = u.rows, n = vt.cols, nb = rhs.data ? rhs.cols : m;
AutoBuffer<double> buffer(nb); AutoBuffer<double> buffer(nb);
@ -1456,7 +1484,8 @@ void SVD::backSubst( const Mat& w, const Mat& u, const Mat& vt, const Mat& rhs,
CV_Assert( rhs.data == 0 || (rhs.type() == type && rhs.rows == m) ); CV_Assert( rhs.data == 0 || (rhs.type() == type && rhs.rows == m) );
dst.create( n, nb, type ); _dst.create( n, nb, type );
Mat dst = _dst.getMat();
if( type == CV_32F ) if( type == CV_32F )
SVBkSb(m, n, (float*)w.data, 1, (float*)u.data, (int)(u.step/esz), false, SVBkSb(m, n, (float*)w.data, 1, (float*)u.data, (int)(u.step/esz), false,
(float*)vt.data, (int)(vt.step/esz), true, (float*)rhs.data, (int)(rhs.step/esz), (float*)vt.data, (int)(vt.step/esz), true, (float*)rhs.data, (int)(rhs.step/esz),
@ -1470,14 +1499,14 @@ void SVD::backSubst( const Mat& w, const Mat& u, const Mat& vt, const Mat& rhs,
} }
SVD& SVD::operator ()(const Mat& a, int flags) SVD& SVD::operator ()(const InputArray& a, int flags)
{ {
_SVDcompute(a, w, &u, &vt, flags); _SVDcompute(a, w, u, vt, flags);
return *this; return *this;
} }
void SVD::backSubst( const Mat& rhs, Mat& dst ) const void SVD::backSubst( const InputArray& rhs, OutputArray dst ) const
{ {
backSubst( w, u, vt, rhs, dst ); backSubst( w, u, vt, rhs, dst );
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -208,9 +208,11 @@ static inline bool isIdentity(const MatExpr& e) { return e.op == &g_MatOp_Identi
static inline bool isAddEx(const MatExpr& e) { return e.op == &g_MatOp_AddEx; } static inline bool isAddEx(const MatExpr& e) { return e.op == &g_MatOp_AddEx; }
static inline bool isScaled(const MatExpr& e) { return isAddEx(e) && (!e.b.data || e.beta == 0) && e.s == Scalar(); } static inline bool isScaled(const MatExpr& e) { return isAddEx(e) && (!e.b.data || e.beta == 0) && e.s == Scalar(); }
static inline bool isBin(const MatExpr& e, char c) { return e.op == &g_MatOp_Bin && e.flags == c; } static inline bool isBin(const MatExpr& e, char c) { return e.op == &g_MatOp_Bin && e.flags == c; }
static inline bool isCmp(const MatExpr& e) { return e.op == &g_MatOp_Cmp; }
static inline bool isReciprocal(const MatExpr& e) { return isBin(e,'/') && (!e.b.data || e.beta == 0); } static inline bool isReciprocal(const MatExpr& e) { return isBin(e,'/') && (!e.b.data || e.beta == 0); }
static inline bool isT(const MatExpr& e) { return e.op == &g_MatOp_T; } static inline bool isT(const MatExpr& e) { return e.op == &g_MatOp_T; }
static inline bool isInv(const MatExpr& e) { return e.op == &g_MatOp_Invert; } static inline bool isInv(const MatExpr& e) { return e.op == &g_MatOp_Invert; }
static inline bool isSolve(const MatExpr& e) { return e.op == &g_MatOp_Solve; }
static inline bool isGEMM(const MatExpr& e) { return e.op == &g_MatOp_GEMM; } static inline bool isGEMM(const MatExpr& e) { return e.op == &g_MatOp_GEMM; }
static inline bool isMatProd(const MatExpr& e) { return e.op == &g_MatOp_GEMM && (!e.c.data || e.beta == 0); } static inline bool isMatProd(const MatExpr& e) { return e.op == &g_MatOp_GEMM && (!e.c.data || e.beta == 0); }
static inline bool isInitializer(const MatExpr& e) { return e.op == &g_MatOp_Initializer; } static inline bool isInitializer(const MatExpr& e) { return e.op == &g_MatOp_Initializer; }
@ -572,6 +574,17 @@ void MatOp::invert(const MatExpr& expr, int method, MatExpr& res) const
MatOp_Invert::makeExpr(res, method, m); MatOp_Invert::makeExpr(res, method, m);
} }
Size MatOp::size(const MatExpr& expr) const
{
return !expr.a.empty() ? expr.a.size() : expr.b.empty() ? expr.b.size() : expr.c.size();
}
int MatOp::type(const MatExpr& expr) const
{
return !expr.a.empty() ? expr.a.type() : expr.b.empty() ? expr.b.type() : expr.c.type();
}
////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////
MatExpr::MatExpr(const Mat& m) : op(&g_MatOp_Identity), flags(0), a(m), b(Mat()), c(Mat()), alpha(1), beta(0), s(Scalar()) MatExpr::MatExpr(const Mat& m) : op(&g_MatOp_Identity), flags(0), a(m), b(Mat()), c(Mat()), alpha(1), beta(0), s(Scalar())
@ -1142,6 +1155,30 @@ MatExpr abs(const MatExpr& e)
} }
Size MatExpr::size() const
{
if( isT(*this) || isInv(*this) )
return Size(a.rows, a.cols);
if( isGEMM(*this) )
return Size(b.cols, a.rows);
if( isSolve(*this) )
return Size(b.cols, a.cols);
if( isInitializer(*this) )
return a.size();
return op ? op->size(*this) : Size();
}
int MatExpr::type() const
{
if( isInitializer(*this) )
return a.type();
if( isCmp(*this) )
return CV_8U;
return op ? op->type(*this) : -1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////
void MatOp_Identity::assign(const MatExpr& e, Mat& m, int type) const void MatOp_Identity::assign(const MatExpr& e, Mat& m, int type) const
@ -1552,10 +1589,10 @@ MatExpr Mat::inv(int method) const
} }
MatExpr Mat::mul(const Mat& m, double scale) const MatExpr Mat::mul(const InputArray& m, double scale) const
{ {
MatExpr e; MatExpr e;
MatOp_Bin::makeExpr(e, '*', *this, m, scale); MatOp_Bin::makeExpr(e, '*', *this, m.getMat(), scale);
return e; return e;
} }

File diff suppressed because it is too large Load Diff

@ -65,74 +65,6 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define CV_MEMCPY_CHAR( dst, src, len ) \
{ \
size_t _icv_memcpy_i_, _icv_memcpy_len_ = (len); \
char* _icv_memcpy_dst_ = (char*)(dst); \
const char* _icv_memcpy_src_ = (const char*)(src); \
\
for( _icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; _icv_memcpy_i_++ ) \
_icv_memcpy_dst_[_icv_memcpy_i_] = _icv_memcpy_src_[_icv_memcpy_i_]; \
}
#define CV_MEMCPY_INT( dst, src, len ) \
{ \
size_t _icv_memcpy_i_, _icv_memcpy_len_ = (len); \
int* _icv_memcpy_dst_ = (int*)(dst); \
const int* _icv_memcpy_src_ = (const int*)(src); \
assert( ((size_t)_icv_memcpy_src_&(sizeof(int)-1)) == 0 && \
((size_t)_icv_memcpy_dst_&(sizeof(int)-1)) == 0 ); \
\
for(_icv_memcpy_i_=0;_icv_memcpy_i_<_icv_memcpy_len_;_icv_memcpy_i_++) \
_icv_memcpy_dst_[_icv_memcpy_i_] = _icv_memcpy_src_[_icv_memcpy_i_];\
}
#define CV_MEMCPY_AUTO( dst, src, len ) \
{ \
size_t _icv_memcpy_i_, _icv_memcpy_len_ = (len); \
char* _icv_memcpy_dst_ = (char*)(dst); \
const char* _icv_memcpy_src_ = (const char*)(src); \
if( (_icv_memcpy_len_ & (sizeof(int)-1)) == 0 ) \
{ \
assert( ((size_t)_icv_memcpy_src_&(sizeof(int)-1)) == 0 && \
((size_t)_icv_memcpy_dst_&(sizeof(int)-1)) == 0 ); \
for( _icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; \
_icv_memcpy_i_+=sizeof(int) ) \
{ \
*(int*)(_icv_memcpy_dst_+_icv_memcpy_i_) = \
*(const int*)(_icv_memcpy_src_+_icv_memcpy_i_); \
} \
} \
else \
{ \
for(_icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; _icv_memcpy_i_++)\
_icv_memcpy_dst_[_icv_memcpy_i_] = _icv_memcpy_src_[_icv_memcpy_i_]; \
} \
}
#define CV_ZERO_CHAR( dst, len ) \
{ \
size_t _icv_memcpy_i_, _icv_memcpy_len_ = (len); \
char* _icv_memcpy_dst_ = (char*)(dst); \
\
for( _icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; _icv_memcpy_i_++ ) \
_icv_memcpy_dst_[_icv_memcpy_i_] = '\0'; \
}
#define CV_ZERO_INT( dst, len ) \
{ \
size_t _icv_memcpy_i_, _icv_memcpy_len_ = (len); \
int* _icv_memcpy_dst_ = (int*)(dst); \
assert( ((size_t)_icv_memcpy_dst_&(sizeof(int)-1)) == 0 ); \
\
for(_icv_memcpy_i_=0;_icv_memcpy_i_<_icv_memcpy_len_;_icv_memcpy_i_++) \
_icv_memcpy_dst_[_icv_memcpy_i_] = 0; \
}
namespace cv namespace cv
{ {
@ -150,24 +82,12 @@ extern const uchar g_Saturate8u[];
#define CV_MIN_8U(a,b) ((a) - CV_FAST_CAST_8U((a) - (b))) #define CV_MIN_8U(a,b) ((a) - CV_FAST_CAST_8U((a) - (b)))
#define CV_MAX_8U(a,b) ((a) + CV_FAST_CAST_8U((b) - (a))) #define CV_MAX_8U(a,b) ((a) + CV_FAST_CAST_8U((b) - (a)))
typedef void (*CopyMaskFunc)(const Mat& src, Mat& dst, const Mat& mask);
extern CopyMaskFunc g_copyMaskFuncTab[];
static inline CopyMaskFunc getCopyMaskFunc(int esz)
{
CV_Assert( (unsigned)esz <= 32U );
CopyMaskFunc func = g_copyMaskFuncTab[esz];
CV_Assert( func != 0 );
return func;
}
#if defined WIN32 || defined _WIN32 #if defined WIN32 || defined _WIN32
void deleteThreadAllocData(); void deleteThreadAllocData();
void deleteThreadRNGData(); void deleteThreadRNGData();
#endif #endif
template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd
{ {
typedef T1 type1; typedef T1 type1;
@ -192,22 +112,6 @@ template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub
T3 operator ()(T1 a, T2 b) const { return saturate_cast<T3>(b - a); } T3 operator ()(T1 a, T2 b) const { return saturate_cast<T3>(b - a); }
}; };
template<typename T1, typename T2=T1, typename T3=T1> struct OpMul
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(T1 a, T2 b) const { return saturate_cast<T3>(a * b); }
};
template<typename T1, typename T2=T1, typename T3=T1> struct OpDiv
{
typedef T1 type1;
typedef T2 type2;
typedef T3 rtype;
T3 operator ()(T1 a, T2 b) const { return saturate_cast<T3>(a / b); }
};
template<typename T> struct OpMin template<typename T> struct OpMin
{ {
typedef T type1; typedef T type1;
@ -261,154 +165,34 @@ inline Size getContinuousSize( const Mat& m1, const Mat& m2,
struct NoVec struct NoVec
{ {
int operator()(const void*, const void*, void*, int) const { return 0; } size_t operator()(const void*, const void*, void*, size_t) const { return 0; }
}; };
extern volatile bool USE_SSE2;
template<class Op, class VecOp> static void typedef void (*BinaryFunc)(const uchar* src1, size_t step1,
binaryOpC1_( const Mat& srcmat1, const Mat& srcmat2, Mat& dstmat ) const uchar* src2, size_t step2,
{ uchar* dst, size_t step, Size sz,
Op op; VecOp vecOp; void*);
typedef typename Op::type1 T1;
typedef typename Op::type2 T2;
typedef typename Op::rtype DT;
const T1* src1 = (const T1*)srcmat1.data;
const T2* src2 = (const T2*)srcmat2.data;
DT* dst = (DT*)dstmat.data;
size_t step1 = srcmat1.step/sizeof(src1[0]);
size_t step2 = srcmat2.step/sizeof(src2[0]);
size_t step = dstmat.step/sizeof(dst[0]);
Size size = getContinuousSize( srcmat1, srcmat2, dstmat, dstmat.channels() );
if( size.width == 1 )
{
for( ; size.height--; src1 += step1, src2 += step2, dst += step )
dst[0] = op( src1[0], src2[0] );
return;
}
for( ; size.height--; src1 += step1, src2 += step2, dst += step )
{
int x;
x = vecOp(src1, src2, dst, size.width);
for( ; x <= size.width - 4; x += 4 )
{
DT f0, f1;
f0 = op( src1[x], src2[x] );
f1 = op( src1[x+1], src2[x+1] );
dst[x] = f0;
dst[x+1] = f1;
f0 = op(src1[x+2], src2[x+2]);
f1 = op(src1[x+3], src2[x+3]);
dst[x+2] = f0;
dst[x+3] = f1;
}
for( ; x < size.width; x++ )
dst[x] = op( src1[x], src2[x] );
}
}
typedef void (*BinaryFunc)(const Mat& src1, const Mat& src2, Mat& dst);
template<class Op> static void BinaryFunc getConvertFunc(int sdepth, int ddepth);
binarySOpCn_( const Mat& srcmat, Mat& dstmat, const Scalar& _scalar ) BinaryFunc getConvertScaleFunc(int sdepth, int ddepth);
{ BinaryFunc getCopyMaskFunc(size_t esz);
Op op;
typedef typename Op::type1 T;
typedef typename Op::type2 WT;
typedef typename Op::rtype DT;
const T* src0 = (const T*)srcmat.data;
DT* dst0 = (DT*)dstmat.data;
size_t step1 = srcmat.step/sizeof(src0[0]);
size_t step = dstmat.step/sizeof(dst0[0]);
int cn = dstmat.channels();
Size size = getContinuousSize( srcmat, dstmat, cn );
WT scalar[12];
scalarToRawData(_scalar, scalar, CV_MAKETYPE(DataType<WT>::depth,cn), 12);
for( ; size.height--; src0 += step1, dst0 += step )
{
int i, len = size.width;
const T* src = src0;
T* dst = dst0;
for( ; (len -= 12) >= 0; dst += 12, src += 12 )
{
DT t0 = op(src[0], scalar[0]);
DT t1 = op(src[1], scalar[1]);
dst[0] = t0; dst[1] = t1;
t0 = op(src[2], scalar[2]); enum { BLOCK_SIZE = 1024 };
t1 = op(src[3], scalar[3]);
dst[2] = t0; dst[3] = t1;
t0 = op(src[4], scalar[4]); #ifdef HAVE_IPP
t1 = op(src[5], scalar[5]); static inline IppiSize ippiSize(int width, int height) { IppiSize sz={width, height}; return sz; }
dst[4] = t0; dst[5] = t1; static inline IppiSize ippiSize(Size _sz) { reIppiSize sz={_sz.width, _sz.height}; return sz; }
#endif
t0 = op(src[6], scalar[6]);
t1 = op(src[7], scalar[7]);
dst[6] = t0; dst[7] = t1;
t0 = op(src[8], scalar[8]);
t1 = op(src[9], scalar[9]);
dst[8] = t0; dst[9] = t1;
t0 = op(src[10], scalar[10]);
t1 = op(src[11], scalar[11]);
dst[10] = t0; dst[11] = t1;
}
for( (len) += 12, i = 0; i < (len); i++ )
dst[i] = op((WT)src[i], scalar[i]);
}
}
template<class Op> static void
binarySOpC1_( const Mat& srcmat, Mat& dstmat, double _scalar )
{
Op op;
typedef typename Op::type1 T;
typedef typename Op::type2 WT;
typedef typename Op::rtype DT;
WT scalar = saturate_cast<WT>(_scalar);
const T* src = (const T*)srcmat.data;
DT* dst = (DT*)dstmat.data;
size_t step1 = srcmat.step/sizeof(src[0]);
size_t step = dstmat.step/sizeof(dst[0]);
Size size = srcmat.size();
size.width *= srcmat.channels();
if( srcmat.isContinuous() && dstmat.isContinuous() )
{
size.width *= size.height;
size.height = 1;
}
for( ; size.height--; src += step1, dst += step )
{
int x;
for( x = 0; x <= size.width - 4; x += 4 )
{
DT f0 = op( src[x], scalar );
DT f1 = op( src[x+1], scalar );
dst[x] = f0;
dst[x+1] = f1;
f0 = op( src[x+2], scalar );
f1 = op( src[x+3], scalar );
dst[x+2] = f0;
dst[x+3] = f1;
}
for( ; x < size.width; x++ )
dst[x] = op( src[x], scalar );
}
}
typedef void (*BinarySFuncCn)(const Mat& src1, Mat& dst, const Scalar& scalar); #if defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7)
typedef void (*BinarySFuncC1)(const Mat& src1, Mat& dst, double scalar); #define ARITHM_USE_IPP 1
#define IF_IPP(then_call, else_call) then_call
#else
#define ARITHM_USE_IPP 0
#define IF_IPP(then_call, else_call) else_call
#endif
} }

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -170,12 +170,14 @@ struct IPPInitializer
IPPInitializer ippInitializer; IPPInitializer ippInitializer;
#else #else
volatile bool useOptimizedFlag = false; volatile bool useOptimizedFlag = false;
volatile bool USE_SSE2 = false;
#endif #endif
void setUseOptimized( bool flag ) void setUseOptimized( bool flag )
{ {
useOptimizedFlag = flag; useOptimizedFlag = flag;
currentFeatures = flag ? &featuresEnabled : &featuresDisabled; currentFeatures = flag ? &featuresEnabled : &featuresDisabled;
USE_SSE2 = currentFeatures->have[CV_CPU_SSE2];
} }
bool useOptimized(void) bool useOptimized(void)

@ -35,7 +35,7 @@ struct BaseElemWiseOp
virtual int getRandomType(RNG& rng) virtual int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL_BUT_8S, 1, return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1,
ninputs > 1 ? ARITHM_MAX_CHANNELS : 4); ninputs > 1 ? ARITHM_MAX_CHANNELS : 4);
} }
@ -172,6 +172,10 @@ struct ScaleAddOp : public BaseAddOp
{ {
scaleAdd(src[0], alpha, src[1], dst); scaleAdd(src[0], alpha, src[1], dst);
} }
double getMaxErr(int depth)
{
return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-4 : 1e-12;
}
}; };
@ -414,7 +418,7 @@ struct CmpOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL_BUT_8S, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 1);
} }
double getMaxErr(int) double getMaxErr(int)
@ -431,6 +435,8 @@ struct CmpSOp : public BaseElemWiseOp
{ {
BaseElemWiseOp::generateScalars(depth, rng); BaseElemWiseOp::generateScalars(depth, rng);
cmpop = rng.uniform(0, 6); cmpop = rng.uniform(0, 6);
if( depth < CV_32F )
gamma[0] = cvRound(gamma[0]);
} }
void op(const vector<Mat>& src, Mat& dst, const Mat&) void op(const vector<Mat>& src, Mat& dst, const Mat&)
{ {
@ -442,7 +448,7 @@ struct CmpSOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL_BUT_8S, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 1);
} }
double getMaxErr(int) double getMaxErr(int)
{ {
@ -465,7 +471,7 @@ struct CopyOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL, 1, ARITHM_MAX_CHANNELS); return cvtest::randomType(rng, DEPTH_MASK_ALL, 1, ARITHM_MAX_CHANNELS);
} }
double getMaxErr(int) double getMaxErr(int)
{ {
@ -488,7 +494,7 @@ struct SetOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL, 1, ARITHM_MAX_CHANNELS); return cvtest::randomType(rng, DEPTH_MASK_ALL, 1, ARITHM_MAX_CHANNELS);
} }
double getMaxErr(int) double getMaxErr(int)
{ {
@ -504,14 +510,14 @@ inRangeS_(const _Tp* src, const _WTp* a, const _WTp* b, uchar* dst, size_t total
for( i = 0; i < total; i++ ) for( i = 0; i < total; i++ )
{ {
_Tp val = src[i*cn]; _Tp val = src[i*cn];
dst[i] = a[0] <= val && val < b[0] ? 255 : 0; dst[i] = a[0] <= val && val <= b[0] ? 255 : 0;
} }
for( c = 1; c < cn; c++ ) for( c = 1; c < cn; c++ )
{ {
for( i = 0; i < total; i++ ) for( i = 0; i < total; i++ )
{ {
_Tp val = src[i*cn + c]; _Tp val = src[i*cn + c];
dst[i] = a[c] <= val && val < b[c] ? dst[i] : 0; dst[i] = a[c] <= val && val <= b[c] ? dst[i] : 0;
} }
} }
} }
@ -523,14 +529,14 @@ template<typename _Tp> static void inRange_(const _Tp* src, const _Tp* a, const
for( i = 0; i < total; i++ ) for( i = 0; i < total; i++ )
{ {
_Tp val = src[i*cn]; _Tp val = src[i*cn];
dst[i] = a[i*cn] <= val && val < b[i*cn] ? 255 : 0; dst[i] = a[i*cn] <= val && val <= b[i*cn] ? 255 : 0;
} }
for( c = 1; c < cn; c++ ) for( c = 1; c < cn; c++ )
{ {
for( i = 0; i < total; i++ ) for( i = 0; i < total; i++ )
{ {
_Tp val = src[i*cn + c]; _Tp val = src[i*cn + c];
dst[i] = a[i*cn + c] <= val && val < b[i*cn + c] ? dst[i] : 0; dst[i] = a[i*cn + c] <= val && val <= b[i*cn + c] ? dst[i] : 0;
} }
} }
} }
@ -703,13 +709,13 @@ struct ConvertScaleOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
int srctype = cvtest::randomType(rng, cvtest::TYPE_MASK_ALL, 1, ARITHM_MAX_CHANNELS); int srctype = cvtest::randomType(rng, DEPTH_MASK_ALL, 1, ARITHM_MAX_CHANNELS);
ddepth = cvtest::randomType(rng, cvtest::TYPE_MASK_ALL, 1, 1); ddepth = cvtest::randomType(rng, DEPTH_MASK_ALL, 1, 1);
return srctype; return srctype;
} }
double getMaxErr(int) double getMaxErr(int)
{ {
return ddepth <= CV_32S ? 2 : ddepth < CV_64F ? 1e-4 : 1e-12; return ddepth <= CV_32S ? 2 : ddepth < CV_64F ? 1e-3 : 1e-12;
} }
void generateScalars(int depth, RNG& rng) void generateScalars(int depth, RNG& rng)
{ {
@ -940,7 +946,7 @@ struct ExpOp : public BaseElemWiseOp
ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_FLT, 1, ARITHM_MAX_CHANNELS); return cvtest::randomType(rng, DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
} }
void getValueRange(int depth, double& minval, double& maxval) void getValueRange(int depth, double& minval, double& maxval)
{ {
@ -967,7 +973,7 @@ struct LogOp : public BaseElemWiseOp
LogOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; LogOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_FLT, 1, ARITHM_MAX_CHANNELS); return cvtest::randomType(rng, DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
} }
void getValueRange(int depth, double& minval, double& maxval) void getValueRange(int depth, double& minval, double& maxval)
{ {
@ -1052,7 +1058,7 @@ struct CartToPolarToCartOp : public BaseElemWiseOp
} }
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_FLT, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_FLT, 1, 1);
} }
void op(const vector<Mat>& src, Mat& dst, const Mat&) void op(const vector<Mat>& src, Mat& dst, const Mat&)
{ {
@ -1128,7 +1134,7 @@ struct SumOp : public BaseElemWiseOp
} }
double getMaxErr(int) double getMaxErr(int)
{ {
return 1e-6; return 1e-5;
} }
}; };
@ -1139,7 +1145,7 @@ struct CountNonZeroOp : public BaseElemWiseOp
{} {}
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_ALL, 1, 1);
} }
void op(const vector<Mat>& src, Mat& dst, const Mat& mask) void op(const vector<Mat>& src, Mat& dst, const Mat& mask)
{ {
@ -1208,7 +1214,7 @@ struct NormOp : public BaseElemWiseOp
}; };
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL_BUT_8S, 1, 4); return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 4);
} }
void op(const vector<Mat>& src, Mat& dst, const Mat& mask) void op(const vector<Mat>& src, Mat& dst, const Mat& mask)
{ {
@ -1242,7 +1248,7 @@ struct MinMaxLocOp : public BaseElemWiseOp
}; };
int getRandomType(RNG& rng) int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, cvtest::TYPE_MASK_ALL_BUT_8S, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 1);
} }
void saveOutput(const vector<int>& minidx, const vector<int>& maxidx, void saveOutput(const vector<int>& minidx, const vector<int>& maxidx,
double minval, double maxval, Mat& dst) double minval, double maxval, Mat& dst)
@ -1341,6 +1347,8 @@ INSTANTIATE_TEST_CASE_P(Core_SubRS, ElemWiseTest, ::testing::Values(ElemWiseOpPt
INSTANTIATE_TEST_CASE_P(Core_ScaleAdd, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::ScaleAddOp))); INSTANTIATE_TEST_CASE_P(Core_ScaleAdd, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::ScaleAddOp)));
INSTANTIATE_TEST_CASE_P(Core_AddWeighted, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AddWeightedOp))); INSTANTIATE_TEST_CASE_P(Core_AddWeighted, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AddWeightedOp)));
INSTANTIATE_TEST_CASE_P(Core_AbsDiff, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AbsDiffOp))); INSTANTIATE_TEST_CASE_P(Core_AbsDiff, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AbsDiffOp)));
INSTANTIATE_TEST_CASE_P(Core_AbsDiffS, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AbsDiffSOp))); INSTANTIATE_TEST_CASE_P(Core_AbsDiffS, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::AbsDiffSOp)));
INSTANTIATE_TEST_CASE_P(Core_And, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::LogicOp('&')))); INSTANTIATE_TEST_CASE_P(Core_And, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::LogicOp('&'))));
@ -1380,3 +1388,6 @@ INSTANTIATE_TEST_CASE_P(Core_Sum, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(
INSTANTIATE_TEST_CASE_P(Core_Norm, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::NormOp))); INSTANTIATE_TEST_CASE_P(Core_Norm, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::NormOp)));
INSTANTIATE_TEST_CASE_P(Core_MinMaxLoc, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::MinMaxLocOp))); INSTANTIATE_TEST_CASE_P(Core_MinMaxLoc, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::MinMaxLocOp)));
INSTANTIATE_TEST_CASE_P(Core_CartToPolarToCart, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::CartToPolarToCartOp))); INSTANTIATE_TEST_CASE_P(Core_CartToPolarToCart, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::CartToPolarToCartOp)));

@ -827,3 +827,4 @@ TEST(Core_DCT, accuracy) { CxCore_DCTTest test; test.safe_run(); }
TEST(Core_DFT, accuracy) { CxCore_DFTTest test; test.safe_run(); } TEST(Core_DFT, accuracy) { CxCore_DFTTest test; test.safe_run(); }
TEST(Core_MulSpectrums, accuracy) { CxCore_MulSpectrumsTest test; test.safe_run(); } TEST(Core_MulSpectrums, accuracy) { CxCore_MulSpectrumsTest test; test.safe_run(); }

@ -277,8 +277,6 @@ public:
protected: protected:
void run(int) void run(int)
{ {
int code = cvtest::TS::OK;
double diffPrjEps, diffBackPrjEps, double diffPrjEps, diffBackPrjEps,
prjEps, backPrjEps, prjEps, backPrjEps,
evalEps, evecEps; evalEps, evecEps;
@ -327,26 +325,44 @@ protected:
if( err > eigenEps ) if( err > eigenEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of eigen(); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of eigen(); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
} }
// check pca eigenvalues // check pca eigenvalues
evalEps = 1e-6, evecEps = 1; evalEps = 1e-6, evecEps = 1e-3;
err = norm( rPCA.eigenvalues, subEval ); err = norm( rPCA.eigenvalues, subEval );
if( err > evalEps ) if( err > evalEps )
{ {
ts->printf( cvtest::TS::LOG, "pca.eigenvalues is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "pca.eigenvalues is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
// check pca eigenvectors // check pca eigenvectors
err = norm( rPCA.eigenvectors, subEvec, CV_RELATIVE_L2 ); for(int i = 0; i < subEvec.rows; i++)
{
Mat r0 = rPCA.eigenvectors.row(i);
Mat r1 = subEvec.row(i);
err = norm( r0, r1, CV_L2 );
if( err > evecEps ) if( err > evecEps )
{ {
r1 *= -1;
double err2 = norm(r0, r1, CV_L2);
if( err2 > evecEps )
{
Mat tmp;
absdiff(rPCA.eigenvectors, subEvec, tmp);
double mval = 0; Point mloc;
minMaxLoc(tmp, 0, &mval, 0, &mloc);
ts->printf( cvtest::TS::LOG, "pca.eigenvectors is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "pca.eigenvectors is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->printf( cvtest::TS::LOG, "max diff is %g at (i=%d, j=%d) (%g vs %g)\n",
goto exit_func; mval, mloc.y, mloc.x, rPCA.eigenvectors.at<float>(mloc.y, mloc.x),
subEvec.at<float>(mloc.y, mloc.x));
ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
return;
}
}
} }
prjEps = 1.265, backPrjEps = 1.265; prjEps = 1.265, backPrjEps = 1.265;
@ -359,8 +375,8 @@ protected:
if( err > prjEps ) if( err > prjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
// check pca backProject // check pca backProject
Mat backPrj = rPrjTestPoints.row(i) * subEvec + avg; Mat backPrj = rPrjTestPoints.row(i) * subEvec + avg;
@ -368,27 +384,28 @@ protected:
if( err > backPrjEps ) if( err > backPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
} }
// 2. check C++ PCA & COL // 2. check C++ PCA & COL
cPCA( rPoints.t(), Mat(), CV_PCA_DATA_AS_COL, maxComponents ); cPCA( rPoints.t(), Mat(), CV_PCA_DATA_AS_COL, maxComponents );
diffPrjEps = 1, diffBackPrjEps = 1; diffPrjEps = 1, diffBackPrjEps = 1;
err = norm(cPCA.project(rTestPoints.t()), rPrjTestPoints.t(), CV_RELATIVE_L2 ); Mat ocvPrjTestPoints = cPCA.project(rTestPoints.t());
err = norm(cv::abs(ocvPrjTestPoints), cv::abs(rPrjTestPoints.t()), CV_RELATIVE_L2 );
if( err > diffPrjEps ) if( err > diffPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_COL); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_COL); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
err = norm(cPCA.backProject(rPrjTestPoints.t()), rBackPrjTestPoints.t(), CV_RELATIVE_L2 ); err = norm(cPCA.backProject(ocvPrjTestPoints), rBackPrjTestPoints.t(), CV_RELATIVE_L2 );
if( err > diffBackPrjEps ) if( err > diffBackPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_COL); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_COL); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
#ifdef CHECK_C #ifdef CHECK_C
@ -411,15 +428,15 @@ protected:
if( err > diffPrjEps ) if( err > diffPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
err = norm(backPrjTestPoints, rBackPrjTestPoints, CV_RELATIVE_L2); err = norm(backPrjTestPoints, rBackPrjTestPoints, CV_RELATIVE_L2);
if( err > diffBackPrjEps ) if( err > diffBackPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
// 3. check C PCA & COL // 3. check C PCA & COL
@ -435,27 +452,21 @@ protected:
cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints ); cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints );
cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints ); cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints );
err = norm(prjTestPoints, rPrjTestPoints.t(), CV_RELATIVE_L2 ); err = norm(cv::abs(prjTestPoints), cv::abs(rPrjTestPoints.t()), CV_RELATIVE_L2 );
if( err > diffPrjEps ) if( err > diffPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
err = norm(backPrjTestPoints, rBackPrjTestPoints.t(), CV_RELATIVE_L2); err = norm(backPrjTestPoints, rBackPrjTestPoints.t(), CV_RELATIVE_L2);
if( err > diffBackPrjEps ) if( err > diffBackPrjEps )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err ); ts->printf( cvtest::TS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err );
code = cvtest::TS::FAIL_BAD_ACCURACY; ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
goto exit_func; return;
} }
#endif #endif
exit_func:
RNG& _rng = ts->get_rng();
_rng = rng;
ts->set_failed_test_info( code );
} }
}; };
@ -790,7 +801,7 @@ void Core_ArrayOpTest::run( int /* start_from */)
break; break;
} }
minMaxLoc(Md, &val1, &val2, idx1, idx2); minMaxIdx(Md, &val1, &val2, idx1, idx2);
s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims); s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims);
if( (min_val < 0 && (val1 != min_val || s1 != min_sidx)) || if( (min_val < 0 && (val1 != min_val || s1 != min_sidx)) ||
(max_val > 0 && (val2 != max_val || s2 != max_sidx)) ) (max_val > 0 && (val2 != max_val || s2 != max_sidx)) )
@ -809,3 +820,5 @@ void Core_ArrayOpTest::run( int /* start_from */)
TEST(Core_PCA, accuracy) { Core_PCATest test; test.safe_run(); } TEST(Core_PCA, accuracy) { Core_PCATest test; test.safe_run(); }
TEST(Core_Reduce, accuracy) { Core_ReduceTest test; test.safe_run(); } TEST(Core_Reduce, accuracy) { Core_ReduceTest test; test.safe_run(); }
TEST(Core_Array, basic_operations) { Core_ArrayOpTest test; test.safe_run(); } TEST(Core_Array, basic_operations) { Core_ArrayOpTest test; test.safe_run(); }

@ -113,7 +113,7 @@ BOWKMeansTrainer::~BOWKMeansTrainer()
Mat BOWKMeansTrainer::cluster( const Mat& descriptors ) const Mat BOWKMeansTrainer::cluster( const Mat& descriptors ) const
{ {
Mat labels, vocabulary; Mat labels, vocabulary;
kmeans( descriptors, clusterCount, labels, termcrit, attempts, flags, &vocabulary ); kmeans( descriptors, clusterCount, labels, termcrit, attempts, flags, vocabulary );
return vocabulary; return vocabulary;
} }

@ -281,7 +281,6 @@ void CV_KDTreeTest_CPP::createModel( const Mat& data )
int CV_KDTreeTest_CPP::checkGetPoins( const Mat& data ) int CV_KDTreeTest_CPP::checkGetPoins( const Mat& data )
{ {
Mat res1( data.size(), data.type() ), Mat res1( data.size(), data.type() ),
res2( data.size(), data.type() ),
res3( data.size(), data.type() ); res3( data.size(), data.type() );
Mat idxs( 1, data.rows, CV_32SC1 ); Mat idxs( 1, data.rows, CV_32SC1 );
for( int pi = 0; pi < data.rows; pi++ ) for( int pi = 0; pi < data.rows; pi++ )
@ -292,14 +291,11 @@ int CV_KDTreeTest_CPP::checkGetPoins( const Mat& data )
for( int di = 0; di < data.cols; di++ ) for( int di = 0; di < data.cols; di++ )
res1.at<float>(pi, di) = point[di]; res1.at<float>(pi, di) = point[di];
} }
// 2nd way
tr->getPoints( idxs.ptr<int>(0), data.rows, res2 );
// 3d way // 3d way
tr->getPoints( idxs, res3 ); tr->getPoints( idxs, res3 );
if( norm( res1, data, NORM_L1) != 0 || if( norm( res1, data, NORM_L1) != 0 ||
norm( res2, data, NORM_L1) != 0 ||
norm( res3, data, NORM_L1) != 0) norm( res3, data, NORM_L1) != 0)
return cvtest::TS::FAIL_BAD_ACCURACY; return cvtest::TS::FAIL_BAD_ACCURACY;
return cvtest::TS::OK; return cvtest::TS::OK;
@ -309,7 +305,7 @@ int CV_KDTreeTest_CPP::checkFindBoxed()
{ {
vector<float> min( dims, minValue), max(dims, maxValue); vector<float> min( dims, minValue), max(dims, maxValue);
vector<int> indices; vector<int> indices;
tr->findOrthoRange( &min[0], &max[0], &indices ); tr->findOrthoRange( min, max, indices );
// TODO check indices // TODO check indices
if( (int)indices.size() != featuresCount) if( (int)indices.size() != featuresCount)
return cvtest::TS::FAIL_BAD_ACCURACY; return cvtest::TS::FAIL_BAD_ACCURACY;
@ -326,11 +322,12 @@ int CV_KDTreeTest_CPP::findNeighbors( Mat& points, Mat& neighbors )
for( int pi = 0; pi < points.rows; pi++ ) for( int pi = 0; pi < points.rows; pi++ )
{ {
// 1st way // 1st way
tr->findNearest( points.ptr<float>(pi), neighbors.cols, emax, neighbors.ptr<int>(pi) ); Mat nrow = neighbors.row(pi);
tr->findNearest( points.row(pi), neighbors.cols, emax, nrow );
// 2nd way // 2nd way
vector<int> neighborsIdx2( neighbors2.cols, 0 ); vector<int> neighborsIdx2( neighbors2.cols, 0 );
tr->findNearest( points.ptr<float>(pi), neighbors2.cols, emax, &neighborsIdx2 ); tr->findNearest( points.row(pi), neighbors2.cols, emax, neighborsIdx2 );
vector<int>::const_iterator it2 = neighborsIdx2.begin(); vector<int>::const_iterator it2 = neighborsIdx2.begin();
for( j = 0; it2 != neighborsIdx2.end(); ++it2, j++ ) for( j = 0; it2 != neighborsIdx2.end(); ++it2, j++ )
neighbors2.at<int>(pi,j) = *it2; neighbors2.at<int>(pi,j) = *it2;

@ -344,7 +344,7 @@ protected:
ts->printf(cvtest::TS::LOG, "Tesing %s\n", names[i]); ts->printf(cvtest::TS::LOG, "Tesing %s\n", names[i]);
cv::Mat cpuRes; cv::Mat cpuRes;
cv::morphologyEx(img, cpuRes, ops[i], kernel); cv::morphologyEx(img, cpuRes, ops[i], (Mat)kernel);
GpuMat gpuRes; GpuMat gpuRes;
cv::gpu::morphologyEx(GpuMat(img), gpuRes, ops[i], kernel); cv::gpu::morphologyEx(GpuMat(img), gpuRes, ops[i], kernel);

@ -249,7 +249,7 @@ struct CV_GpuHogGetDescriptorsTestRunner: cv::gpu::HOGDescriptor
cv::cvtColor(img_rgb, img, CV_BGR2BGRA); cv::cvtColor(img_rgb, img, CV_BGR2BGRA);
computeBlockHistograms(cv::gpu::GpuMat(img)); computeBlockHistograms(cv::gpu::GpuMat(img));
// Everything is fine with interpolation for left top subimage // Everything is fine with interpolation for left top subimage
CHECK(cv::norm(block_hists, descriptors.rowRange(0, 1)) == 0.f, cvtest::TS::FAIL_INVALID_OUTPUT); CHECK(cv::norm((cv::Mat)block_hists, (cv::Mat)descriptors.rowRange(0, 1)) == 0.f, cvtest::TS::FAIL_INVALID_OUTPUT);
img_rgb = cv::imread(std::string(ts->get_data_path()) + "hog/positive2.png"); img_rgb = cv::imread(std::string(ts->get_data_path()) + "hog/positive2.png");
CHECK(!img_rgb.empty(), cvtest::TS::FAIL_MISSING_TEST_DATA); CHECK(!img_rgb.empty(), cvtest::TS::FAIL_MISSING_TEST_DATA);

@ -74,7 +74,7 @@ struct CV_AsyncGpuMatTest : public cvtest::BaseTest
Mat cpu_gold0(100, 100, CV_8UC1, Scalar::all(255)); Mat cpu_gold0(100, 100, CV_8UC1, Scalar::all(255));
Mat cpu_gold1(100, 100, CV_8UC1, Scalar::all(128)); Mat cpu_gold1(100, 100, CV_8UC1, Scalar::all(128));
if (norm(cpudst0, cpu_gold0, NORM_INF) > 0 || norm(cpudst1, cpu_gold1, NORM_INF) > 0) if (norm((Mat)cpudst0, cpu_gold0, NORM_INF) > 0 || norm((Mat)cpudst1, cpu_gold1, NORM_INF) > 0)
ts->set_failed_test_info(cvtest::TS::FAIL_GENERIC); ts->set_failed_test_info(cvtest::TS::FAIL_GENERIC);
else else
ts->set_failed_test_info(cvtest::TS::OK); ts->set_failed_test_info(cvtest::TS::OK);

@ -92,7 +92,7 @@ void CV_GpuMatOpConvertToTest::run(int /* start_from */)
cpumatsrc.convertTo(cpumatdst, dst_type, 0.5, 3.0); cpumatsrc.convertTo(cpumatdst, dst_type, 0.5, 3.0);
gpumatsrc.convertTo(gpumatdst, dst_type, 0.5, 3.0); gpumatsrc.convertTo(gpumatdst, dst_type, 0.5, 3.0);
double r = norm(cpumatdst, gpumatdst, NORM_INF); double r = norm(cpumatdst, (Mat)gpumatdst, NORM_INF);
if (r > 1) if (r > 1)
{ {
ts->printf(cvtest::TS::LOG, ts->printf(cvtest::TS::LOG,

@ -106,7 +106,7 @@ bool CV_GpuMatOpCopyToTest::compare_matrix(cv::Mat & cpumat, gpu::GpuMat & gpuma
cv::waitKey(0); cv::waitKey(0);
#endif #endif
double ret = norm(cmat, gmat); double ret = norm(cmat, (Mat)gmat);
if (ret < 1.0) if (ret < 1.0)
return true; return true;

@ -78,7 +78,7 @@ bool CV_GpuMatOpSetToTest::testSetTo(cv::Mat& cpumat, gpu::GpuMat& gpumat, const
cpumat.setTo(s, cpumask); cpumat.setTo(s, cpumask);
gpumat.setTo(s, gpumask); gpumat.setTo(s, gpumask);
double ret = norm(cpumat, gpumat, NORM_INF); double ret = norm(cpumat, (Mat)gpumat, NORM_INF);
if (ret < std::numeric_limits<double>::epsilon()) if (ret < std::numeric_limits<double>::epsilon())
return true; return true;

@ -106,7 +106,7 @@ struct CV_GpuStereoBMTest : public cvtest::BaseTest
bm(cv::gpu::GpuMat(img_l), cv::gpu::GpuMat(img_r), disp); bm(cv::gpu::GpuMat(img_l), cv::gpu::GpuMat(img_r), disp);
disp.convertTo(disp, img_reference.type()); disp.convertTo(disp, img_reference.type());
double norm = cv::norm(disp, img_reference, cv::NORM_INF); double norm = cv::norm((Mat)disp, img_reference, cv::NORM_INF);
//cv::imwrite(std::string(ts->get_data_path()) + "stereobm/aloe-disp.png", disp); //cv::imwrite(std::string(ts->get_data_path()) + "stereobm/aloe-disp.png", disp);

@ -70,7 +70,7 @@ struct CV_AsyncStereoBMTest : public cvtest::BaseTest
stream.waitForCompletion(); stream.waitForCompletion();
disp.convertTo(disp, img_reference.type()); disp.convertTo(disp, img_reference.type());
double norm = cv::norm(disp, img_reference, cv::NORM_INF); double norm = cv::norm((Mat)disp, img_reference, cv::NORM_INF);
if (norm >= 100) if (norm >= 100)
{ {

@ -67,7 +67,7 @@ struct CV_GpuStereoBPTest : public cvtest::BaseTest
disp.convertTo(disp, img_template.type()); disp.convertTo(disp, img_template.type());
double norm = cv::norm(disp, img_template, cv::NORM_INF); double norm = cv::norm((cv::Mat)disp, img_template, cv::NORM_INF);
if (norm >= 0.5) if (norm >= 0.5)
{ {
ts->printf(cvtest::TS::LOG, "\nStereoBP norm = %f\n", norm); ts->printf(cvtest::TS::LOG, "\nStereoBP norm = %f\n", norm);

@ -67,7 +67,7 @@ struct CV_GpuStereoCSBPTest : public cvtest::BaseTest
disp.convertTo(disp, img_template.type()); disp.convertTo(disp, img_template.type());
double norm = cv::norm(disp, img_template, cv::NORM_INF); double norm = cv::norm((cv::Mat)disp, img_template, cv::NORM_INF);
if (norm >= 0.5) if (norm >= 0.5)
{ {
ts->printf(cvtest::TS::LOG, "\nConstantSpaceStereoBP norm = %f\n", norm); ts->printf(cvtest::TS::LOG, "\nConstantSpaceStereoBP norm = %f\n", norm);

@ -66,7 +66,9 @@ CV_EXPORTS_W double getWindowProperty(const string& winname, int prop_id);//YV
//Only for Qt //Only for Qt
//------------------------ //------------------------
CV_EXPORTS CvFont fontQt(const string& nameFont, int pointSize CV_DEFAULT(-1), Scalar color CV_DEFAULT(Scalar::all(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); CV_EXPORTS CvFont fontQt(const string& nameFont, int pointSize CV_DEFAULT(-1),
Scalar color CV_DEFAULT(Scalar::all(0)), int weight CV_DEFAULT(CV_FONT_NORMAL),
int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0));
CV_EXPORTS void addText( const Mat& img, const string& text, Point org, CvFont font); CV_EXPORTS void addText( const Mat& img, const string& text, Point org, CvFont font);
CV_EXPORTS void displayOverlay(const string& winname, const string& text, int delayms); CV_EXPORTS void displayOverlay(const string& winname, const string& text, int delayms);
@ -81,10 +83,12 @@ CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char
CV_EXPORTS void stopLoop(); CV_EXPORTS void stopLoop();
typedef void (CV_CDECL *ButtonCallback)(int state, void* userdata); typedef void (CV_CDECL *ButtonCallback)(int state, void* userdata);
CV_EXPORTS int createButton( const string& bar_name, ButtonCallback on_change , void* userdata CV_DEFAULT(NULL), int type CV_DEFAULT(CV_PUSH_BUTTON), bool initial_button_state CV_DEFAULT(0)); CV_EXPORTS int createButton( const string& bar_name, ButtonCallback on_change,
void* userdata CV_DEFAULT(NULL), int type CV_DEFAULT(CV_PUSH_BUTTON),
bool initial_button_state CV_DEFAULT(0));
//------------------------- //-------------------------
CV_EXPORTS_W void imshow( const string& winname, const Mat& mat ); CV_EXPORTS_W void imshow( const string& winname, const InputArray& mat );
typedef void (CV_CDECL *TrackbarCallback)(int pos, void* userdata); typedef void (CV_CDECL *TrackbarCallback)(int pos, void* userdata);
@ -102,11 +106,11 @@ typedef void (*MouseCallback )(int event, int x, int y, int flags, void* param);
CV_EXPORTS void setMouseCallback( const string& windowName, MouseCallback onMouse, void* param=0); CV_EXPORTS void setMouseCallback( const string& windowName, MouseCallback onMouse, void* param=0);
CV_EXPORTS_W Mat imread( const string& filename, int flags=1 ); CV_EXPORTS_W Mat imread( const string& filename, int flags=1 );
CV_EXPORTS_W bool imwrite( const string& filename, const Mat& img, CV_EXPORTS_W bool imwrite( const string& filename, const InputArray& img,
const vector<int>& params=vector<int>()); const vector<int>& params=vector<int>());
CV_EXPORTS_W Mat imdecode( const Mat& buf, int flags ); CV_EXPORTS_W Mat imdecode( const InputArray& buf, int flags );
CV_EXPORTS_W bool imencode( const string& ext, const Mat& img, CV_EXPORTS_W bool imencode( const string& ext, const InputArray& img,
CV_OUT vector<uchar>& buf, vector<uchar>& buf,
const vector<int>& params=vector<int>()); const vector<int>& params=vector<int>());
CV_EXPORTS_W int waitKey(int delay=0); CV_EXPORTS_W int waitKey(int delay=0);

@ -295,9 +295,10 @@ static bool imwrite_( const string& filename, const Mat& image,
return code; return code;
} }
bool imwrite( const string& filename, const Mat& img, bool imwrite( const string& filename, const InputArray& _img,
const vector<int>& params ) const vector<int>& params )
{ {
Mat img = _img.getMat();
return imwrite_(filename, img, params, false); return imwrite_(filename, img, params, false);
} }
@ -388,17 +389,17 @@ imdecode_( const Mat& buf, int flags, int hdrtype, Mat* mat=0 )
} }
Mat imdecode( const Mat& buf, int flags ) Mat imdecode( const InputArray& _buf, int flags )
{ {
Mat img; Mat buf = _buf.getMat(), img;
imdecode_( buf, flags, LOAD_MAT, &img ); imdecode_( buf, flags, LOAD_MAT, &img );
return img; return img;
} }
bool imencode( const string& ext, const Mat& image, bool imencode( const string& ext, const InputArray& _image,
vector<uchar>& buf, const vector<int>& params ) vector<uchar>& buf, const vector<int>& params )
{ {
Mat temp; Mat temp, image = _image.getMat();
const Mat* pimage = &image; const Mat* pimage = &image;
int channels = image.channels(); int channels = image.channels();

@ -126,41 +126,38 @@ CV_IMPL double cvGetWindowProperty(const char* name, int prop_id)
} }
} }
namespace cv void cv::namedWindow( const string& winname, int flags )
{
void namedWindow( const string& winname, int flags )
{ {
cvNamedWindow( winname.c_str(), flags ); cvNamedWindow( winname.c_str(), flags );
} }
void destroyWindow( const string& winname ) void cv::destroyWindow( const string& winname )
{ {
cvDestroyWindow( winname.c_str() ); cvDestroyWindow( winname.c_str() );
} }
void setWindowProperty(const string& winname, int prop_id, double prop_value) void cv::setWindowProperty(const string& winname, int prop_id, double prop_value)
{ {
cvSetWindowProperty( winname.c_str(),prop_id,prop_value); cvSetWindowProperty( winname.c_str(),prop_id,prop_value);
} }
double getWindowProperty(const string& winname, int prop_id) double cv::getWindowProperty(const string& winname, int prop_id)
{ {
return cvGetWindowProperty(winname.c_str(),prop_id); return cvGetWindowProperty(winname.c_str(),prop_id);
} }
void imshow( const string& winname, const Mat& img ) void cv::imshow( const string& winname, const InputArray& img )
{ {
CvMat _img = img; CvMat c_img = img.getMat();
cvShowImage( winname.c_str(), &_img ); cvShowImage( winname.c_str(), &c_img );
} }
int waitKey(int delay) int cv::waitKey(int delay)
{ {
return cvWaitKey(delay); return cvWaitKey(delay);
} }
int createTrackbar(const string& trackbarName, const string& winName, int cv::createTrackbar(const string& trackbarName, const string& winName,
int* value, int count, TrackbarCallback callback, int* value, int count, TrackbarCallback callback,
void* userdata) void* userdata)
{ {
@ -168,83 +165,81 @@ int createTrackbar(const string& trackbarName, const string& winName,
value, count, callback, userdata); value, count, callback, userdata);
} }
void setTrackbarPos( const string& trackbarName, const string& winName, int value ) void cv::setTrackbarPos( const string& trackbarName, const string& winName, int value )
{ {
cvSetTrackbarPos(trackbarName.c_str(), winName.c_str(), value ); cvSetTrackbarPos(trackbarName.c_str(), winName.c_str(), value );
} }
int getTrackbarPos( const string& trackbarName, const string& winName ) int cv::getTrackbarPos( const string& trackbarName, const string& winName )
{ {
return cvGetTrackbarPos(trackbarName.c_str(), winName.c_str()); return cvGetTrackbarPos(trackbarName.c_str(), winName.c_str());
} }
void setMouseCallback( const string& windowName, MouseCallback onMouse, void* param) void cv::setMouseCallback( const string& windowName, MouseCallback onMouse, void* param)
{ {
cvSetMouseCallback(windowName.c_str(), onMouse, param); cvSetMouseCallback(windowName.c_str(), onMouse, param);
} }
int startWindowThread() int cv::startWindowThread()
{ {
return cvStartWindowThread(); return cvStartWindowThread();
} }
#if defined (HAVE_QT) #if defined (HAVE_QT)
CvFont fontQt(const string& nameFont, int pointSize, Scalar color, int weight, int style, int spacing) CvFont cv::fontQt(const string& nameFont, int pointSize, Scalar color, int weight, int style, int spacing)
{ {
return cvFontQt(nameFont.c_str(), pointSize,color,weight, style); return cvFontQt(nameFont.c_str(), pointSize,color,weight, style);
} }
void addText( const Mat& img, const string& text, Point org, CvFont font) void cv::addText( const Mat& img, const string& text, Point org, CvFont font)
{ {
CvMat _img = img; CvMat _img = img;
cvAddText( &_img, text.c_str(), org,&font); cvAddText( &_img, text.c_str(), org,&font);
} }
void displayStatusBar(const string& name, const string& text, int delayms) void cv::displayStatusBar(const string& name, const string& text, int delayms)
{ {
cvDisplayStatusBar(name.c_str(),text.c_str(), delayms); cvDisplayStatusBar(name.c_str(),text.c_str(), delayms);
} }
void createOpenGLCallback(const string& name, OpenGLCallback callback, void* param) void cv::createOpenGLCallback(const string& name, OpenGLCallback callback, void* param)
{ {
cvCreateOpenGLCallback(name.c_str(),callback, param); cvCreateOpenGLCallback(name.c_str(),callback, param);
} }
void displayOverlay(const string& name, const string& text, int delayms) void cv::displayOverlay(const string& name, const string& text, int delayms)
{ {
cvDisplayOverlay(name.c_str(),text.c_str(), delayms); cvDisplayOverlay(name.c_str(),text.c_str(), delayms);
} }
int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]) int cv::startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
{ {
return cvStartLoop(pt2Func, argc, argv); return cvStartLoop(pt2Func, argc, argv);
} }
void stopLoop() void cv::stopLoop()
{ {
cvStopLoop(); cvStopLoop();
} }
void saveWindowParameters(const string& windowName) void cv::saveWindowParameters(const string& windowName)
{ {
cvSaveWindowParameters(windowName.c_str()); cvSaveWindowParameters(windowName.c_str());
} }
void loadWindowParameters(const string& windowName) void cv::loadWindowParameters(const string& windowName)
{ {
cvLoadWindowParameters(windowName.c_str()); cvLoadWindowParameters(windowName.c_str());
} }
int createButton(const string& button_name, ButtonCallback on_change, void* userdata, int button_type , bool initial_button_state ) int cv::createButton(const string& button_name, ButtonCallback on_change, void* userdata, int button_type , bool initial_button_state )
{ {
return cvCreateButton(button_name.c_str(), on_change, userdata, button_type , initial_button_state ); return cvCreateButton(button_name.c_str(), on_change, userdata, button_type , initial_button_state );
} }
#endif #endif
}
#if defined WIN32 || defined _WIN32 // see window_w32.cpp #if defined WIN32 || defined _WIN32 // see window_w32.cpp
#elif defined (HAVE_GTK) // see window_gtk.cpp #elif defined (HAVE_GTK) // see window_gtk.cpp
#elif defined (HAVE_COCOA) // see window_carbon.cpp #elif defined (HAVE_COCOA) // see window_carbon.cpp

@ -287,28 +287,28 @@ enum { KERNEL_GENERAL=0, KERNEL_SYMMETRICAL=1, KERNEL_ASYMMETRICAL=2,
KERNEL_SMOOTH=4, KERNEL_INTEGER=8 }; KERNEL_SMOOTH=4, KERNEL_INTEGER=8 };
//! returns type (one of KERNEL_*) of 1D or 2D kernel specified by its coefficients. //! returns type (one of KERNEL_*) of 1D or 2D kernel specified by its coefficients.
CV_EXPORTS int getKernelType(const Mat& kernel, Point anchor); CV_EXPORTS int getKernelType(const InputArray& kernel, Point anchor);
//! returns the primitive row filter with the specified kernel //! returns the primitive row filter with the specified kernel
CV_EXPORTS Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType, CV_EXPORTS Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType,
const Mat& kernel, int anchor, const InputArray& kernel, int anchor,
int symmetryType); int symmetryType);
//! returns the primitive column filter with the specified kernel //! returns the primitive column filter with the specified kernel
CV_EXPORTS Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType, CV_EXPORTS Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType,
const Mat& kernel, int anchor, const InputArray& kernel, int anchor,
int symmetryType, double delta=0, int symmetryType, double delta=0,
int bits=0); int bits=0);
//! returns 2D filter with the specified kernel //! returns 2D filter with the specified kernel
CV_EXPORTS Ptr<BaseFilter> getLinearFilter(int srcType, int dstType, CV_EXPORTS Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,
const Mat& kernel, const InputArray& kernel,
Point anchor=Point(-1,-1), Point anchor=Point(-1,-1),
double delta=0, int bits=0); double delta=0, int bits=0);
//! returns the separable linear filter engine //! returns the separable linear filter engine
CV_EXPORTS Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType, CV_EXPORTS Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType,
const Mat& rowKernel, const Mat& columnKernel, const InputArray& rowKernel, const InputArray& columnKernel,
Point _anchor=Point(-1,-1), double delta=0, Point _anchor=Point(-1,-1), double delta=0,
int _rowBorderType=BORDER_DEFAULT, int _rowBorderType=BORDER_DEFAULT,
int _columnBorderType=-1, int _columnBorderType=-1,
@ -316,7 +316,7 @@ CV_EXPORTS Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstTyp
//! returns the non-separable linear filter engine //! returns the non-separable linear filter engine
CV_EXPORTS Ptr<FilterEngine> createLinearFilter(int srcType, int dstType, CV_EXPORTS Ptr<FilterEngine> createLinearFilter(int srcType, int dstType,
const Mat& kernel, Point _anchor=Point(-1,-1), const InputArray& kernel, Point _anchor=Point(-1,-1),
double delta=0, int _rowBorderType=BORDER_DEFAULT, double delta=0, int _rowBorderType=BORDER_DEFAULT,
int _columnBorderType=-1, const Scalar& _borderValue=Scalar()); int _columnBorderType=-1, const Scalar& _borderValue=Scalar());
@ -328,7 +328,7 @@ CV_EXPORTS Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,
double sigma1, double sigma2=0, double sigma1, double sigma2=0,
int borderType=BORDER_DEFAULT); int borderType=BORDER_DEFAULT);
//! initializes kernels of the generalized Sobel operator //! initializes kernels of the generalized Sobel operator
CV_EXPORTS_W void getDerivKernels( CV_OUT Mat& kx, CV_OUT Mat& ky, CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky,
int dx, int dy, int ksize, int dx, int dy, int ksize,
bool normalize=false, int ktype=CV_32F ); bool normalize=false, int ktype=CV_32F );
//! returns filter engine for the generalized Sobel operator //! returns filter engine for the generalized Sobel operator
@ -358,14 +358,14 @@ CV_EXPORTS Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int ksize
//! returns vertical 1D morphological filter //! returns vertical 1D morphological filter
CV_EXPORTS Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int anchor=-1); CV_EXPORTS Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int anchor=-1);
//! returns 2D morphological filter //! returns 2D morphological filter
CV_EXPORTS Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat& kernel, CV_EXPORTS Ptr<BaseFilter> getMorphologyFilter(int op, int type, const InputArray& kernel,
Point anchor=Point(-1,-1)); Point anchor=Point(-1,-1));
//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. //! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }
//! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported. //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
CV_EXPORTS Ptr<FilterEngine> createMorphologyFilter(int op, int type, const Mat& kernel, CV_EXPORTS Ptr<FilterEngine> createMorphologyFilter(int op, int type, const InputArray& kernel,
Point anchor=Point(-1,-1), int _rowBorderType=BORDER_CONSTANT, Point anchor=Point(-1,-1), int _rowBorderType=BORDER_CONSTANT,
int _columnBorderType=-1, int _columnBorderType=-1,
const Scalar& _borderValue=morphologyDefaultBorderValue()); const Scalar& _borderValue=morphologyDefaultBorderValue());
@ -378,123 +378,124 @@ CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor=Point
template<> CV_EXPORTS void Ptr<IplConvKernel>::delete_obj(); template<> CV_EXPORTS void Ptr<IplConvKernel>::delete_obj();
//! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode //! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode
CV_EXPORTS_W void copyMakeBorder( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void copyMakeBorder( const InputArray& src, OutputArray dst,
int top, int bottom, int left, int right, int top, int bottom, int left, int right,
int borderType, const Scalar& value=Scalar() ); int borderType, const Scalar& value=Scalar() );
//! smooths the image using median filter. //! smooths the image using median filter.
CV_EXPORTS_W void medianBlur( const Mat& src, CV_OUT Mat& dst, int ksize ); CV_EXPORTS_W void medianBlur( const InputArray& src, OutputArray dst, int ksize );
//! smooths the image using Gaussian filter. //! smooths the image using Gaussian filter.
CV_EXPORTS_AS(gaussianBlur) void GaussianBlur( const Mat& src, CV_OUT Mat& dst, Size ksize, CV_EXPORTS_AS(gaussianBlur) void GaussianBlur( const InputArray& src,
OutputArray dst, Size ksize,
double sigma1, double sigma2=0, double sigma1, double sigma2=0,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! smooths the image using bilateral filter //! smooths the image using bilateral filter
CV_EXPORTS_W void bilateralFilter( const Mat& src, CV_OUT Mat& dst, int d, CV_EXPORTS_W void bilateralFilter( const InputArray& src, OutputArray dst, int d,
double sigmaColor, double sigmaSpace, double sigmaColor, double sigmaSpace,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! smooths the image using the box filter. Each pixel is processed in O(1) time //! smooths the image using the box filter. Each pixel is processed in O(1) time
CV_EXPORTS_W void boxFilter( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_W void boxFilter( const InputArray& src, OutputArray dst, int ddepth,
Size ksize, Point anchor=Point(-1,-1), Size ksize, Point anchor=Point(-1,-1),
bool normalize=true, bool normalize=true,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! a synonym for normalized box filter //! a synonym for normalized box filter
CV_EXPORTS_W void blur( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void blur( const InputArray& src, OutputArray dst,
Size ksize, Point anchor=Point(-1,-1), Size ksize, Point anchor=Point(-1,-1),
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! applies non-separable 2D linear filter to the image //! applies non-separable 2D linear filter to the image
CV_EXPORTS_W void filter2D( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_W void filter2D( const InputArray& src, OutputArray dst, int ddepth,
const Mat& kernel, Point anchor=Point(-1,-1), const InputArray& kernel, Point anchor=Point(-1,-1),
double delta=0, int borderType=BORDER_DEFAULT ); double delta=0, int borderType=BORDER_DEFAULT );
//! applies separable 2D linear filter to the image //! applies separable 2D linear filter to the image
CV_EXPORTS_W void sepFilter2D( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_W void sepFilter2D( const InputArray& src, OutputArray dst, int ddepth,
const Mat& kernelX, const Mat& kernelY, const InputArray& kernelX, const InputArray& kernelY,
Point anchor=Point(-1,-1), Point anchor=Point(-1,-1),
double delta=0, int borderType=BORDER_DEFAULT ); double delta=0, int borderType=BORDER_DEFAULT );
//! applies generalized Sobel operator to the image //! applies generalized Sobel operator to the image
CV_EXPORTS_AS(sobel) void Sobel( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_AS(sobel) void Sobel( const InputArray& src, OutputArray dst, int ddepth,
int dx, int dy, int ksize=3, int dx, int dy, int ksize=3,
double scale=1, double delta=0, double scale=1, double delta=0,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! applies the vertical or horizontal Scharr operator to the image //! applies the vertical or horizontal Scharr operator to the image
CV_EXPORTS_AS(scharr) void Scharr( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_AS(scharr) void Scharr( const InputArray& src, OutputArray dst, int ddepth,
int dx, int dy, double scale=1, double delta=0, int dx, int dy, double scale=1, double delta=0,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! applies Laplacian operator to the image //! applies Laplacian operator to the image
CV_EXPORTS_AS(laplacian) void Laplacian( const Mat& src, CV_OUT Mat& dst, int ddepth, CV_EXPORTS_AS(laplacian) void Laplacian( const InputArray& src, OutputArray dst, int ddepth,
int ksize=1, double scale=1, double delta=0, int ksize=1, double scale=1, double delta=0,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! applies Canny edge detector and produces the edge map. //! applies Canny edge detector and produces the edge map.
CV_EXPORTS_AS(canny) void Canny( const Mat& image, CV_OUT Mat& edges, CV_EXPORTS_AS(canny) void Canny( const InputArray& image, OutputArray edges,
double threshold1, double threshold2, double threshold1, double threshold2,
int apertureSize=3, bool L2gradient=false ); int apertureSize=3, bool L2gradient=false );
//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria //! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
CV_EXPORTS_W void cornerMinEigenVal( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void cornerMinEigenVal( const InputArray& src, OutputArray dst,
int blockSize, int ksize=3, int blockSize, int ksize=3,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! computes Harris cornerness criteria at each image pixel //! computes Harris cornerness criteria at each image pixel
CV_EXPORTS_W void cornerHarris( const Mat& src, CV_OUT Mat& dst, int blockSize, CV_EXPORTS_W void cornerHarris( const InputArray& src, OutputArray dst, int blockSize,
int ksize, double k, int ksize, double k,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix. //! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix.
CV_EXPORTS_W void cornerEigenValsAndVecs( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void cornerEigenValsAndVecs( const InputArray& src, OutputArray dst,
int blockSize, int ksize, int blockSize, int ksize,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! computes another complex cornerness criteria at each pixel //! computes another complex cornerness criteria at each pixel
CV_EXPORTS_W void preCornerDetect( const Mat& src, CV_OUT Mat& dst, int ksize, CV_EXPORTS_W void preCornerDetect( const InputArray& src, OutputArray dst, int ksize,
int borderType=BORDER_DEFAULT ); int borderType=BORDER_DEFAULT );
//! adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria //! adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria
CV_EXPORTS void cornerSubPix( const Mat& image, vector<Point2f>& corners, CV_EXPORTS void cornerSubPix( const InputArray& image, InputOutputArray corners,
Size winSize, Size zeroZone, Size winSize, Size zeroZone,
TermCriteria criteria ); TermCriteria criteria );
//! finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima //! finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima
CV_EXPORTS_W void goodFeaturesToTrack( const Mat& image, CV_OUT vector<Point2f>& corners, CV_EXPORTS_W void goodFeaturesToTrack( const InputArray& image, OutputArray corners,
int maxCorners, double qualityLevel, double minDistance, int maxCorners, double qualityLevel, double minDistance,
const Mat& mask=Mat(), int blockSize=3, const InputArray& mask=InputArray(), int blockSize=3,
bool useHarrisDetector=false, double k=0.04 ); bool useHarrisDetector=false, double k=0.04 );
//! finds lines in the black-n-white image using the standard or pyramid Hough transform //! finds lines in the black-n-white image using the standard or pyramid Hough transform
CV_EXPORTS_AS(houghLines) void HoughLines( const Mat& image, CV_OUT vector<Vec2f>& lines, CV_EXPORTS_AS(houghLines) void HoughLines( const InputArray& image, OutputArray lines,
double rho, double theta, int threshold, double rho, double theta, int threshold,
double srn=0, double stn=0 ); double srn=0, double stn=0 );
//! finds line segments in the black-n-white image using probabalistic Hough transform //! finds line segments in the black-n-white image using probabalistic Hough transform
CV_EXPORTS_AS(houghLinesP) void HoughLinesP( Mat& image, CV_OUT vector<Vec4i>& lines, CV_EXPORTS_AS(houghLinesP) void HoughLinesP( const InputArray& image, OutputArray lines,
double rho, double theta, int threshold, double rho, double theta, int threshold,
double minLineLength=0, double maxLineGap=0 ); double minLineLength=0, double maxLineGap=0 );
//! finds circles in the grayscale image using 2+1 gradient Hough transform //! finds circles in the grayscale image using 2+1 gradient Hough transform
CV_EXPORTS_AS(houghCircles) void HoughCircles( const Mat& image, CV_OUT vector<Vec3f>& circles, CV_EXPORTS_AS(houghCircles) void HoughCircles( const InputArray& image, OutputArray circles,
int method, double dp, double minDist, int method, double dp, double minDist,
double param1=100, double param2=100, double param1=100, double param2=100,
int minRadius=0, int maxRadius=0 ); int minRadius=0, int maxRadius=0 );
//! erodes the image (applies the local minimum operator) //! erodes the image (applies the local minimum operator)
CV_EXPORTS_W void erode( const Mat& src, CV_OUT Mat& dst, const Mat& kernel, CV_EXPORTS_W void erode( const InputArray& src, OutputArray dst, const InputArray& kernel,
Point anchor=Point(-1,-1), int iterations=1, Point anchor=Point(-1,-1), int iterations=1,
int borderType=BORDER_CONSTANT, int borderType=BORDER_CONSTANT,
const Scalar& borderValue=morphologyDefaultBorderValue() ); const Scalar& borderValue=morphologyDefaultBorderValue() );
//! dilates the image (applies the local maximum operator) //! dilates the image (applies the local maximum operator)
CV_EXPORTS_W void dilate( const Mat& src, CV_OUT Mat& dst, const Mat& kernel, CV_EXPORTS_W void dilate( const InputArray& src, OutputArray dst, const InputArray& kernel,
Point anchor=Point(-1,-1), int iterations=1, Point anchor=Point(-1,-1), int iterations=1,
int borderType=BORDER_CONSTANT, int borderType=BORDER_CONSTANT,
const Scalar& borderValue=morphologyDefaultBorderValue() ); const Scalar& borderValue=morphologyDefaultBorderValue() );
//! applies an advanced morphological operation to the image //! applies an advanced morphological operation to the image
CV_EXPORTS_W void morphologyEx( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void morphologyEx( const InputArray& src, OutputArray dst,
int op, const Mat& kernel, int op, const InputArray& kernel,
Point anchor=Point(-1,-1), int iterations=1, Point anchor=Point(-1,-1), int iterations=1,
int borderType=BORDER_CONSTANT, int borderType=BORDER_CONSTANT,
const Scalar& borderValue=morphologyDefaultBorderValue() ); const Scalar& borderValue=morphologyDefaultBorderValue() );
@ -512,36 +513,40 @@ enum
}; };
//! resizes the image //! resizes the image
CV_EXPORTS_W void resize( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void resize( const InputArray& src, OutputArray dst,
Size dsize, double fx=0, double fy=0, Size dsize, double fx=0, double fy=0,
int interpolation=INTER_LINEAR ); int interpolation=INTER_LINEAR );
//! warps the image using affine transformation //! warps the image using affine transformation
CV_EXPORTS_W void warpAffine( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void warpAffine( const InputArray& src, OutputArray dst,
const Mat& M, Size dsize, const InputArray& M, Size dsize,
int flags=INTER_LINEAR, int flags=INTER_LINEAR,
int borderMode=BORDER_CONSTANT, int borderMode=BORDER_CONSTANT,
const Scalar& borderValue=Scalar()); const Scalar& borderValue=Scalar());
//! warps the image using perspective transformation //! warps the image using perspective transformation
CV_EXPORTS_W void warpPerspective( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void warpPerspective( const InputArray& src, OutputArray dst,
const Mat& M, Size dsize, const InputArray& M, Size dsize,
int flags=INTER_LINEAR, int flags=INTER_LINEAR,
int borderMode=BORDER_CONSTANT, int borderMode=BORDER_CONSTANT,
const Scalar& borderValue=Scalar()); const Scalar& borderValue=Scalar());
enum { INTER_BITS=5, INTER_BITS2=INTER_BITS*2, enum
{
INTER_BITS=5, INTER_BITS2=INTER_BITS*2,
INTER_TAB_SIZE=(1<<INTER_BITS), INTER_TAB_SIZE=(1<<INTER_BITS),
INTER_TAB_SIZE2=INTER_TAB_SIZE*INTER_TAB_SIZE }; INTER_TAB_SIZE2=INTER_TAB_SIZE*INTER_TAB_SIZE
};
//! warps the image using the precomputed maps. The maps are stored in either floating-point or integer fixed-point format //! warps the image using the precomputed maps. The maps are stored in either floating-point or integer fixed-point format
CV_EXPORTS_W void remap( const Mat& src, CV_OUT Mat& dst, const Mat& map1, const Mat& map2, CV_EXPORTS_W void remap( const InputArray& src, OutputArray dst,
const InputArray& map1, const InputArray& map2,
int interpolation, int borderMode=BORDER_CONSTANT, int interpolation, int borderMode=BORDER_CONSTANT,
const Scalar& borderValue=Scalar()); const Scalar& borderValue=Scalar());
//! converts maps for remap from floating-point to fixed-point format or backwards //! converts maps for remap from floating-point to fixed-point format or backwards
CV_EXPORTS_W void convertMaps( const Mat& map1, const Mat& map2, CV_EXPORTS_W void convertMaps( const InputArray& map1, const InputArray& map2,
CV_OUT Mat& dstmap1, CV_OUT Mat& dstmap2, OutputArray dstmap1, OutputArray dstmap2,
int dstmap1type, bool nninterpolation=false ); int dstmap1type, bool nninterpolation=false );
//! returns 2x3 affine transformation matrix for the planar rotation. //! returns 2x3 affine transformation matrix for the planar rotation.
@ -551,29 +556,34 @@ CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[]
//! returns 2x3 affine transformation for the corresponding 3 point pairs. //! returns 2x3 affine transformation for the corresponding 3 point pairs.
CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] );
//! computes 2x3 affine transformation matrix that is inverse to the specified 2x3 affine transformation. //! computes 2x3 affine transformation matrix that is inverse to the specified 2x3 affine transformation.
CV_EXPORTS_W void invertAffineTransform( const Mat& M, CV_OUT Mat& iM ); CV_EXPORTS_W void invertAffineTransform( const InputArray& M, OutputArray iM );
//! extracts rectangle from the image at sub-pixel location //! extracts rectangle from the image at sub-pixel location
CV_EXPORTS_W void getRectSubPix( const Mat& image, Size patchSize, CV_EXPORTS_W void getRectSubPix( const InputArray& image, Size patchSize,
Point2f center, CV_OUT Mat& patch, int patchType=-1 ); Point2f center, OutputArray patch, int patchType=-1 );
//! computes the integral image //! computes the integral image
CV_EXPORTS_W void integral( const Mat& src, CV_OUT Mat& sum, int sdepth=-1 ); CV_EXPORTS_W void integral( const InputArray& src, OutputArray sum, int sdepth=-1 );
//! computes the integral image and integral for the squared image //! computes the integral image and integral for the squared image
CV_EXPORTS_AS(integral2) void integral( const Mat& src, CV_OUT Mat& sum, CV_OUT Mat& sqsum, int sdepth=-1 ); CV_EXPORTS_AS(integral2) void integral( const InputArray& src, OutputArray sum,
OutputArray sqsum, int sdepth=-1 );
//! computes the integral image, integral for the squared image and the tilted integral image //! computes the integral image, integral for the squared image and the tilted integral image
CV_EXPORTS_AS(integral3) void integral( const Mat& src, CV_OUT Mat& sum, CV_OUT Mat& sqsum, CV_OUT Mat& tilted, int sdepth=-1 ); CV_EXPORTS_AS(integral3) void integral( const InputArray& src, OutputArray sum,
OutputArray sqsum, OutputArray tilted,
int sdepth=-1 );
//! adds image to the accumulator (dst += src). Unlike cv::add, dst and src can have different types. //! adds image to the accumulator (dst += src). Unlike cv::add, dst and src can have different types.
CV_EXPORTS_W void accumulate( const Mat& src, CV_IN_OUT Mat& dst, const Mat& mask=Mat() ); CV_EXPORTS_W void accumulate( const InputArray& src, CV_IN_OUT InputOutputArray dst,
const InputArray& mask=InputArray() );
//! adds squared src image to the accumulator (dst += src*src). //! adds squared src image to the accumulator (dst += src*src).
CV_EXPORTS_W void accumulateSquare( const Mat& src, CV_IN_OUT Mat& dst, const Mat& mask=Mat() ); CV_EXPORTS_W void accumulateSquare( const InputArray& src, CV_IN_OUT InputOutputArray dst,
const InputArray& mask=InputArray() );
//! adds product of the 2 images to the accumulator (dst += src1*src2). //! adds product of the 2 images to the accumulator (dst += src1*src2).
CV_EXPORTS_W void accumulateProduct( const Mat& src1, const Mat& src2, CV_EXPORTS_W void accumulateProduct( const InputArray& src1, const InputArray& src2,
CV_IN_OUT Mat& dst, const Mat& mask=Mat() ); CV_IN_OUT InputOutputArray dst, const InputArray& mask=InputArray() );
//! updates the running average (dst = dst*(1-alpha) + src*alpha) //! updates the running average (dst = dst*(1-alpha) + src*alpha)
CV_EXPORTS_W void accumulateWeighted( const Mat& src, CV_IN_OUT Mat& dst, CV_EXPORTS_W void accumulateWeighted( const InputArray& src, CV_IN_OUT InputOutputArray dst,
double alpha, const Mat& mask=Mat() ); double alpha, const InputArray& mask=InputArray() );
//! type of the threshold operation //! type of the threshold operation
enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV, enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV,
@ -582,30 +592,37 @@ enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV,
THRESH_OTSU=CV_THRESH_OTSU }; THRESH_OTSU=CV_THRESH_OTSU };
//! applies fixed threshold to the image //! applies fixed threshold to the image
CV_EXPORTS_W double threshold( const Mat& src, CV_OUT Mat& dst, double thresh, double maxval, int type ); CV_EXPORTS_W double threshold( const InputArray& src, OutputArray dst,
double thresh, double maxval, int type );
//! adaptive threshold algorithm //! adaptive threshold algorithm
enum { ADAPTIVE_THRESH_MEAN_C=0, ADAPTIVE_THRESH_GAUSSIAN_C=1 }; enum { ADAPTIVE_THRESH_MEAN_C=0, ADAPTIVE_THRESH_GAUSSIAN_C=1 };
//! applies variable (adaptive) threshold to the image //! applies variable (adaptive) threshold to the image
CV_EXPORTS_W void adaptiveThreshold( const Mat& src, CV_OUT Mat& dst, double maxValue, CV_EXPORTS_W void adaptiveThreshold( const InputArray& src, OutputArray dst,
int adaptiveMethod, int thresholdType, double maxValue, int adaptiveMethod,
int blockSize, double C ); int thresholdType, int blockSize, double C );
//! smooths and downsamples the image //! smooths and downsamples the image
CV_EXPORTS_W void pyrDown( const Mat& src, CV_OUT Mat& dst, const Size& dstsize=Size()); CV_EXPORTS_W void pyrDown( const InputArray& src, OutputArray dst,
const Size& dstsize=Size());
//! upsamples and smoothes the image //! upsamples and smoothes the image
CV_EXPORTS_W void pyrUp( const Mat& src, CV_OUT Mat& dst, const Size& dstsize=Size()); CV_EXPORTS_W void pyrUp( const InputArray& src, OutputArray dst,
const Size& dstsize=Size());
//! builds the gaussian pyramid using pyrDown() as a basic operation //! builds the gaussian pyramid using pyrDown() as a basic operation
CV_EXPORTS void buildPyramid( const Mat& src, CV_OUT vector<Mat>& dst, int maxlevel ); CV_EXPORTS void buildPyramid( const InputArray& src, OutputArrayOfArrays dst, int maxlevel );
//! corrects lens distortion for the given camera matrix and distortion coefficients //! corrects lens distortion for the given camera matrix and distortion coefficients
CV_EXPORTS_W void undistort( const Mat& src, CV_OUT Mat& dst, const Mat& cameraMatrix, CV_EXPORTS_W void undistort( const InputArray& src, OutputArray dst,
const Mat& distCoeffs, const Mat& newCameraMatrix=Mat() ); const InputArray& cameraMatrix,
const InputArray& distCoeffs,
const InputArray& newCameraMatrix=InputArray() );
//! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image //! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image
CV_EXPORTS_W void initUndistortRectifyMap( const Mat& cameraMatrix, const Mat& distCoeffs, CV_EXPORTS_W void initUndistortRectifyMap( const InputArray& cameraMatrix, const InputArray& distCoeffs,
const Mat& R, const Mat& newCameraMatrix, const InputArray& R, const InputArray& newCameraMatrix,
Size size, int m1type, CV_OUT Mat& map1, CV_OUT Mat& map2 ); Size size, int m1type, OutputArray map1, OutputArray map2 );
enum enum
{ {
@ -614,42 +631,39 @@ enum
}; };
//! initializes maps for cv::remap() for wide-angle //! initializes maps for cv::remap() for wide-angle
CV_EXPORTS_W float initWideAngleProjMap( const Mat& cameraMatrix, const Mat& distCoeffs, CV_EXPORTS_W float initWideAngleProjMap( const InputArray& cameraMatrix, const InputArray& distCoeffs,
Size imageSize, int destImageWidth, Size imageSize, int destImageWidth,
int m1type, CV_OUT Mat& map1, CV_OUT Mat& map2, int m1type, OutputArray map1, OutputArray map2,
int projType=PROJ_SPHERICAL_EQRECT, double alpha=0); int projType=PROJ_SPHERICAL_EQRECT, double alpha=0);
//! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true) //! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true)
CV_EXPORTS_W Mat getDefaultNewCameraMatrix( const Mat& cameraMatrix, Size imgsize=Size(), CV_EXPORTS_W Mat getDefaultNewCameraMatrix( const InputArray& cameraMatrix, Size imgsize=Size(),
bool centerPrincipalPoint=false ); bool centerPrincipalPoint=false );
//! returns points' coordinates after lens distortion correction //! returns points' coordinates after lens distortion correction
CV_EXPORTS void undistortPoints( const Mat& src, CV_OUT vector<Point2f>& dst, CV_EXPORTS void undistortPoints( const InputArray& src, OutputArray dst,
const Mat& cameraMatrix, const Mat& distCoeffs, const InputArray& cameraMatrix, const InputArray& distCoeffs,
const Mat& R=Mat(), const Mat& P=Mat()); const InputArray& R=InputArray(), const InputArray& P=InputArray());
//! returns points' coordinates after lens distortion correction
CV_EXPORTS_W void undistortPoints( const Mat& src, CV_OUT Mat& dst,
const Mat& cameraMatrix, const Mat& distCoeffs,
const Mat& R=Mat(), const Mat& P=Mat());
template<> CV_EXPORTS void Ptr<CvHistogram>::delete_obj(); template<> CV_EXPORTS void Ptr<CvHistogram>::delete_obj();
//! computes the joint dense histogram for a set of images. //! computes the joint dense histogram for a set of images.
CV_EXPORTS void calcHist( const Mat* images, int nimages, CV_EXPORTS void calcHist( const Mat* images, int nimages,
const int* channels, const Mat& mask, const int* channels, const InputArray& mask,
Mat& hist, int dims, const int* histSize, OutputArray hist, int dims, const int* histSize,
const float** ranges, bool uniform=true, bool accumulate=false ); const float** ranges, bool uniform=true, bool accumulate=false );
//! computes the joint sparse histogram for a set of images. //! computes the joint sparse histogram for a set of images.
CV_EXPORTS void calcHist( const Mat* images, int nimages, CV_EXPORTS void calcHist( const Mat* images, int nimages,
const int* channels, const Mat& mask, const int* channels, const InputArray& mask,
SparseMat& hist, int dims, SparseMat& hist, int dims,
const int* histSize, const float** ranges, const int* histSize, const float** ranges,
bool uniform=true, bool accumulate=false ); bool uniform=true, bool accumulate=false );
//! computes back projection for the set of images //! computes back projection for the set of images
CV_EXPORTS void calcBackProject( const Mat* images, int nimages, CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
const int* channels, const Mat& hist, const int* channels, const InputArray& hist,
Mat& backProject, const float** ranges, OutputArray backProject, const float** ranges,
double scale=1, bool uniform=true ); double scale=1, bool uniform=true );
//! computes back projection for the set of images //! computes back projection for the set of images
@ -659,25 +673,26 @@ CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
double scale=1, bool uniform=true ); double scale=1, bool uniform=true );
//! compares two histograms stored in dense arrays //! compares two histograms stored in dense arrays
CV_EXPORTS_W double compareHist( const Mat& H1, const Mat& H2, int method ); CV_EXPORTS_W double compareHist( const InputArray& H1, const InputArray& H2, int method );
//! compares two histograms stored in sparse arrays //! compares two histograms stored in sparse arrays
CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
//! normalizes the grayscale image brightness and contrast by normalizing its histogram //! normalizes the grayscale image brightness and contrast by normalizing its histogram
CV_EXPORTS_W void equalizeHist( const Mat& src, CV_OUT Mat& dst ); CV_EXPORTS_W void equalizeHist( const InputArray& src, OutputArray dst );
CV_EXPORTS float EMD( const Mat& signature1, const Mat& signature2, CV_EXPORTS float EMD( const InputArray& signature1, const InputArray& signature2,
int distType, const Mat& cost=Mat(), int distType, const InputArray& cost=InputArray(),
float* lowerBound=0, Mat* flow=0 ); float* lowerBound=0, OutputArray flow=OutputArray() );
//! segments the image using watershed algorithm //! segments the image using watershed algorithm
CV_EXPORTS_W void watershed( const Mat& image, Mat& markers ); CV_EXPORTS_W void watershed( const InputArray& image, InputOutputArray markers );
//! filters image using meanshift algorithm //! filters image using meanshift algorithm
CV_EXPORTS_W void pyrMeanShiftFiltering( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS_W void pyrMeanShiftFiltering( const InputArray& src, OutputArray dst,
double sp, double sr, int maxLevel=1, double sp, double sr, int maxLevel=1,
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); TermCriteria termcrit=TermCriteria(
TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
//! class of the pixel in GrabCut algorithm //! class of the pixel in GrabCut algorithm
enum enum
@ -697,8 +712,8 @@ enum
}; };
//! segments the image using GrabCut algorithm //! segments the image using GrabCut algorithm
CV_EXPORTS_W void grabCut( const Mat& img, Mat& mask, Rect rect, CV_EXPORTS_W void grabCut( const InputArray& img, InputOutputArray mask, Rect rect,
Mat& bgdModel, Mat& fgdModel, InputOutputArray bgdModel, InputOutputArray fgdModel,
int iterCount, int mode = GC_EVAL ); int iterCount, int mode = GC_EVAL );
//! the inpainting algorithm //! the inpainting algorithm
@ -709,35 +724,33 @@ enum
}; };
//! restores the damaged image areas using one of the available intpainting algorithms //! restores the damaged image areas using one of the available intpainting algorithms
CV_EXPORTS_W void inpaint( const Mat& src, const Mat& inpaintMask, CV_EXPORTS_W void inpaint( const InputArray& src, const InputArray& inpaintMask,
CV_OUT Mat& dst, double inpaintRange, int flags ); OutputArray dst, double inpaintRange, int flags );
//! builds the discrete Voronoi diagram //! builds the discrete Voronoi diagram
CV_EXPORTS_AS(distanceTransformWithLabels) CV_EXPORTS_W void distanceTransform( const InputArray& src, OutputArray dst,
void distanceTransform( const Mat& src, CV_OUT Mat& dst, Mat& labels, OutputArray labels, int distanceType, int maskSize );
int distanceType, int maskSize );
//! computes the distance transform map //! computes the distance transform map
CV_EXPORTS_W void distanceTransform( const Mat& src, CV_OUT Mat& dst, CV_EXPORTS void distanceTransform( const InputArray& src, OutputArray dst,
int distanceType, int maskSize ); int distanceType, int maskSize );
enum { FLOODFILL_FIXED_RANGE = 1 << 16, enum { FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17 };
FLOODFILL_MASK_ONLY = 1 << 17 };
//! fills the semi-uniform image region starting from the specified seed point //! fills the semi-uniform image region starting from the specified seed point
CV_EXPORTS_W int floodFill( Mat& image, CV_EXPORTS int floodFill( InputOutputArray image,
Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
int flags=4 ); int flags=4 );
//! fills the semi-uniform image region and/or the mask starting from the specified seed point //! fills the semi-uniform image region and/or the mask starting from the specified seed point
CV_EXPORTS_AS(floodFillMask) int floodFill( Mat& image, Mat& mask, CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
int flags=4 ); int flags=4 );
//! converts image from one color space to another //! converts image from one color space to another
CV_EXPORTS_W void cvtColor( const Mat& src, CV_OUT Mat& dst, int code, int dstCn=0 ); CV_EXPORTS_W void cvtColor( const InputArray& src, OutputArray dst, int code, int dstCn=0 );
//! raster image moments //! raster image moments
class CV_EXPORTS_W_MAP Moments class CV_EXPORTS_W_MAP Moments
@ -762,7 +775,7 @@ public:
}; };
//! computes moments of the rasterized shape or a vector of points //! computes moments of the rasterized shape or a vector of points
CV_EXPORTS_W Moments moments( const Mat& array, bool binaryImage=false ); CV_EXPORTS_W Moments moments( const InputArray& array, bool binaryImage=false );
//! computes 7 Hu invariants from the moments //! computes 7 Hu invariants from the moments
CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
@ -771,7 +784,8 @@ CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
enum { TM_SQDIFF=0, TM_SQDIFF_NORMED=1, TM_CCORR=2, TM_CCORR_NORMED=3, TM_CCOEFF=4, TM_CCOEFF_NORMED=5 }; enum { TM_SQDIFF=0, TM_SQDIFF_NORMED=1, TM_CCORR=2, TM_CCORR_NORMED=3, TM_CCOEFF=4, TM_CCOEFF_NORMED=5 };
//! computes the proximity map for the raster template and the image where the template is searched for //! computes the proximity map for the raster template and the image where the template is searched for
CV_EXPORTS_W void matchTemplate( const Mat& image, const Mat& templ, CV_OUT Mat& result, int method ); CV_EXPORTS_W void matchTemplate( const InputArray& image, const InputArray& templ,
OutputArray result, int method );
//! mode of the contour retrieval algorithm //! mode of the contour retrieval algorithm
enum enum
@ -792,74 +806,58 @@ enum
}; };
//! retrieves contours and the hierarchical information from black-n-white image. //! retrieves contours and the hierarchical information from black-n-white image.
CV_EXPORTS void findContours( Mat& image, CV_OUT vector<vector<Point> >& contours, CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
vector<Vec4i>& hierarchy, int mode, OutputArray hierarchy, int mode,
int method, Point offset=Point()); int method, Point offset=Point());
//! retrieves contours from black-n-white image. //! retrieves contours from black-n-white image.
CV_EXPORTS void findContours( Mat& image, CV_OUT vector<vector<Point> >& contours, CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
int mode, int method, Point offset=Point()); int mode, int method, Point offset=Point());
//! draws contours in the image //! draws contours in the image
CV_EXPORTS void drawContours( Mat& image, const vector<vector<Point> >& contours, CV_EXPORTS void drawContours( InputOutputArray image, const InputArrayOfArrays& contours,
int contourIdx, const Scalar& color, int contourIdx, const Scalar& color,
int thickness=1, int lineType=8, int thickness=1, int lineType=8,
const vector<Vec4i>& hierarchy=vector<Vec4i>(), const InputArray& hierarchy=InputArray(),
int maxLevel=INT_MAX, Point offset=Point() ); int maxLevel=INT_MAX, Point offset=Point() );
//! approximates contour or a curve using Douglas-Peucker algorithm //! approximates contour or a curve using Douglas-Peucker algorithm
CV_EXPORTS void approxPolyDP( const Mat& curve, CV_EXPORTS void approxPolyDP( const InputArray& curve,
CV_OUT vector<Point>& approxCurve, OutputArray approxCurve,
double epsilon, bool closed );
//! approximates contour or a curve using Douglas-Peucker algorithm
CV_EXPORTS void approxPolyDP( const Mat& curve,
CV_OUT vector<Point2f>& approxCurve,
double epsilon, bool closed ); double epsilon, bool closed );
//! computes the contour perimeter (closed=true) or a curve length //! computes the contour perimeter (closed=true) or a curve length
CV_EXPORTS_W double arcLength( const Mat& curve, bool closed ); CV_EXPORTS_W double arcLength( const InputArray& curve, bool closed );
//! computes the bounding rectangle for a contour //! computes the bounding rectangle for a contour
CV_EXPORTS_W Rect boundingRect( const Mat& points ); CV_EXPORTS_W Rect boundingRect( const InputArray& points );
//! computes the contour area //! computes the contour area
CV_EXPORTS_W double contourArea( const Mat& contour, bool oriented=false ); CV_EXPORTS_W double contourArea( const InputArray& contour, bool oriented=false );
//! computes the minimal rotated rectangle for a set of points //! computes the minimal rotated rectangle for a set of points
CV_EXPORTS_W RotatedRect minAreaRect( const Mat& points ); CV_EXPORTS_W RotatedRect minAreaRect( const InputArray& points );
//! computes the minimal enclosing circle for a set of points //! computes the minimal enclosing circle for a set of points
CV_EXPORTS_W void minEnclosingCircle( const Mat& points, CV_EXPORTS_W void minEnclosingCircle( const InputArray& points,
Point2f& center, float& radius ); Point2f& center, float& radius );
//! matches two contours using one of the available algorithms //! matches two contours using one of the available algorithms
CV_EXPORTS_W double matchShapes( const Mat& contour1, CV_EXPORTS_W double matchShapes( const InputArray& contour1, const InputArray& contour2,
const Mat& contour2,
int method, double parameter ); int method, double parameter );
//! computes convex hull for a set of 2D points. //! computes convex hull for a set of 2D points.
CV_EXPORTS void convexHull( const Mat& points, CV_OUT vector<int>& hull, bool clockwise=false ); CV_EXPORTS void convexHull( const InputArray& points, OutputArray hull,
//! computes convex hull for a set of 2D points. bool clockwise=false, bool returnPoints=true );
CV_EXPORTS void convexHull( const Mat& points, CV_OUT vector<Point>& hull, bool clockwise=false );
//! computes convex hull for a set of 2D points.
CV_EXPORTS void convexHull( const Mat& points, CV_OUT vector<Point2f>& hull, bool clockwise=false );
//! returns true iff the contour is convex. Does not support contours with self-intersection //! returns true iff the contour is convex. Does not support contours with self-intersection
CV_EXPORTS_W bool isContourConvex( const Mat& contour ); CV_EXPORTS_W bool isContourConvex( const InputArray& contour );
//! fits ellipse to the set of 2D points //! fits ellipse to the set of 2D points
CV_EXPORTS_W RotatedRect fitEllipse( const Mat& points ); CV_EXPORTS_W RotatedRect fitEllipse( const InputArray& points );
//! fits line to the set of 2D points using M-estimator algorithm //! fits line to the set of 2D points using M-estimator algorithm
CV_EXPORTS void fitLine( const Mat& points, CV_OUT Vec4f& line, int distType, CV_EXPORTS void fitLine( const InputArray& points, OutputArray line, int distType,
double param, double reps, double aeps );
//! fits line to the set of 3D points using M-estimator algorithm
CV_EXPORTS void fitLine( const Mat& points, CV_OUT Vec6f& line, int distType,
double param, double reps, double aeps ); double param, double reps, double aeps );
//! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary //! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary
CV_EXPORTS_W double pointPolygonTest( const Mat& contour, CV_EXPORTS_W double pointPolygonTest( const InputArray& contour, Point2f pt, bool measureDist );
Point2f pt, bool measureDist );
//! estimates the best-fit affine transformation that maps one 2D point set to another or one image to another.
CV_EXPORTS_W Mat estimateRigidTransform( const Mat& A, const Mat& B,
bool fullAffine );
} }
// 2009-01-12, Xavier Delacour <xavier.delacour@gmail.com> // 2009-01-12, Xavier Delacour <xavier.delacour@gmail.com>
struct lsh_hash { struct lsh_hash {

@ -45,555 +45,406 @@
namespace cv namespace cv
{ {
inline float sqr(uchar a) { return CV_8TO32F_SQR(a); } template<typename T, typename AT> void
inline float sqr(float a) { return a*a; } acc_( const T* src, AT* dst, const uchar* mask, int len, int cn )
{
inline double sqr(double a) { return a*a; } int i = 0;
inline Vec3f sqr(const Vec3b& a) if( !mask )
{ {
return Vec3f(CV_8TO32F_SQR(a[0]), CV_8TO32F_SQR(a[1]), CV_8TO32F_SQR(a[2])); len *= cn;
} for( ; i <= len - 4; i += 4 )
inline Vec3f sqr(const Vec3f& a)
{ {
return Vec3f(a[0]*a[0], a[1]*a[1], a[2]*a[2]); AT t0, t1;
t0 = src[i] + dst[i];
t1 = src[i+1] + dst[i+1];
dst[i] = t0; dst[i+1] = t1;
t0 = src[i+2] + dst[i+2];
t1 = src[i+3] + dst[i+3];
dst[i+2] = t0; dst[i+3] = t1;
} }
inline Vec3d sqr(const Vec3d& a)
{ for( ; i < len; i++ )
return Vec3d(a[0]*a[0], a[1]*a[1], a[2]*a[2]); dst[i] += src[i];
} }
inline float multiply(uchar a, uchar b) { return CV_8TO32F(a)*CV_8TO32F(b); } else if( cn == 1 )
inline float multiply(float a, float b) { return a*b; }
inline double multiply(double a, double b) { return a*b; }
inline Vec3f multiply(const Vec3b& a, const Vec3b& b)
{ {
return Vec3f( for( ; i < len; i++ )
CV_8TO32F(a[0])*CV_8TO32F(b[0]),
CV_8TO32F(a[1])*CV_8TO32F(b[1]),
CV_8TO32F(a[2])*CV_8TO32F(b[2]));
}
inline Vec3f multiply(const Vec3f& a, const Vec3f& b)
{ {
return Vec3f(a[0]*b[0], a[1]*b[1], a[2]*b[2]); if( mask[i] )
dst[i] += src[i];
} }
inline Vec3d multiply(const Vec3d& a, const Vec3d& b)
{
return Vec3d(a[0]*b[0], a[1]*b[1], a[2]*b[2]);
} }
else if( cn == 3 )
inline float addw(uchar a, float alpha, float b, float beta)
{ {
return b*beta + CV_8TO32F(a)*alpha; for( ; i < len; i++, src += 3, dst += 3 )
}
inline float addw(float a, float alpha, float b, float beta)
{ {
return b*beta + a*alpha; if( mask[i] )
}
inline double addw(uchar a, double alpha, double b, double beta)
{ {
return b*beta + CV_8TO32F(a)*alpha; AT t0 = src[0] + dst[0];
AT t1 = src[1] + dst[1];
AT t2 = src[2] + dst[2];
dst[0] = t0; dst[1] = t1; dst[2] = t2;
} }
inline double addw(float a, double alpha, double b, double beta)
{
return b*beta + a*alpha;
} }
inline double addw(double a, double alpha, double b, double beta)
{
return b*beta + a*alpha;
} }
else
inline Vec3f addw(const Vec3b& a, float alpha, const Vec3f& b, float beta)
{
return Vec3f(b[0]*beta + CV_8TO32F(a[0])*alpha,
b[1]*beta + CV_8TO32F(a[1])*alpha,
b[2]*beta + CV_8TO32F(a[2])*alpha);
}
inline Vec3f addw(const Vec3f& a, float alpha, const Vec3f& b, float beta)
{ {
return Vec3f(b[0]*beta + a[0]*alpha, b[1]*beta + a[1]*alpha, b[2]*beta + a[2]*alpha); for( ; i < len; i++, src += cn, dst += cn )
} if( mask[i] )
inline Vec3d addw(const Vec3b& a, double alpha, const Vec3d& b, double beta)
{ {
return Vec3d(b[0]*beta + CV_8TO32F(a[0])*alpha, for( int k = 0; k < cn; k++ )
b[1]*beta + CV_8TO32F(a[1])*alpha, dst[k] += src[k];
b[2]*beta + CV_8TO32F(a[2])*alpha);
} }
inline Vec3d addw(const Vec3f& a, double alpha, const Vec3d& b, double beta)
{
return Vec3d(b[0]*beta + a[0]*alpha, b[1]*beta + a[1]*alpha, b[2]*beta + a[2]*alpha);
} }
inline Vec3d addw(const Vec3d& a, double alpha, const Vec3d& b, double beta)
{
return Vec3d(b[0]*beta + a[0]*alpha, b[1]*beta + a[1]*alpha, b[2]*beta + a[2]*alpha);
} }
template<typename T, typename AT> void template<typename T, typename AT> void
acc_( const Mat& _src, Mat& _dst ) accSqr_( const T* src, AT* dst, const uchar* mask, int len, int cn )
{ {
Size size = _src.size(); int i = 0;
size.width *= _src.channels();
if( _src.isContinuous() && _dst.isContinuous() ) if( !mask )
{ {
size.width *= size.height; len *= cn;
size.height = 1; for( ; i <= len - 4; i += 4 )
}
int i, j;
for( i = 0; i < size.height; i++ )
{ {
const T* src = (const T*)(_src.data + _src.step*i); AT t0, t1;
AT* dst = (AT*)(_dst.data + _dst.step*i); t0 = (AT)src[i]*src[i] + dst[i];
t1 = (AT)src[i+1]*src[i+1] + dst[i+1];
dst[i] = t0; dst[i+1] = t1;
for( j = 0; j <= size.width - 4; j += 4 ) t0 = (AT)src[i+2]*src[i+2] + dst[i+2];
{ t1 = (AT)src[i+3]*src[i+3] + dst[i+3];
AT t0 = dst[j] + src[j], t1 = dst[j+1] + src[j+1]; dst[i+2] = t0; dst[i+3] = t1;
dst[j] = t0; dst[j+1] = t1;
t0 = dst[j+2] + src[j+2]; t1 = dst[j+3] + src[j+3];
dst[j+2] = t0; dst[j+3] = t1;
} }
for( ; j < size.width; j++ ) for( ; i < len; i++ )
dst[j] += src[j]; dst[i] += (AT)src[i]*src[i];
}
} }
else if( cn == 1 )
template<typename T, typename AT> void
accSqr_( const Mat& _src, Mat& _dst )
{ {
Size size = _src.size(); for( ; i < len; i++ )
size.width *= _src.channels();
if( _src.isContinuous() && _dst.isContinuous() )
{ {
size.width *= size.height; if( mask[i] )
size.height = 1; dst[i] += (AT)src[i]*src[i];
} }
}
int i, j; else if( cn == 3 )
for( i = 0; i < size.height; i++ ) {
for( ; i < len; i++, src += 3, dst += 3 )
{ {
const T* src = (const T*)(_src.data + _src.step*i); if( mask[i] )
AT* dst = (AT*)(_dst.data + _dst.step*i); {
AT t0 = (AT)src[0]*src[0] + dst[0];
AT t1 = (AT)src[1]*src[1] + dst[1];
AT t2 = (AT)src[2]*src[2] + dst[2];
for( j = 0; j <= size.width - 4; j += 4 ) dst[0] = t0; dst[1] = t1; dst[2] = t2;
}
}
}
else
{
for( ; i < len; i++, src += cn, dst += cn )
if( mask[i] )
{ {
AT t0 = dst[j] + sqr(src[j]), t1 = dst[j+1] + sqr(src[j+1]); for( int k = 0; k < cn; k++ )
dst[j] = t0; dst[j+1] = t1; dst[k] += (AT)src[k]*src[k];
t0 = dst[j+2] + sqr(src[j+2]); t1 = dst[j+3] + sqr(src[j+3]);
dst[j+2] = t0; dst[j+3] = t1;
} }
for( ; j < size.width; j++ )
dst[j] += sqr(src[j]);
} }
} }
template<typename T, typename AT> void template<typename T, typename AT> void
accProd_( const Mat& _src1, const Mat& _src2, Mat& _dst ) accProd_( const T* src1, const T* src2, AT* dst, const uchar* mask, int len, int cn )
{
Size size = _src1.size();
size.width *= _src1.channels();
if( _src1.isContinuous() && _src2.isContinuous() && _dst.isContinuous() )
{ {
size.width *= size.height; int i = 0;
size.height = 1;
}
int i, j; if( !mask )
for( i = 0; i < size.height; i++ )
{ {
const T* src1 = (const T*)(_src1.data + _src1.step*i); len *= cn;
const T* src2 = (const T*)(_src2.data + _src2.step*i); for( ; i <= len - 4; i += 4 )
AT* dst = (AT*)(_dst.data + _dst.step*i);
for( j = 0; j <= size.width - 4; j += 4 )
{ {
AT t0, t1; AT t0, t1;
t0 = dst[j] + multiply(src1[j], src2[j]); t0 = (AT)src1[i]*src2[i] + dst[i];
t1 = dst[j+1] + multiply(src1[j+1], src2[j+1]); t1 = (AT)src1[i+1]*src2[i+1] + dst[i+1];
dst[j] = t0; dst[j+1] = t1; dst[i] = t0; dst[i+1] = t1;
t0 = dst[j+2] + multiply(src1[j+2], src2[j+2]);
t1 = dst[j+3] + multiply(src1[j+3], src2[j+3]);
dst[j+2] = t0; dst[j+3] = t1;
}
for( ; j < size.width; j++ ) t0 = (AT)src1[i+2]*src2[i+2] + dst[i+2];
dst[j] += multiply(src1[j], src2[j]); t1 = (AT)src1[i+3]*src2[i+3] + dst[i+3];
dst[i+2] = t0; dst[i+3] = t1;
} }
}
template<typename T, typename AT> void for( ; i < len; i++ )
accW_( const Mat& _src, Mat& _dst, double _alpha ) dst[i] += (AT)src1[i]*src2[i];
}
else if( cn == 1 )
{ {
AT alpha = (AT)_alpha, beta = (AT)(1 - _alpha); for( ; i < len; i++ )
Size size = _src.size();
size.width *= _src.channels();
if( _src.isContinuous() && _dst.isContinuous() )
{ {
size.width *= size.height; if( mask[i] )
size.height = 1; dst[i] += (AT)src1[i]*src2[i];
} }
}
int i, j; else if( cn == 3 )
for( i = 0; i < size.height; i++ ) {
for( ; i < len; i++, src1 += 3, src2 += 3, dst += 3 )
{ {
const T* src = (const T*)(_src.data + _src.step*i); if( mask[i] )
AT* dst = (AT*)(_dst.data + _dst.step*i); {
AT t0 = (AT)src1[0]*src2[0] + dst[0];
AT t1 = (AT)src1[1]*src2[1] + dst[1];
AT t2 = (AT)src1[2]*src2[2] + dst[2];
for( j = 0; j <= size.width - 4; j += 4 ) dst[0] = t0; dst[1] = t1; dst[2] = t2;
}
}
}
else
{ {
AT t0, t1; for( ; i < len; i++, src1 += cn, src2 += cn, dst += cn )
t0 = addw(src[j], alpha, dst[j], beta); if( mask[i] )
t1 = addw(src[j+1], alpha, dst[j+1], beta); {
dst[j] = t0; dst[j+1] = t1; for( int k = 0; k < cn; k++ )
t0 = addw(src[j+2], alpha, dst[j+2], beta); dst[k] += (AT)src1[k]*src2[k];
t1 = addw(src[j+3], alpha, dst[j+3], beta);
dst[j+2] = t0; dst[j+3] = t1;
} }
for( ; j < size.width; j++ )
dst[j] = addw(src[j], alpha, dst[j], beta);
} }
} }
template<typename T, typename AT> void template<typename T, typename AT> void
accMask_( const Mat& _src, Mat& _dst, const Mat& _mask ) accW_( const T* src, AT* dst, const uchar* mask, int len, int cn, double alpha )
{ {
Size size = _src.size(); AT a = (AT)alpha, b = 1 - a;
int i = 0;
if( _src.isContinuous() && _dst.isContinuous() && _mask.isContinuous() ) if( !mask )
{ {
size.width *= size.height; len *= cn;
size.height = 1; for( ; i <= len - 4; i += 4 )
}
int i, j;
for( i = 0; i < size.height; i++ )
{ {
const T* src = (const T*)(_src.data + _src.step*i); AT t0, t1;
AT* dst = (AT*)(_dst.data + _dst.step*i); t0 = src[i]*a + dst[i]*b;
const uchar* mask = _mask.data + _mask.step*i; t1 = src[i+1]*a + dst[i+1]*b;
dst[i] = t0; dst[i+1] = t1;
for( j = 0; j < size.width; j++ ) t0 = src[i+2]*a + dst[i+2]*b;
if( mask[j] ) t1 = src[i+3]*a + dst[i+3]*b;
dst[j] += src[j]; dst[i+2] = t0; dst[i+3] = t1;
}
} }
for( ; i < len; i++ )
template<typename T, typename AT> void dst[i] = src[i]*a + dst[i]*b;
accSqrMask_( const Mat& _src, Mat& _dst, const Mat& _mask ) }
else if( cn == 1 )
{ {
Size size = _src.size(); for( ; i < len; i++ )
if( _src.isContinuous() && _dst.isContinuous() && _mask.isContinuous() )
{ {
size.width *= size.height; if( mask[i] )
size.height = 1; dst[i] = src[i]*a + dst[i]*b;
} }
}
int i, j; else if( cn == 3 )
for( i = 0; i < size.height; i++ ) {
for( ; i < len; i++, src += 3, dst += 3 )
{ {
const T* src = (const T*)(_src.data + _src.step*i); if( mask[i] )
AT* dst = (AT*)(_dst.data + _dst.step*i); {
const uchar* mask = _mask.data + _mask.step*i; AT t0 = src[0]*a + dst[0]*b;
AT t1 = src[1]*a + dst[1]*b;
AT t2 = src[2]*a + dst[2]*b;
for( j = 0; j < size.width; j++ ) dst[0] = t0; dst[1] = t1; dst[2] = t2;
if( mask[j] )
dst[j] += sqr(src[j]);
} }
} }
}
else
template<typename T, typename AT> void
accProdMask_( const Mat& _src1, const Mat& _src2, Mat& _dst, const Mat& _mask )
{ {
Size size = _src1.size(); for( ; i < len; i++, src += cn, dst += cn )
if( mask[i] )
if( _src1.isContinuous() && _src2.isContinuous() &&
_dst.isContinuous() && _mask.isContinuous() )
{ {
size.width *= size.height; for( int k = 0; k < cn; k++ )
size.height = 1; dst[k] += src[k]*a + dst[k]*b;
} }
int i, j;
for( i = 0; i < size.height; i++ )
{
const T* src1 = (const T*)(_src1.data + _src1.step*i);
const T* src2 = (const T*)(_src2.data + _src2.step*i);
AT* dst = (AT*)(_dst.data + _dst.step*i);
const uchar* mask = _mask.data + _mask.step*i;
for( j = 0; j < size.width; j++ )
if( mask[j] )
dst[j] += multiply(src1[j], src2[j]);
} }
} }
template<typename T, typename AT> void #define DEF_ACC_FUNCS(suffix, type, acctype) \
accWMask_( const Mat& _src, Mat& _dst, double _alpha, const Mat& _mask ) static void acc_##suffix(const type* src, acctype* dst, \
{ const uchar* mask, int len, int cn) \
typedef typename DataType<AT>::channel_type AT1; { acc_(src, dst, mask, len, cn); } \
AT1 alpha = (AT1)_alpha, beta = (AT1)(1 - _alpha); \
Size size = _src.size(); static void accSqr_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn) \
{ accSqr_(src, dst, mask, len, cn); } \
\
static void accProd_##suffix(const type* src1, const type* src2, \
acctype* dst, const uchar* mask, int len, int cn) \
{ accProd_(src1, src2, dst, mask, len, cn); } \
\
static void accW_##suffix(const type* src, acctype* dst, \
const uchar* mask, int len, int cn, double alpha) \
{ accW_(src, dst, mask, len, cn, alpha); }
if( _src.isContinuous() && _dst.isContinuous() && _mask.isContinuous() )
{
size.width *= size.height;
size.height = 1;
}
int i, j; DEF_ACC_FUNCS(8u32f, uchar, float)
for( i = 0; i < size.height; i++ ) DEF_ACC_FUNCS(8u64f, uchar, double)
{ DEF_ACC_FUNCS(16u32f, ushort, float)
const T* src = (const T*)(_src.data + _src.step*i); DEF_ACC_FUNCS(16u64f, ushort, double)
AT* dst = (AT*)(_dst.data + _dst.step*i); DEF_ACC_FUNCS(32f, float, float)
const uchar* mask = _mask.data + _mask.step*i; DEF_ACC_FUNCS(32f64f, float, double)
DEF_ACC_FUNCS(64f, double, double)
for( j = 0; j < size.width; j++ )
if( mask[j] )
dst[j] = addw(src[j], alpha, dst[j], beta);
}
}
typedef void (*AccFunc)(const uchar*, uchar*, const uchar*, int, int);
typedef void (*AccProdFunc)(const uchar*, const uchar*, uchar*, const uchar*, int, int);
typedef void (*AccWFunc)(const uchar*, uchar*, const uchar*, int, int, double);
typedef void (*AccFunc)(const Mat&, Mat&); static AccFunc accTab[] =
typedef void (*AccMaskFunc)(const Mat&, Mat&, const Mat&); {
typedef void (*AccProdFunc)(const Mat&, const Mat&, Mat&); (AccFunc)acc_8u32f, (AccFunc)acc_8u64f,
typedef void (*AccProdMaskFunc)(const Mat&, const Mat&, Mat&, const Mat&); (AccFunc)acc_16u32f, (AccFunc)acc_16u64f,
typedef void (*AccWFunc)(const Mat&, Mat&, double); (AccFunc)acc_32f, (AccFunc)acc_32f64f,
typedef void (*AccWMaskFunc)(const Mat&, Mat&, double, const Mat&); (AccFunc)acc_64f
};
void accumulate( const Mat& src, Mat& dst, const Mat& mask ) static AccFunc accSqrTab[] =
{ {
CV_Assert( dst.size() == src.size() && dst.channels() == src.channels() ); (AccFunc)accSqr_8u32f, (AccFunc)accSqr_8u64f,
(AccFunc)accSqr_16u32f, (AccFunc)accSqr_16u64f,
(AccFunc)accSqr_32f, (AccFunc)accSqr_32f64f,
(AccFunc)accSqr_64f
};
if( !mask.data ) static AccProdFunc accProdTab[] =
{ {
AccFunc func = 0; (AccProdFunc)accProd_8u32f, (AccProdFunc)accProd_8u64f,
if( src.depth() == CV_8U && dst.depth() == CV_32F ) (AccProdFunc)accProd_16u32f, (AccProdFunc)accProd_16u64f,
func = acc_<uchar, float>; (AccProdFunc)accProd_32f, (AccProdFunc)accProd_32f64f,
else if( src.depth() == CV_8U && dst.depth() == CV_64F ) (AccProdFunc)accProd_64f
func = acc_<uchar, double>; };
else if( src.depth() == CV_32F && dst.depth() == CV_32F )
func = acc_<float, float>;
else if( src.depth() == CV_32F && dst.depth() == CV_64F )
func = acc_<float, double>;
else if( src.depth() == CV_64F && dst.depth() == CV_64F )
func = acc_<double, double>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst ); static AccWFunc accWTab[] =
}
else
{ {
CV_Assert( mask.size() == src.size() && mask.type() == CV_8UC1 ); (AccWFunc)accW_8u32f, (AccWFunc)accW_8u64f,
(AccWFunc)accW_16u32f, (AccWFunc)accW_16u64f,
AccMaskFunc func = 0; (AccWFunc)accW_32f, (AccWFunc)accW_32f64f,
if( src.type() == CV_8UC1 && dst.type() == CV_32FC1 ) (AccWFunc)accW_64f
func = accMask_<uchar, float>; };
else if( src.type() == CV_8UC3 && dst.type() == CV_32FC3 )
func = accMask_<Vec3b, Vec3f>;
else if( src.type() == CV_8UC1 && dst.type() == CV_64FC1 )
func = accMask_<uchar, double>;
else if( src.type() == CV_8UC3 && dst.type() == CV_64FC3 )
func = accMask_<Vec3b, Vec3d>;
else if( src.type() == CV_32FC1 && dst.type() == CV_32FC1 )
func = accMask_<float, float>;
else if( src.type() == CV_32FC3 && dst.type() == CV_32FC3 )
func = accMask_<Vec3f, Vec3f>;
else if( src.type() == CV_32FC1 && dst.type() == CV_64FC1 )
func = accMask_<float, double>;
else if( src.type() == CV_32FC3 && dst.type() == CV_64FC3 )
func = accMask_<Vec3f, Vec3d>;
else if( src.type() == CV_64FC1 && dst.type() == CV_64FC1 )
func = accMask_<double, double>;
else if( src.type() == CV_64FC3 && dst.type() == CV_64FC3 )
func = accMask_<Vec3d, Vec3d>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst, mask ); inline int getAccTabIdx(int sdepth, int ddepth)
} {
return sdepth == CV_8U && ddepth == CV_32F ? 0 :
sdepth == CV_8U && ddepth == CV_64F ? 1 :
sdepth == CV_16U && ddepth == CV_32F ? 2 :
sdepth == CV_16U && ddepth == CV_64F ? 3 :
sdepth == CV_32F && ddepth == CV_32F ? 4 :
sdepth == CV_32F && ddepth == CV_64F ? 5 :
sdepth == CV_64F && ddepth == CV_64F ? 6 : -1;
} }
}
void accumulateSquare( const Mat& src, Mat& dst, const Mat& mask ) void cv::accumulate( const InputArray& _src, InputOutputArray _dst, const InputArray& _mask )
{ {
CV_Assert( dst.size() == src.size() && dst.channels() == src.channels() ); Mat src = _src.getMat(), dst = _dst.getMat(), mask = _mask.getMat();
int sdepth = src.depth(), ddepth = dst.depth(), cn = src.channels();
if( !mask.data ) CV_Assert( dst.size == src.size && dst.channels() == cn );
{
AccFunc func = 0;
if( src.depth() == CV_8U && dst.depth() == CV_32F )
func = accSqr_<uchar, float>;
else if( src.depth() == CV_8U && dst.depth() == CV_64F )
func = accSqr_<uchar, double>;
else if( src.depth() == CV_32F && dst.depth() == CV_32F )
func = accSqr_<float, float>;
else if( src.depth() == CV_32F && dst.depth() == CV_64F )
func = accSqr_<float, double>;
else if( src.depth() == CV_64F && dst.depth() == CV_64F )
func = accSqr_<double, double>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst ); if( !mask.empty() )
} CV_Assert( mask.size == src.size && mask.type() == CV_8U );
else
{
CV_Assert( mask.size() == src.size() && mask.type() == CV_8UC1 );
AccMaskFunc func = 0;
if( src.type() == CV_8UC1 && dst.type() == CV_32FC1 )
func = accSqrMask_<uchar, float>;
else if( src.type() == CV_8UC3 && dst.type() == CV_32FC3 )
func = accSqrMask_<Vec3b, Vec3f>;
else if( src.type() == CV_8UC1 && dst.type() == CV_64FC1 )
func = accSqrMask_<uchar, double>;
else if( src.type() == CV_8UC3 && dst.type() == CV_64FC3 )
func = accSqrMask_<Vec3b, Vec3d>;
else if( src.type() == CV_32FC1 && dst.type() == CV_32FC1 )
func = accSqrMask_<float, float>;
else if( src.type() == CV_32FC3 && dst.type() == CV_32FC3 )
func = accSqrMask_<Vec3f, Vec3f>;
else if( src.type() == CV_32FC1 && dst.type() == CV_64FC1 )
func = accSqrMask_<float, double>;
else if( src.type() == CV_32FC3 && dst.type() == CV_64FC3 )
func = accSqrMask_<Vec3f, Vec3d>;
else if( src.type() == CV_64FC1 && dst.type() == CV_64FC1 )
func = accSqrMask_<double, double>;
else if( src.type() == CV_64FC3 && dst.type() == CV_64FC3 )
func = accSqrMask_<Vec3d, Vec3d>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst, mask ); int fidx = getAccTabIdx(sdepth, ddepth);
} AccFunc func = fidx >= 0 ? accTab[fidx] : 0;
CV_Assert( func != 0 );
const Mat* arrays[] = {&src, &dst, &mask, 0};
uchar* ptrs[3];
NAryMatIterator it(arrays, ptrs);
int len = (int)it.size;
for( size_t i = 0; i < it.nplanes; i++, ++it )
func(ptrs[0], ptrs[1], ptrs[2], len, cn);
} }
void accumulateProduct( const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask ) void cv::accumulateSquare( const InputArray& _src, InputOutputArray _dst, const InputArray& _mask )
{ {
CV_Assert( dst.size() == src1.size() && dst.channels() == src1.channels() && Mat src = _src.getMat(), dst = _dst.getMat(), mask = _mask.getMat();
src1.size() == src2.size() && src1.type() == src2.type() ); int sdepth = src.depth(), ddepth = dst.depth(), cn = src.channels();
if( !mask.data ) CV_Assert( dst.size == src.size && dst.channels() == cn );
{
AccProdFunc func = 0;
if( src1.depth() == CV_8U && dst.depth() == CV_32F )
func = accProd_<uchar, float>;
else if( src1.depth() == CV_8U && dst.depth() == CV_64F )
func = accProd_<uchar, double>;
else if( src1.depth() == CV_32F && dst.depth() == CV_32F )
func = accProd_<float, float>;
else if( src1.depth() == CV_32F && dst.depth() == CV_64F )
func = accProd_<float, double>;
else if( src1.depth() == CV_64F && dst.depth() == CV_64F )
func = accProd_<double, double>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src1, src2, dst ); if( !mask.empty() )
CV_Assert( mask.size == src.size && mask.type() == CV_8U );
int fidx = getAccTabIdx(sdepth, ddepth);
AccFunc func = fidx >= 0 ? accSqrTab[fidx] : 0;
CV_Assert( func != 0 );
const Mat* arrays[] = {&src, &dst, &mask, 0};
uchar* ptrs[3];
NAryMatIterator it(arrays, ptrs);
int len = (int)it.size;
for( size_t i = 0; i < it.nplanes; i++, ++it )
func(ptrs[0], ptrs[1], ptrs[2], len, cn);
} }
else
void cv::accumulateProduct( const InputArray& _src1, const InputArray& _src2,
InputOutputArray _dst, const InputArray& _mask )
{ {
CV_Assert( mask.size() == src1.size() && mask.type() == CV_8UC1 ); Mat src1 = _src1.getMat(), src2 = _src2.getMat(), dst = _dst.getMat(), mask = _mask.getMat();
int sdepth = src1.depth(), ddepth = dst.depth(), cn = src1.channels();
AccProdMaskFunc func = 0;
if( src1.type() == CV_8UC1 && dst.type() == CV_32FC1 )
func = accProdMask_<uchar, float>;
else if( src1.type() == CV_8UC3 && dst.type() == CV_32FC3 )
func = accProdMask_<Vec3b, Vec3f>;
else if( src1.type() == CV_8UC1 && dst.type() == CV_64FC1 )
func = accProdMask_<uchar, double>;
else if( src1.type() == CV_8UC3 && dst.type() == CV_64FC3 )
func = accProdMask_<Vec3b, Vec3d>;
else if( src1.type() == CV_32FC1 && dst.type() == CV_32FC1 )
func = accProdMask_<float, float>;
else if( src1.type() == CV_32FC3 && dst.type() == CV_32FC3 )
func = accProdMask_<Vec3f, Vec3f>;
else if( src1.type() == CV_32FC1 && dst.type() == CV_64FC1 )
func = accProdMask_<float, double>;
else if( src1.type() == CV_32FC3 && dst.type() == CV_64FC3 )
func = accProdMask_<Vec3f, Vec3d>;
else if( src1.type() == CV_64FC1 && dst.type() == CV_64FC1 )
func = accProdMask_<double, double>;
else if( src1.type() == CV_64FC3 && dst.type() == CV_64FC3 )
func = accProdMask_<Vec3d, Vec3d>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src1, src2, dst, mask ); CV_Assert( src2.size && src1.size && src2.type() == src1.type() );
} CV_Assert( dst.size == src1.size && dst.channels() == cn );
}
if( !mask.empty() )
CV_Assert( mask.size == src1.size && mask.type() == CV_8U );
void accumulateWeighted( const Mat& src, Mat& dst, double alpha, const Mat& mask ) int fidx = getAccTabIdx(sdepth, ddepth);
{ AccProdFunc func = fidx >= 0 ? accProdTab[fidx] : 0;
CV_Assert( dst.size() == src.size() && dst.channels() == src.channels() ); CV_Assert( func != 0 );
if( !mask.data ) const Mat* arrays[] = {&src1, &src2, &dst, &mask, 0};
{ uchar* ptrs[4];
AccWFunc func = 0; NAryMatIterator it(arrays, ptrs);
if( src.depth() == CV_8U && dst.depth() == CV_32F ) int len = (int)it.size;
func = accW_<uchar, float>;
else if( src.depth() == CV_8U && dst.depth() == CV_64F )
func = accW_<uchar, double>;
else if( src.depth() == CV_32F && dst.depth() == CV_32F )
func = accW_<float, float>;
else if( src.depth() == CV_32F && dst.depth() == CV_64F )
func = accW_<float, double>;
else if( src.depth() == CV_64F && dst.depth() == CV_64F )
func = accW_<double, double>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst, alpha ); for( size_t i = 0; i < it.nplanes; i++, ++it )
func(ptrs[0], ptrs[1], ptrs[2], ptrs[3], len, cn);
} }
else
void cv::accumulateWeighted( const InputArray& _src, CV_IN_OUT InputOutputArray _dst,
double alpha, const InputArray& _mask )
{ {
CV_Assert( mask.size() == src.size() && mask.type() == CV_8UC1 ); Mat src = _src.getMat(), dst = _dst.getMat(), mask = _mask.getMat();
int sdepth = src.depth(), ddepth = dst.depth(), cn = src.channels();
AccWMaskFunc func = 0;
if( src.type() == CV_8UC1 && dst.type() == CV_32FC1 )
func = accWMask_<uchar, float>;
else if( src.type() == CV_8UC3 && dst.type() == CV_32FC3 )
func = accWMask_<Vec3b, Vec3f>;
else if( src.type() == CV_8UC1 && dst.type() == CV_64FC1 )
func = accWMask_<uchar, double>;
else if( src.type() == CV_8UC3 && dst.type() == CV_64FC3 )
func = accWMask_<Vec3b, Vec3d>;
else if( src.type() == CV_32FC1 && dst.type() == CV_32FC1 )
func = accWMask_<float, float>;
else if( src.type() == CV_32FC3 && dst.type() == CV_32FC3 )
func = accWMask_<Vec3f, Vec3f>;
else if( src.type() == CV_32FC1 && dst.type() == CV_64FC1 )
func = accWMask_<float, double>;
else if( src.type() == CV_32FC3 && dst.type() == CV_64FC3 )
func = accWMask_<Vec3f, Vec3d>;
else if( src.type() == CV_64FC1 && dst.type() == CV_64FC1 )
func = accWMask_<double, double>;
else if( src.type() == CV_64FC3 && dst.type() == CV_64FC3 )
func = accWMask_<Vec3d, Vec3d>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
func( src, dst, alpha, mask ); CV_Assert( dst.size == src.size && dst.channels() == cn );
}
} if( !mask.empty() )
CV_Assert( mask.size == src.size && mask.type() == CV_8U );
int fidx = getAccTabIdx(sdepth, ddepth);
AccWFunc func = fidx >= 0 ? accWTab[fidx] : 0;
CV_Assert( func != 0 );
const Mat* arrays[] = {&src, &dst, &mask, 0};
uchar* ptrs[3];
NAryMatIterator it(arrays, ptrs);
int len = (int)it.size;
for( size_t i = 0; i < it.nplanes; i++, ++it )
func(ptrs[0], ptrs[1], ptrs[2], len, cn, alpha);
} }

@ -335,14 +335,14 @@ CV_IMPL void cvCanny( const void* srcarr, void* dstarr,
} }
} }
void cv::Canny( const Mat& image, Mat& edges, void cv::Canny( const InputArray& image, OutputArray _edges,
double threshold1, double threshold2, double threshold1, double threshold2,
int apertureSize, bool L2gradient ) int apertureSize, bool L2gradient )
{ {
Mat src = image; Mat src = image.getMat();
edges.create(src.size(), CV_8U); _edges.create(src.size(), CV_8U);
CvMat _src = src, _dst = edges; CvMat c_src = src, c_dst = _edges.getMat();
cvCanny( &_src, &_dst, threshold1, threshold2, cvCanny( &c_src, &c_dst, threshold1, threshold2,
apertureSize + (L2gradient ? CV_CANNY_L2_GRADIENT : 0)); apertureSize + (L2gradient ? CV_CANNY_L2_GRADIENT : 0));
} }

@ -2618,13 +2618,15 @@ static void Bayer2RGB_VNG_8u( const Mat& srcmat, Mat& dstmat, int code )
} }
} }
}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
// The main function // // The main function //
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
void cvtColor( const Mat& src, Mat& dst, int code, int dcn ) void cv::cvtColor( const InputArray& _src, OutputArray _dst, int code, int dcn )
{ {
Mat src = _src.getMat(), dst;
Size sz = src.size(); Size sz = src.size();
int scn = src.channels(), depth = src.depth(), bidx; int scn = src.channels(), depth = src.depth(), bidx;
@ -2638,7 +2640,9 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
dcn = code == CV_BGR2BGRA || code == CV_RGB2BGRA || code == CV_BGRA2RGBA ? 4 : 3; dcn = code == CV_BGR2BGRA || code == CV_RGB2BGRA || code == CV_BGRA2RGBA ? 4 : 3;
bidx = code == CV_BGR2BGRA || code == CV_BGRA2BGR ? 0 : 2; bidx = code == CV_BGR2BGRA || code == CV_BGRA2BGR ? 0 : 2;
dst.create( sz, CV_MAKETYPE(depth, dcn)); _dst.create( sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, RGB2RGB<uchar>(scn, dcn, bidx)); CvtColorLoop(src, dst, RGB2RGB<uchar>(scn, dcn, bidx));
else if( depth == CV_16U ) else if( depth == CV_16U )
@ -2650,7 +2654,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_RGB2BGR565: case CV_RGB2BGR555: case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_RGB2BGR565: case CV_RGB2BGR555:
case CV_BGRA2BGR565: case CV_BGRA2BGR555: case CV_RGBA2BGR565: case CV_RGBA2BGR555: case CV_BGRA2BGR565: case CV_BGRA2BGR555: case CV_RGBA2BGR565: case CV_RGBA2BGR555:
CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U ); CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U );
dst.create(sz, CV_8UC2); _dst.create(sz, CV_8UC2);
dst = _dst.getMat();
CvtColorLoop(src, dst, RGB2RGB5x5(scn, CvtColorLoop(src, dst, RGB2RGB5x5(scn,
code == CV_BGR2BGR565 || code == CV_BGR2BGR555 || code == CV_BGR2BGR565 || code == CV_BGR2BGR555 ||
@ -2664,7 +2669,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BGR5652BGRA: case CV_BGR5552BGRA: case CV_BGR5652RGBA: case CV_BGR5552RGBA: case CV_BGR5652BGRA: case CV_BGR5552BGRA: case CV_BGR5652RGBA: case CV_BGR5552RGBA:
if(dcn <= 0) dcn = 3; if(dcn <= 0) dcn = 3;
CV_Assert( (dcn == 3 || dcn == 4) && scn == 2 && depth == CV_8U ); CV_Assert( (dcn == 3 || dcn == 4) && scn == 2 && depth == CV_8U );
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
CvtColorLoop(src, dst, RGB5x52RGB(dcn, CvtColorLoop(src, dst, RGB5x52RGB(dcn,
code == CV_BGR5652BGR || code == CV_BGR5552BGR || code == CV_BGR5652BGR || code == CV_BGR5552BGR ||
@ -2676,7 +2682,9 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BGR2GRAY: case CV_BGRA2GRAY: case CV_RGB2GRAY: case CV_RGBA2GRAY: case CV_BGR2GRAY: case CV_BGRA2GRAY: case CV_RGB2GRAY: case CV_RGBA2GRAY:
CV_Assert( scn == 3 || scn == 4 ); CV_Assert( scn == 3 || scn == 4 );
dst.create(sz, CV_MAKETYPE(depth, 1)); _dst.create(sz, CV_MAKETYPE(depth, 1));
dst = _dst.getMat();
bidx = code == CV_BGR2GRAY || code == CV_BGRA2GRAY ? 0 : 2; bidx = code == CV_BGR2GRAY || code == CV_BGRA2GRAY ? 0 : 2;
if( depth == CV_8U ) if( depth == CV_8U )
@ -2689,14 +2697,17 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BGR5652GRAY: case CV_BGR5552GRAY: case CV_BGR5652GRAY: case CV_BGR5552GRAY:
CV_Assert( scn == 2 && depth == CV_8U ); CV_Assert( scn == 2 && depth == CV_8U );
dst.create(sz, CV_8UC1); _dst.create(sz, CV_8UC1);
dst = _dst.getMat();
CvtColorLoop(src, dst, RGB5x52Gray(code == CV_BGR5652GRAY ? 6 : 5)); CvtColorLoop(src, dst, RGB5x52Gray(code == CV_BGR5652GRAY ? 6 : 5));
break; break;
case CV_GRAY2BGR: case CV_GRAY2BGRA: case CV_GRAY2BGR: case CV_GRAY2BGRA:
if( dcn <= 0 ) dcn = 3; if( dcn <= 0 ) dcn = 3;
CV_Assert( scn == 1 && (dcn == 3 || dcn == 4)); CV_Assert( scn == 1 && (dcn == 3 || dcn == 4));
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, Gray2RGB<uchar>(dcn)); CvtColorLoop(src, dst, Gray2RGB<uchar>(dcn));
@ -2708,7 +2719,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_GRAY2BGR565: case CV_GRAY2BGR555: case CV_GRAY2BGR565: case CV_GRAY2BGR555:
CV_Assert( scn == 1 && depth == CV_8U ); CV_Assert( scn == 1 && depth == CV_8U );
dst.create(sz, CV_8UC2); _dst.create(sz, CV_8UC2);
dst = _dst.getMat();
CvtColorLoop(src, dst, Gray2RGB5x5(code == CV_GRAY2BGR565 ? 6 : 5)); CvtColorLoop(src, dst, Gray2RGB5x5(code == CV_GRAY2BGR565 ? 6 : 5));
break; break;
@ -2723,7 +2735,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f; const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f;
const int* coeffs_i = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_i; const int* coeffs_i = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_i;
dst.create(sz, CV_MAKETYPE(depth, 3)); _dst.create(sz, CV_MAKETYPE(depth, 3));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, RGB2YCrCb_i<uchar>(scn, bidx, coeffs_i)); CvtColorLoop(src, dst, RGB2YCrCb_i<uchar>(scn, bidx, coeffs_i));
@ -2745,7 +2758,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f; const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f;
const int* coeffs_i = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_i; const int* coeffs_i = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_i;
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, YCrCb2RGB_i<uchar>(dcn, bidx, coeffs_i)); CvtColorLoop(src, dst, YCrCb2RGB_i<uchar>(dcn, bidx, coeffs_i));
@ -2760,7 +2774,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
CV_Assert( scn == 3 || scn == 4 ); CV_Assert( scn == 3 || scn == 4 );
bidx = code == CV_BGR2XYZ ? 0 : 2; bidx = code == CV_BGR2XYZ ? 0 : 2;
dst.create(sz, CV_MAKETYPE(depth, 3)); _dst.create(sz, CV_MAKETYPE(depth, 3));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, RGB2XYZ_i<uchar>(scn, bidx, 0)); CvtColorLoop(src, dst, RGB2XYZ_i<uchar>(scn, bidx, 0));
@ -2775,7 +2790,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) );
bidx = code == CV_XYZ2BGR ? 0 : 2; bidx = code == CV_XYZ2BGR ? 0 : 2;
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( depth == CV_8U ) if( depth == CV_8U )
CvtColorLoop(src, dst, XYZ2RGB_i<uchar>(dcn, bidx, 0)); CvtColorLoop(src, dst, XYZ2RGB_i<uchar>(dcn, bidx, 0));
@ -2794,7 +2810,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
int hrange = depth == CV_32F ? 360 : code == CV_BGR2HSV || code == CV_RGB2HSV || int hrange = depth == CV_32F ? 360 : code == CV_BGR2HSV || code == CV_RGB2HSV ||
code == CV_BGR2HLS || code == CV_RGB2HLS ? 180 : 255; code == CV_BGR2HLS || code == CV_RGB2HLS ? 180 : 255;
dst.create(sz, CV_MAKETYPE(depth, 3)); _dst.create(sz, CV_MAKETYPE(depth, 3));
dst = _dst.getMat();
if( code == CV_BGR2HSV || code == CV_RGB2HSV || if( code == CV_BGR2HSV || code == CV_RGB2HSV ||
code == CV_BGR2HSV_FULL || code == CV_RGB2HSV_FULL ) code == CV_BGR2HSV_FULL || code == CV_RGB2HSV_FULL )
@ -2824,7 +2841,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
int hrange = depth == CV_32F ? 360 : code == CV_HSV2BGR || code == CV_HSV2RGB || int hrange = depth == CV_32F ? 360 : code == CV_HSV2BGR || code == CV_HSV2RGB ||
code == CV_HLS2BGR || code == CV_HLS2RGB ? 180 : 255; code == CV_HLS2BGR || code == CV_HLS2RGB ? 180 : 255;
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( code == CV_HSV2BGR || code == CV_HSV2RGB || if( code == CV_HSV2BGR || code == CV_HSV2RGB ||
code == CV_HSV2BGR_FULL || code == CV_HSV2RGB_FULL ) code == CV_HSV2BGR_FULL || code == CV_HSV2RGB_FULL )
@ -2853,7 +2871,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
bool srgb = code == CV_BGR2Lab || code == CV_RGB2Lab || bool srgb = code == CV_BGR2Lab || code == CV_RGB2Lab ||
code == CV_BGR2Luv || code == CV_RGB2Luv; code == CV_BGR2Luv || code == CV_RGB2Luv;
dst.create(sz, CV_MAKETYPE(depth, 3)); _dst.create(sz, CV_MAKETYPE(depth, 3));
dst = _dst.getMat();
if( code == CV_BGR2Lab || code == CV_RGB2Lab || if( code == CV_BGR2Lab || code == CV_RGB2Lab ||
code == CV_LBGR2Lab || code == CV_LRGB2Lab ) code == CV_LBGR2Lab || code == CV_LRGB2Lab )
@ -2883,7 +2902,8 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
bool srgb = code == CV_Lab2BGR || code == CV_Lab2RGB || bool srgb = code == CV_Lab2BGR || code == CV_Lab2RGB ||
code == CV_Luv2BGR || code == CV_Luv2RGB; code == CV_Luv2BGR || code == CV_Luv2RGB;
dst.create(sz, CV_MAKETYPE(depth, dcn)); _dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( code == CV_Lab2BGR || code == CV_Lab2RGB || if( code == CV_Lab2BGR || code == CV_Lab2RGB ||
code == CV_Lab2LBGR || code == CV_Lab2LRGB ) code == CV_Lab2LBGR || code == CV_Lab2LRGB )
@ -2906,7 +2926,10 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BayerBG2GRAY: case CV_BayerGB2GRAY: case CV_BayerRG2GRAY: case CV_BayerGR2GRAY: case CV_BayerBG2GRAY: case CV_BayerGB2GRAY: case CV_BayerRG2GRAY: case CV_BayerGR2GRAY:
if(dcn <= 0) dcn = 1; if(dcn <= 0) dcn = 1;
CV_Assert( scn == 1 && dcn == 1 && depth == CV_8U ); CV_Assert( scn == 1 && dcn == 1 && depth == CV_8U );
dst.create(sz, depth);
_dst.create(sz, depth);
dst = _dst.getMat();
Bayer2Gray_8u(src, dst, code); Bayer2Gray_8u(src, dst, code);
break; break;
@ -2914,7 +2937,9 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
case CV_BayerBG2BGR_VNG: case CV_BayerGB2BGR_VNG: case CV_BayerRG2BGR_VNG: case CV_BayerGR2BGR_VNG: case CV_BayerBG2BGR_VNG: case CV_BayerGB2BGR_VNG: case CV_BayerRG2BGR_VNG: case CV_BayerGR2BGR_VNG:
if(dcn <= 0) dcn = 3; if(dcn <= 0) dcn = 3;
CV_Assert( scn == 1 && dcn == 3 && depth == CV_8U ); CV_Assert( scn == 1 && dcn == 3 && depth == CV_8U );
dst.create(sz, CV_MAKETYPE(depth, dcn));
_dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( code == CV_BayerBG2BGR || code == CV_BayerGB2BGR || if( code == CV_BayerBG2BGR || code == CV_BayerGB2BGR ||
code == CV_BayerRG2BGR || code == CV_BayerGR2BGR ) code == CV_BayerRG2BGR || code == CV_BayerGR2BGR )
@ -2927,8 +2952,6 @@ void cvtColor( const Mat& src, Mat& dst, int code, int dcn )
} }
} }
}
CV_IMPL void CV_IMPL void
cvCvtColor( const CvArr* srcarr, CvArr* dstarr, int code ) cvCvtColor( const CvArr* srcarr, CvArr* dstarr, int code )
{ {

@ -1469,37 +1469,40 @@ cvFindContours( void* img, CvMemStorage* storage,
return count; return count;
} }
namespace cv void cv::findContours( const InputOutputArray _image, OutputArrayOfArrays _contours,
{ OutputArray _hierarchy, int mode, int method, Point offset )
static void
_findContours( Mat& image, vector<vector<Point> >& contours,
vector<Vec4i>* hierarchy, int mode, int method, Point offset )
{ {
Mat image = _image.getMat();
MemStorage storage(cvCreateMemStorage()); MemStorage storage(cvCreateMemStorage());
CvMat _image = image; CvMat _cimage = image;
CvSeq* _contours = 0; CvSeq* _ccontours = 0;
if( hierarchy ) if( _hierarchy.needed() )
hierarchy->clear(); _hierarchy.clear();
cvFindContours(&_image, storage, &_contours, sizeof(CvContour), mode, method, offset); cvFindContours(&_cimage, storage, &_ccontours, sizeof(CvContour), mode, method, offset);
if( !_contours ) if( !_ccontours )
{ {
contours.clear(); _contours.clear();
return; return;
} }
Seq<CvSeq*> all_contours(cvTreeToNodeSeq( _contours, sizeof(CvSeq), storage )); Seq<CvSeq*> all_contours(cvTreeToNodeSeq( _ccontours, sizeof(CvSeq), storage ));
size_t i, total = all_contours.size(); size_t i, total = all_contours.size();
contours.resize(total); _contours.create(total, 1, 0, -1, true);
SeqIterator<CvSeq*> it = all_contours.begin(); SeqIterator<CvSeq*> it = all_contours.begin();
for( i = 0; i < total; i++, ++it ) for( i = 0; i < total; i++, ++it )
{ {
CvSeq* c = *it; CvSeq* c = *it;
((CvContour*)c)->color = (int)i; ((CvContour*)c)->color = (int)i;
Seq<Point>(c).copyTo(contours[i]); _contours.create(c->total, 1, CV_32SC2, i, true);
Mat ci = _contours.getMat(i);
CV_Assert( ci.isContinuous() );
cvCvtSeqToArray(c, ci.data);
} }
if( hierarchy ) if( _hierarchy.needed() )
{ {
hierarchy->resize(total); _hierarchy.create(1, total, CV_32SC4, -1, true);
Vec4i* hierarchy = _hierarchy.getMat().ptr<Vec4i>();
it = all_contours.begin(); it = all_contours.begin();
for( i = 0; i < total; i++, ++it ) for( i = 0; i < total; i++, ++it )
{ {
@ -1508,62 +1511,57 @@ _findContours( Mat& image, vector<vector<Point> >& contours,
int h_prev = c->h_prev ? ((CvContour*)c->h_prev)->color : -1; int h_prev = c->h_prev ? ((CvContour*)c->h_prev)->color : -1;
int v_next = c->v_next ? ((CvContour*)c->v_next)->color : -1; int v_next = c->v_next ? ((CvContour*)c->v_next)->color : -1;
int v_prev = c->v_prev ? ((CvContour*)c->v_prev)->color : -1; int v_prev = c->v_prev ? ((CvContour*)c->v_prev)->color : -1;
(*hierarchy)[i] = Vec4i(h_next, h_prev, v_next, v_prev); hierarchy[i] = Vec4i(h_next, h_prev, v_next, v_prev);
}
} }
} }
} }
void cv::findContours( Mat& image, vector<vector<Point> >& contours, void cv::findContours( InputOutputArray _image, OutputArrayOfArrays _contours,
vector<Vec4i>& hierarchy, int mode, int method, Point offset )
{
_findContours(image, contours, &hierarchy, mode, method, offset);
}
void cv::findContours( Mat& image, vector<vector<Point> >& contours,
int mode, int method, Point offset) int mode, int method, Point offset)
{ {
_findContours(image, contours, 0, mode, method, offset); findContours(_image, _contours, OutputArrayOfArrays(), mode, method, offset);
} }
namespace cv namespace cv
{ {
static void addChildContour(const vector<vector<Point> >& contours, static void addChildContour(const InputArrayOfArrays& contours,
const vector<Vec4i>& hierarchy, size_t ncontours,
const Vec4i* hierarchy,
int i, vector<CvSeq>& seq, int i, vector<CvSeq>& seq,
vector<CvSeqBlock>& block) vector<CvSeqBlock>& block)
{ {
size_t count = contours.size();
for( ; i >= 0; i = hierarchy[i][0] ) for( ; i >= 0; i = hierarchy[i][0] )
{ {
const vector<Point>& ci = contours[i]; Mat ci = contours.getMat(i);
cvMakeSeqHeaderForArray(CV_SEQ_POLYGON, sizeof(CvSeq), sizeof(Point), cvMakeSeqHeaderForArray(CV_SEQ_POLYGON, sizeof(CvSeq), sizeof(Point),
!ci.empty() ? (void*)&ci[0] : 0, (int)ci.size(), !ci.empty() ? (void*)ci.data : 0, (int)ci.total(),
&seq[i], &block[i] ); &seq[i], &block[i] );
int h_next = hierarchy[i][0], h_prev = hierarchy[i][1], int h_next = hierarchy[i][0], h_prev = hierarchy[i][1],
v_next = hierarchy[i][2], v_prev = hierarchy[i][3]; v_next = hierarchy[i][2], v_prev = hierarchy[i][3];
seq[i].h_next = (size_t)h_next < count ? &seq[h_next] : 0; seq[i].h_next = (size_t)h_next < ncontours ? &seq[h_next] : 0;
seq[i].h_prev = (size_t)h_prev < count ? &seq[h_prev] : 0; seq[i].h_prev = (size_t)h_prev < ncontours ? &seq[h_prev] : 0;
seq[i].v_next = (size_t)v_next < count ? &seq[v_next] : 0; seq[i].v_next = (size_t)v_next < ncontours ? &seq[v_next] : 0;
seq[i].v_prev = (size_t)v_prev < count ? &seq[v_prev] : 0; seq[i].v_prev = (size_t)v_prev < ncontours ? &seq[v_prev] : 0;
if( v_next >= 0 ) if( v_next >= 0 )
addChildContour(contours, hierarchy, v_next, seq, block); addChildContour(contours, ncontours, hierarchy, v_next, seq, block);
} }
} }
} }
void cv::drawContours( Mat& image, const vector<vector<Point> >& contours, void cv::drawContours( InputOutputArray _image, const InputArrayOfArrays& _contours,
int contourIdx, const Scalar& color, int thickness, int contourIdx, const Scalar& color, int thickness,
int lineType, const vector<Vec4i>& hierarchy, int lineType, const InputArray& _hierarchy,
int maxLevel, Point offset ) int maxLevel, Point offset )
{ {
CvMat _image = image; Mat image = _image.getMat(), hierarchy = _hierarchy.getMat();
CvMat _cimage = image;
size_t i = 0, first = 0, last = contours.size(); size_t ncontours = _contours.total();
size_t i = 0, first = 0, last = ncontours;
vector<CvSeq> seq; vector<CvSeq> seq;
vector<CvSeqBlock> block; vector<CvSeqBlock> block;
@ -1585,9 +1583,13 @@ void cv::drawContours( Mat& image, const vector<vector<Point> >& contours,
for( i = first; i < last; i++ ) for( i = first; i < last; i++ )
{ {
const vector<Point>& ci = contours[i]; Mat ci = _contours.getMat(i);
if( ci.empty() )
continue;
int npoints = ci.checkVector(2, CV_32S);
CV_Assert( npoints > 0 );
cvMakeSeqHeaderForArray( CV_SEQ_POLYGON, sizeof(CvSeq), sizeof(Point), cvMakeSeqHeaderForArray( CV_SEQ_POLYGON, sizeof(CvSeq), sizeof(Point),
!ci.empty() ? (void*)&ci[0] : 0, (int)ci.size(), &seq[i], &block[i] ); ci.data, npoints, &seq[i], &block[i] );
} }
if( hierarchy.empty() || maxLevel == 0 ) if( hierarchy.empty() || maxLevel == 0 )
@ -1599,13 +1601,15 @@ void cv::drawContours( Mat& image, const vector<vector<Point> >& contours,
else else
{ {
size_t count = last - first; size_t count = last - first;
CV_Assert(hierarchy.size() == contours.size()); CV_Assert(hierarchy.total() == ncontours && hierarchy.type() == CV_32SC4 );
if( count == contours.size() ) const Vec4i* h = hierarchy.ptr<Vec4i>();
if( count == ncontours )
{ {
for( i = first; i < last; i++ ) for( i = first; i < last; i++ )
{ {
int h_next = hierarchy[i][0], h_prev = hierarchy[i][1], int h_next = h[i][0], h_prev = h[i][1],
v_next = hierarchy[i][2], v_prev = hierarchy[i][3]; v_next = h[i][2], v_prev = h[i][3];
seq[i].h_next = (size_t)h_next < count ? &seq[h_next] : 0; seq[i].h_next = (size_t)h_next < count ? &seq[h_next] : 0;
seq[i].h_prev = (size_t)h_prev < count ? &seq[h_prev] : 0; seq[i].h_prev = (size_t)h_prev < count ? &seq[h_prev] : 0;
seq[i].v_next = (size_t)v_next < count ? &seq[v_next] : 0; seq[i].v_next = (size_t)v_next < count ? &seq[v_next] : 0;
@ -1614,85 +1618,88 @@ void cv::drawContours( Mat& image, const vector<vector<Point> >& contours,
} }
else else
{ {
int child = hierarchy[first][2]; int child = h[first][2];
if( child >= 0 ) if( child >= 0 )
{ {
addChildContour(contours, hierarchy, child, seq, block); addChildContour(_contours, ncontours, h, child, seq, block);
seq[first].v_next = &seq[child]; seq[first].v_next = &seq[child];
} }
} }
} }
cvDrawContours( &_image, &seq[first], color, color, contourIdx >= 0 ? cvDrawContours( &_cimage, &seq[first], color, color, contourIdx >= 0 ?
-maxLevel : maxLevel, thickness, lineType, offset ); -maxLevel : maxLevel, thickness, lineType, offset );
} }
void cv::approxPolyDP( const Mat& curve, vector<Point>& approxCurve, void cv::approxPolyDP( const InputArray& _curve, OutputArray _approxCurve,
double epsilon, bool closed ) double epsilon, bool closed )
{ {
CV_Assert(curve.checkVector(2, CV_32S) >= 0); Mat curve = _curve.getMat();
CvMat _curve = curve; int npoints = curve.checkVector(2), depth = curve.depth();
CV_Assert( npoints >= 0 && (depth == CV_32S || depth == CV_32F));
CvMat _ccurve = curve;
MemStorage storage(cvCreateMemStorage()); MemStorage storage(cvCreateMemStorage());
Seq<Point> seq(cvApproxPoly(&_curve, sizeof(CvContour), storage, CV_POLY_APPROX_DP, epsilon, closed)); CvSeq* result = cvApproxPoly(&_ccurve, sizeof(CvContour), storage, CV_POLY_APPROX_DP, epsilon, closed);
seq.copyTo(approxCurve); if( result->total > 0 )
}
void cv::approxPolyDP( const Mat& curve, vector<Point2f>& approxCurve,
double epsilon, bool closed )
{ {
CV_Assert(curve.checkVector(2, CV_32F) >= 0); _approxCurve.create(result->total, 1, CV_MAKETYPE(curve.depth(), 2), -1, true);
CvMat _curve = curve; cvCvtSeqToArray(result, _approxCurve.getMat().data );
MemStorage storage(cvCreateMemStorage());
Seq<Point2f> seq(cvApproxPoly(&_curve, sizeof(CvContour), storage, CV_POLY_APPROX_DP, epsilon, closed));
seq.copyTo(approxCurve);
} }
}
double cv::arcLength( const Mat& curve, bool closed ) double cv::arcLength( const InputArray& _curve, bool closed )
{ {
Mat curve = _curve.getMat();
CV_Assert(curve.checkVector(2) >= 0 && (curve.depth() == CV_32F || curve.depth() == CV_32S)); CV_Assert(curve.checkVector(2) >= 0 && (curve.depth() == CV_32F || curve.depth() == CV_32S));
CvMat _curve = curve; CvMat _ccurve = curve;
return cvArcLength(&_curve, CV_WHOLE_SEQ, closed); return cvArcLength(&_ccurve, CV_WHOLE_SEQ, closed);
} }
cv::Rect cv::boundingRect( const Mat& points ) cv::Rect cv::boundingRect( const InputArray& _points )
{ {
Mat points = _points.getMat();
CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S)); CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _points = points; CvMat _cpoints = points;
return cvBoundingRect(&_points, 0); return cvBoundingRect(&_cpoints, 0);
} }
double cv::contourArea( const Mat& contour, bool oriented ) double cv::contourArea( const InputArray& _contour, bool oriented )
{ {
Mat contour = _contour.getMat();
CV_Assert(contour.checkVector(2) >= 0 && (contour.depth() == CV_32F || contour.depth() == CV_32S)); CV_Assert(contour.checkVector(2) >= 0 && (contour.depth() == CV_32F || contour.depth() == CV_32S));
CvMat _contour = contour; CvMat _ccontour = contour;
return cvContourArea(&_contour, CV_WHOLE_SEQ, oriented); return cvContourArea(&_ccontour, CV_WHOLE_SEQ, oriented);
} }
cv::RotatedRect cv::minAreaRect( const Mat& points ) cv::RotatedRect cv::minAreaRect( const InputArray& _points )
{ {
Mat points = _points.getMat();
CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S)); CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _points = points; CvMat _cpoints = points;
return cvMinAreaRect2(&_points, 0); return cvMinAreaRect2(&_cpoints, 0);
} }
void cv::minEnclosingCircle( const Mat& points, void cv::minEnclosingCircle( const InputArray& _points,
Point2f& center, float& radius ) Point2f& center, float& radius )
{ {
Mat points = _points.getMat();
CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S)); CV_Assert(points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _points = points; CvMat _cpoints = points;
cvMinEnclosingCircle( &_points, (CvPoint2D32f*)&center, &radius ); cvMinEnclosingCircle( &_cpoints, (CvPoint2D32f*)&center, &radius );
} }
double cv::matchShapes( const Mat& contour1, double cv::matchShapes( const InputArray& _contour1,
const Mat& contour2, const InputArray& _contour2,
int method, double parameter ) int method, double parameter )
{ {
Mat contour1 = _contour1.getMat(), contour2 = _contour2.getMat();
CV_Assert(contour1.checkVector(2) >= 0 && contour2.checkVector(2) >= 0 && CV_Assert(contour1.checkVector(2) >= 0 && contour2.checkVector(2) >= 0 &&
(contour1.depth() == CV_32F || contour1.depth() == CV_32S) && (contour1.depth() == CV_32F || contour1.depth() == CV_32S) &&
contour1.depth() == contour2.depth()); contour1.depth() == contour2.depth());
@ -1702,79 +1709,68 @@ double cv::matchShapes( const Mat& contour1,
} }
void cv::convexHull( const Mat& points, vector<int>& hull, bool clockwise ) void cv::convexHull( const InputArray& _points, OutputArray _hull, bool clockwise, bool returnPoints )
{ {
int nelems = points.checkVector(2); Mat points = _points.getMat();
CV_Assert(nelems >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S)); int nelems = points.checkVector(2), depth = points.depth();
hull.resize(nelems); CV_Assert(nelems >= 0 && (depth == CV_32F || depth == CV_32S));
CvMat _points = Mat(points), _hull=Mat(hull);
cvConvexHull2(&_points, &_hull, clockwise ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE, 0);
hull.resize(_hull.cols + _hull.rows - 1);
}
void cv::convexHull( const Mat& points, if( nelems == 0 )
vector<Point>& hull, bool clockwise )
{ {
int nelems = points.checkVector(2, CV_32S); _hull.release();
CV_Assert(nelems >= 0); return;
hull.resize(nelems);
CvMat _points = Mat(points), _hull=Mat(hull);
cvConvexHull2(&_points, &_hull, clockwise ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE, 1);
hull.resize(_hull.cols + _hull.rows - 1);
} }
returnPoints = !_hull.fixedType() ? returnPoints : _hull.type() != CV_32S;
void cv::convexHull( const Mat& points, Mat hull(nelems, 1, returnPoints ? CV_MAKETYPE(depth, 2) : CV_32S);
vector<Point2f>& hull, bool clockwise ) CvMat _cpoints = points, _chull = hull;
{ cvConvexHull2(&_cpoints, &_chull, clockwise ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE, returnPoints);
int nelems = points.checkVector(2, CV_32F); _hull.create(_chull.rows, 1, hull.type(), -1, true);
CV_Assert(nelems >= 0); Mat dhull = _hull.getMat(), shull(dhull.size(), dhull.type(), hull.data);
hull.resize(nelems); shull.copyTo(dhull);
CvMat _points = Mat(points), _hull=Mat(hull);
cvConvexHull2(&_points, &_hull, clockwise ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE, 1);
hull.resize(_hull.cols + _hull.rows - 1);
} }
bool cv::isContourConvex( const Mat& contour ) bool cv::isContourConvex( const InputArray& _contour )
{ {
Mat contour = _contour.getMat();
CV_Assert(contour.checkVector(2) >= 0 && CV_Assert(contour.checkVector(2) >= 0 &&
(contour.depth() == CV_32F || contour.depth() == CV_32S)); (contour.depth() == CV_32F || contour.depth() == CV_32S));
CvMat c = Mat(contour); CvMat c = Mat(contour);
return cvCheckContourConvexity(&c) > 0; return cvCheckContourConvexity(&c) > 0;
} }
cv::RotatedRect cv::fitEllipse( const Mat& points ) cv::RotatedRect cv::fitEllipse( const InputArray& _points )
{ {
Mat points = _points.getMat();
CV_Assert(points.checkVector(2) >= 0 && CV_Assert(points.checkVector(2) >= 0 &&
(points.depth() == CV_32F || points.depth() == CV_32S)); (points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _points = points; CvMat _cpoints = points;
return cvFitEllipse2(&_points); return cvFitEllipse2(&_cpoints);
} }
void cv::fitLine( const Mat& points, Vec4f& line, int distType, void cv::fitLine( const InputArray& _points, OutputArray _line, int distType,
double param, double reps, double aeps ) double param, double reps, double aeps )
{ {
CV_Assert(points.checkVector(2) >= 0 && Mat points = _points.getMat();
(points.depth() == CV_32F || points.depth() == CV_32S)); bool is3d = points.checkVector(3) >= 0, is2d = is3d ? false : points.checkVector(2) >= 0;
CvMat _points = points;
cvFitLine(&_points, distType, param, reps, aeps, &line[0]);
}
CV_Assert((is2d || is3d) && (points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _cpoints = points;
float line[6];
cvFitLine(&_cpoints, distType, param, reps, aeps, &line[0]);
void cv::fitLine( const Mat& points, Vec6f& line, int distType, _line.create(is2d ? 4 : 6, 1, CV_32F, -1, true);
double param, double reps, double aeps ) Mat l = _line.getMat();
{ CV_Assert( l.isContinuous() );
CV_Assert(points.checkVector(3) >= 0 && memcpy( l.data, line, (is2d ? 4 : 6)*sizeof(line[0]) );
(points.depth() == CV_32F || points.depth() == CV_32S));
CvMat _points = points;
cvFitLine(&_points, distType, param, reps, aeps, &line[0]);
} }
double cv::pointPolygonTest( const Mat& contour,
double cv::pointPolygonTest( const InputArray& _contour,
Point2f pt, bool measureDist ) Point2f pt, bool measureDist )
{ {
Mat contour = _contour.getMat();
CV_Assert(contour.checkVector(2) >= 0 && CV_Assert(contour.checkVector(2) >= 0 &&
(contour.depth() == CV_32F || contour.depth() == CV_32S)); (contour.depth() == CV_32F || contour.depth() == CV_32S));
CvMat c = Mat(contour); CvMat c = Mat(contour);

@ -297,35 +297,46 @@ cornerEigenValsVecs( const Mat& src, Mat& eigenv, int block_size,
calcEigenValsVecs( cov, eigenv ); calcEigenValsVecs( cov, eigenv );
} }
}
void cornerMinEigenVal( const Mat& src, Mat& dst, int blockSize, int ksize, int borderType ) void cv::cornerMinEigenVal( const InputArray& _src, OutputArray _dst, int blockSize, int ksize, int borderType )
{ {
dst.create( src.size(), CV_32F ); Mat src = _src.getMat();
_dst.create( src.size(), CV_32F );
Mat dst = _dst.getMat();
cornerEigenValsVecs( src, dst, blockSize, ksize, MINEIGENVAL, 0, borderType ); cornerEigenValsVecs( src, dst, blockSize, ksize, MINEIGENVAL, 0, borderType );
} }
void cornerHarris( const Mat& src, Mat& dst, int blockSize, int ksize, double k, int borderType ) void cv::cornerHarris( const InputArray& _src, OutputArray _dst, int blockSize, int ksize, double k, int borderType )
{ {
dst.create( src.size(), CV_32F ); Mat src = _src.getMat();
_dst.create( src.size(), CV_32F );
Mat dst = _dst.getMat();
cornerEigenValsVecs( src, dst, blockSize, ksize, HARRIS, k, borderType ); cornerEigenValsVecs( src, dst, blockSize, ksize, HARRIS, k, borderType );
} }
void cornerEigenValsAndVecs( const Mat& src, Mat& dst, int blockSize, int ksize, int borderType ) void cv::cornerEigenValsAndVecs( const InputArray& _src, OutputArray _dst, int blockSize, int ksize, int borderType )
{ {
if( dst.rows != src.rows || dst.cols*dst.channels() != src.cols*6 || dst.depth() != CV_32F ) Mat src = _src.getMat();
dst.create( src.size(), CV_32FC(6) ); Size dsz = _dst.size();
int dtype = _dst.type();
if( dsz.height != src.rows || dsz.width*CV_MAT_CN(dtype) != src.cols*6 || CV_MAT_DEPTH(dtype) != CV_32F )
_dst.create( src.size(), CV_32FC(6) );
Mat dst = _dst.getMat();
cornerEigenValsVecs( src, dst, blockSize, ksize, EIGENVALSVECS, 0, borderType ); cornerEigenValsVecs( src, dst, blockSize, ksize, EIGENVALSVECS, 0, borderType );
} }
void preCornerDetect( const Mat& src, Mat& dst, int ksize, int borderType ) void cv::preCornerDetect( const InputArray& _src, OutputArray _dst, int ksize, int borderType )
{ {
Mat Dx, Dy, D2x, D2y, Dxy; Mat Dx, Dy, D2x, D2y, Dxy, src = _src.getMat();
CV_Assert( src.type() == CV_8UC1 || src.type() == CV_32FC1 ); CV_Assert( src.type() == CV_8UC1 || src.type() == CV_32FC1 );
dst.create( src.size(), CV_32F ); _dst.create( src.size(), CV_32F );
Mat dst = _dst.getMat();
Sobel( src, Dx, CV_32F, 1, 0, ksize, 1, 0, borderType ); Sobel( src, Dx, CV_32F, 1, 0, ksize, 1, 0, borderType );
Sobel( src, Dy, CV_32F, 0, 1, ksize, 1, 0, borderType ); Sobel( src, Dy, CV_32F, 0, 1, ksize, 1, 0, borderType );
@ -358,9 +369,6 @@ void preCornerDetect( const Mat& src, Mat& dst, int ksize, int borderType )
} }
} }
}
CV_IMPL void CV_IMPL void
cvCornerMinEigenVal( const CvArr* srcarr, CvArr* dstarr, cvCornerMinEigenVal( const CvArr* srcarr, CvArr* dstarr,
int block_size, int aperture_size ) int block_size, int aperture_size )

@ -254,12 +254,16 @@ cvFindCornerSubPix( const void* srcarr, CvPoint2D32f* corners,
} }
} }
void cv::cornerSubPix( const Mat& image, vector<Point2f>& corners, void cv::cornerSubPix( const InputArray& _image, InputOutputArray _corners,
Size winSize, Size zeroZone, Size winSize, Size zeroZone,
TermCriteria criteria ) TermCriteria criteria )
{ {
CvMat _image = image; Mat corners = _corners.getMat();
cvFindCornerSubPix(&_image, (CvPoint2D32f*)&corners[0], (int)corners.size(), int ncorners = corners.checkVector(2);
CV_Assert( ncorners >= 0 && corners.depth() == CV_32F );
CvMat c_image = _image.getMat();
cvFindCornerSubPix( &c_image, (CvPoint2D32f*)corners.data, ncorners,
winSize, zeroZone, criteria ); winSize, zeroZone, criteria );
} }

@ -111,16 +111,16 @@ void icvSepConvSmall3_32f( float* src, int src_step, float* dst, int dst_step,
namespace cv namespace cv
{ {
static void getScharrKernels( Mat& kx, Mat& ky, int dx, int dy, bool normalize, int ktype ) static void getScharrKernels( OutputArray _kx, OutputArray _ky,
int dx, int dy, bool normalize, int ktype )
{ {
const int ksize = 3; const int ksize = 3;
CV_Assert( ktype == CV_32F || ktype == CV_64F ); CV_Assert( ktype == CV_32F || ktype == CV_64F );
_kx.create(ksize, 1, ktype, -1, true);
if( kx.cols != ksize || kx.rows != 1 || kx.type() != ktype ) _ky.create(ksize, 1, ktype, -1, true);
kx.create( ksize, 1, ktype ); Mat kx = _kx.getMat();
if( ky.cols != ksize || ky.rows != 1 || ky.type() != ktype ) Mat ky = _ky.getMat();
ky.create( ksize, 1, ktype );
CV_Assert( dx >= 0 && dy >= 0 && dx+dy == 1 ); CV_Assert( dx >= 0 && dy >= 0 && dx+dy == 1 );
@ -142,7 +142,8 @@ static void getScharrKernels( Mat& kx, Mat& ky, int dx, int dy, bool normalize,
} }
static void getSobelKernels( Mat& kx, Mat& ky, int dx, int dy, int _ksize, bool normalize, int ktype ) static void getSobelKernels( OutputArray _kx, OutputArray _ky,
int dx, int dy, int _ksize, bool normalize, int ktype )
{ {
int i, j, ksizeX = _ksize, ksizeY = _ksize; int i, j, ksizeX = _ksize, ksizeY = _ksize;
if( ksizeX == 1 && dx > 0 ) if( ksizeX == 1 && dx > 0 )
@ -152,10 +153,10 @@ static void getSobelKernels( Mat& kx, Mat& ky, int dx, int dy, int _ksize, bool
CV_Assert( ktype == CV_32F || ktype == CV_64F ); CV_Assert( ktype == CV_32F || ktype == CV_64F );
if( kx.cols != ksizeX || kx.rows != 1 || kx.type() != ktype ) _kx.create(ksizeX, 1, ktype, -1, true);
kx.create( ksizeX, 1, ktype ); _ky.create(ksizeY, 1, ktype, -1, true);
if( ky.cols != ksizeY || ky.rows != 1 || ky.type() != ktype ) Mat kx = _kx.getMat();
ky.create( ksizeY, 1, ktype ); Mat ky = _ky.getMat();
if( _ksize % 2 == 0 || _ksize > 31 ) if( _ksize % 2 == 0 || _ksize > 31 )
CV_Error( CV_StsOutOfRange, "The kernel size must be odd and not larger than 31" ); CV_Error( CV_StsOutOfRange, "The kernel size must be odd and not larger than 31" );
@ -218,8 +219,9 @@ static void getSobelKernels( Mat& kx, Mat& ky, int dx, int dy, int _ksize, bool
} }
} }
}
void getDerivKernels( Mat& kx, Mat& ky, int dx, int dy, void cv::getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy,
int ksize, bool normalize, int ktype ) int ksize, bool normalize, int ktype )
{ {
if( ksize <= 0 ) if( ksize <= 0 )
@ -229,7 +231,7 @@ void getDerivKernels( Mat& kx, Mat& ky, int dx, int dy,
} }
Ptr<FilterEngine> createDerivFilter(int srcType, int dstType, cv::Ptr<cv::FilterEngine> cv::createDerivFilter(int srcType, int dstType,
int dx, int dy, int ksize, int borderType ) int dx, int dy, int ksize, int borderType )
{ {
Mat kx, ky; Mat kx, ky;
@ -238,9 +240,11 @@ Ptr<FilterEngine> createDerivFilter(int srcType, int dstType,
kx, ky, Point(-1,-1), 0, borderType ); kx, ky, Point(-1,-1), 0, borderType );
} }
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) #if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
namespace cv
{
static bool IPPDerivScharr(const Mat& src, Mat& dst, int ddepth, int dx, int dy, double scale) static bool IPPDerivScharr(const Mat& src, Mat& dst, int ddepth, int dx, int dy, double scale)
{ {
int bufSize = 0; int bufSize = 0;
@ -346,8 +350,6 @@ static bool IPPDeriv(const Mat& src, Mat& dst, int ddepth, int dx, int dy, int k
if( ddepth < 0 ) if( ddepth < 0 )
ddepth = src.depth(); ddepth = src.depth();
dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
if(src.type() == CV_8U && dst.type() == CV_16S && scale == 1) if(src.type() == CV_8U && dst.type() == CV_16S && scale == 1)
{ {
if((dx == 1) && (dy == 0)) if((dx == 1) && (dy == 0))
@ -462,19 +464,23 @@ static bool IPPDeriv(const Mat& src, Mat& dst, int ddepth, int dx, int dy, int k
return IPPDerivScharr(src, dst, ddepth, dx, dy, scale); return IPPDerivScharr(src, dst, ddepth, dx, dy, scale);
return false; return false;
}
} }
#endif #endif
void cv::Sobel( const InputArray& _src, OutputArray _dst, int ddepth, int dx, int dy,
void Sobel( const Mat& src, Mat& dst, int ddepth, int dx, int dy,
int ksize, double scale, double delta, int borderType ) int ksize, double scale, double delta, int borderType )
{ {
Mat src = _src.getMat();
_dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
Mat dst = _dst.getMat();
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) #if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
if(dx < 3 && dy < 3 && src.channels() == 1 && borderType == 1) if(dx < 3 && dy < 3 && src.channels() == 1 && borderType == 1)
{ {
if(IPPDeriv(src, dst, ddepth, dx, dy, ksize,scale) == true) if(IPPDeriv(src, dst, ddepth, dx, dy, ksize,scale))
return; return;
} }
#endif #endif
@ -495,13 +501,17 @@ void Sobel( const Mat& src, Mat& dst, int ddepth, int dx, int dy,
} }
void Scharr( const Mat& src, Mat& dst, int ddepth, int dx, int dy, void cv::Scharr( const InputArray& _src, OutputArray _dst, int ddepth, int dx, int dy,
double scale, double delta, int borderType ) double scale, double delta, int borderType )
{ {
Mat src = _src.getMat();
_dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
Mat dst = _dst.getMat();
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) #if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
if(dx < 2 && dy < 2 && src.channels() == 1 && borderType == 1) if(dx < 2 && dy < 2 && src.channels() == 1 && borderType == 1)
{ {
if(IPPDerivScharr(src, dst, ddepth, dx, dy, scale) == true) if(IPPDerivScharr(src, dst, ddepth, dx, dy, scale))
return; return;
} }
#endif #endif
@ -522,9 +532,13 @@ void Scharr( const Mat& src, Mat& dst, int ddepth, int dx, int dy,
} }
void Laplacian( const Mat& src, Mat& dst, int ddepth, int ksize, void cv::Laplacian( const InputArray& _src, OutputArray _dst, int ddepth, int ksize,
double scale, double delta, int borderType ) double scale, double delta, int borderType )
{ {
Mat src = _src.getMat();
_dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
Mat dst = _dst.getMat();
if( ksize == 1 || ksize == 3 ) if( ksize == 1 || ksize == 3 )
{ {
float K[2][9] = float K[2][9] =
@ -548,7 +562,6 @@ void Laplacian( const Mat& src, Mat& dst, int ddepth, int ksize,
if( ddepth < 0 ) if( ddepth < 0 )
ddepth = src.depth(); ddepth = src.depth();
int dtype = CV_MAKETYPE(ddepth, src.channels()); int dtype = CV_MAKETYPE(ddepth, src.channels());
dst.create( src.size(), dtype );
int dy0 = std::min(std::max((int)(STRIPE_SIZE/(getElemSize(src.type())*src.cols)), 1), src.rows); int dy0 = std::min(std::max((int)(STRIPE_SIZE/(getElemSize(src.type())*src.cols)), 1), src.rows);
Ptr<FilterEngine> fx = createSeparableLinearFilter(src.type(), Ptr<FilterEngine> fx = createSeparableLinearFilter(src.type(),
@ -578,8 +591,6 @@ void Laplacian( const Mat& src, Mat& dst, int ddepth, int ksize,
} }
} }
}
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
CV_IMPL void CV_IMPL void

@ -850,21 +850,24 @@ cvDistTransform( const void* srcarr, void* dstarr,
} }
} }
void cv::distanceTransform( const Mat& src, Mat& dst, Mat& labels, void cv::distanceTransform( const InputArray& _src, OutputArray _dst, OutputArray _labels,
int distanceType, int maskSize ) int distanceType, int maskSize )
{ {
dst.create(src.size(), CV_32F); Mat src = _src.getMat();
labels.create(src.size(), CV_32S); _dst.create(src.size(), CV_32F);
CvMat _src = src, _dst = dst, _labels = labels; _labels.create(src.size(), CV_32S);
cvDistTransform(&_src, &_dst, distanceType, maskSize, 0, &_labels); CvMat c_src = src, c_dst = _dst.getMat(), c_labels = _labels.getMat();
cvDistTransform(&c_src, &c_dst, distanceType, maskSize, 0, &c_labels);
} }
void cv::distanceTransform( const Mat& src, Mat& dst, void cv::distanceTransform( const InputArray& _src, OutputArray _dst,
int distanceType, int maskSize ) int distanceType, int maskSize )
{ {
dst.create(src.size(), CV_32F); Mat src = _src.getMat();
CvMat _src = src, _dst = dst; _dst.create(src.size(), CV_32F);
cvDistTransform(&_src, &_dst, distanceType, maskSize, 0, 0); Mat dst = _dst.getMat();
CvMat c_src = src, c_dst = _dst.getMat();
cvDistTransform(&c_src, &c_dst, distanceType, maskSize, 0, 0);
} }
/* End of file. */ /* End of file. */

@ -1138,22 +1138,25 @@ icvDistC( const float *x, const float *y, void *user_param )
} }
namespace cv float cv::EMD( const InputArray& _signature1, const InputArray& _signature2,
int distType, const InputArray& _cost,
float* lowerBound, OutputArray _flow )
{ {
Mat signature1 = _signature1.getMat(), signature2 = _signature2.getMat();
Mat cost = _cost.getMat(), flow;
float EMD( const Mat& signature1, const Mat& signature2, CvMat _csignature1 = signature1;
int distType, const Mat& cost, float* lowerBound, Mat* flow ) CvMat _csignature2 = signature2;
CvMat _ccost = cost, _cflow;
if( _flow.needed() )
{ {
CvMat _signature1 = signature1; _flow.create((int)signature1.total(), (int)signature2.total(), CV_32F);
CvMat _signature2 = signature2; flow = _flow.getMat();
CvMat _cost = cost, _flow; _cflow = flow;
if( flow )
_flow = *flow;
return cvCalcEMD2( &_signature1, &_signature2, distType, 0, cost.empty() ? 0 : &_cost,
flow ? &_flow : 0, lowerBound, 0 );
} }
return cvCalcEMD2( &_csignature1, &_csignature2, distType, 0, cost.empty() ? 0 : &_ccost,
_flow.needed() ? &_cflow : 0, lowerBound, 0 );
} }
/* End of file. */ /* End of file. */

@ -50,13 +50,16 @@ template<typename T> struct greaterThanPtr
bool operator()(const T* a, const T* b) const { return *a > *b; } bool operator()(const T* a, const T* b) const { return *a > *b; }
}; };
void goodFeaturesToTrack( const Mat& image, vector<Point2f>& corners, }
void cv::goodFeaturesToTrack( const InputArray& _image, OutputArray _corners,
int maxCorners, double qualityLevel, double minDistance, int maxCorners, double qualityLevel, double minDistance,
const Mat& mask, int blockSize, const InputArray& _mask, int blockSize,
bool useHarrisDetector, double harrisK ) bool useHarrisDetector, double harrisK )
{ {
CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 ); Mat image = _image.getMat(), mask = _mask.getMat();
CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 );
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );
Mat eig, tmp; Mat eig, tmp;
@ -90,7 +93,7 @@ void goodFeaturesToTrack( const Mat& image, vector<Point2f>& corners,
} }
sort( tmpCorners, greaterThanPtr<float>() ); sort( tmpCorners, greaterThanPtr<float>() );
corners.clear(); vector<Point2f> corners;
size_t i, j, total = tmpCorners.size(), ncorners = 0; size_t i, j, total = tmpCorners.size(), ncorners = 0;
if(minDistance >= 1) if(minDistance >= 1)
@ -182,6 +185,9 @@ void goodFeaturesToTrack( const Mat& image, vector<Point2f>& corners,
break; break;
} }
} }
Mat(corners).convertTo(_corners, _corners.fixedType() ? _corners.type() : CV_32F);
/* /*
for( i = 0; i < total; i++ ) for( i = 0; i < total; i++ )
{ {
@ -210,8 +216,6 @@ void goodFeaturesToTrack( const Mat& image, vector<Point2f>& corners,
*/ */
} }
}
CV_IMPL void CV_IMPL void
cvGoodFeaturesToTrack( const void* _image, void*, void*, cvGoodFeaturesToTrack( const void* _image, void*, void*,
CvPoint2D32f* _corners, int *_corner_count, CvPoint2D32f* _corners, int *_corner_count,

@ -46,20 +46,6 @@
Base Image Filter Base Image Filter
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
BaseRowFilter::BaseRowFilter() { ksize = anchor = -1; }
BaseRowFilter::~BaseRowFilter() {}
BaseColumnFilter::BaseColumnFilter() { ksize = anchor = -1; }
BaseColumnFilter::~BaseColumnFilter() {}
void BaseColumnFilter::reset() {}
BaseFilter::BaseFilter() { ksize = Size(-1,-1); anchor = Point(-1,-1); }
BaseFilter::~BaseFilter() {}
void BaseFilter::reset() {}
/* /*
Various border types, image boundaries are denoted with '|' Various border types, image boundaries are denoted with '|'
@ -69,7 +55,7 @@ void BaseFilter::reset() {}
* BORDER_WRAP: cdefgh|abcdefgh|abcdefg * BORDER_WRAP: cdefgh|abcdefgh|abcdefg
* BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i' * BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i'
*/ */
int borderInterpolate( int p, int len, int borderType ) int cv::borderInterpolate( int p, int len, int borderType )
{ {
if( (unsigned)p < (unsigned)len ) if( (unsigned)p < (unsigned)len )
; ;
@ -104,6 +90,20 @@ int borderInterpolate( int p, int len, int borderType )
} }
namespace cv
{
BaseRowFilter::BaseRowFilter() { ksize = anchor = -1; }
BaseRowFilter::~BaseRowFilter() {}
BaseColumnFilter::BaseColumnFilter() { ksize = anchor = -1; }
BaseColumnFilter::~BaseColumnFilter() {}
void BaseColumnFilter::reset() {}
BaseFilter::BaseFilter() { ksize = Size(-1,-1); anchor = Point(-1,-1); }
BaseFilter::~BaseFilter() {}
void BaseFilter::reset() {}
FilterEngine::FilterEngine() FilterEngine::FilterEngine()
{ {
srcType = dstType = bufType = -1; srcType = dstType = bufType = -1;
@ -454,13 +454,15 @@ void FilterEngine::apply(const Mat& src, Mat& dst,
dst.data + dstOfs.y*dst.step + dstOfs.x*dst.elemSize(), (int)dst.step ); dst.data + dstOfs.y*dst.step + dstOfs.x*dst.elemSize(), (int)dst.step );
} }
}
/****************************************************************************************\ /****************************************************************************************\
* Separable linear filter * * Separable linear filter *
\****************************************************************************************/ \****************************************************************************************/
int getKernelType(const Mat& _kernel, Point anchor) int cv::getKernelType(const InputArray& __kernel, Point anchor)
{ {
Mat _kernel = __kernel.getMat();
CV_Assert( _kernel.channels() == 1 ); CV_Assert( _kernel.channels() == 1 );
int i, sz = _kernel.rows*_kernel.cols; int i, sz = _kernel.rows*_kernel.cols;
@ -495,6 +497,9 @@ int getKernelType(const Mat& _kernel, Point anchor)
} }
namespace cv
{
struct RowNoVec struct RowNoVec
{ {
RowNoVec() {} RowNoVec() {}
@ -2527,10 +2532,13 @@ template<typename ST, typename DT> struct FixedPtCastEx
int SHIFT, DELTA; int SHIFT, DELTA;
}; };
Ptr<BaseRowFilter> getLinearRowFilter( int srcType, int bufType, }
const Mat& kernel, int anchor,
cv::Ptr<cv::BaseRowFilter> cv::getLinearRowFilter( int srcType, int bufType,
const InputArray& _kernel, int anchor,
int symmetryType ) int symmetryType )
{ {
Mat kernel = _kernel.getMat();
int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(bufType); int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(bufType);
int cn = CV_MAT_CN(srcType); int cn = CV_MAT_CN(srcType);
CV_Assert( cn == CV_MAT_CN(bufType) && CV_Assert( cn == CV_MAT_CN(bufType) &&
@ -2577,11 +2585,12 @@ Ptr<BaseRowFilter> getLinearRowFilter( int srcType, int bufType,
} }
Ptr<BaseColumnFilter> getLinearColumnFilter( int bufType, int dstType, cv::Ptr<cv::BaseColumnFilter> cv::getLinearColumnFilter( int bufType, int dstType,
const Mat& kernel, int anchor, const InputArray& _kernel, int anchor,
int symmetryType, double delta, int symmetryType, double delta,
int bits ) int bits )
{ {
Mat kernel = _kernel.getMat();
int sdepth = CV_MAT_DEPTH(bufType), ddepth = CV_MAT_DEPTH(dstType); int sdepth = CV_MAT_DEPTH(bufType), ddepth = CV_MAT_DEPTH(dstType);
int cn = CV_MAT_CN(dstType); int cn = CV_MAT_CN(dstType);
CV_Assert( cn == CV_MAT_CN(bufType) && CV_Assert( cn == CV_MAT_CN(bufType) &&
@ -2672,13 +2681,14 @@ Ptr<BaseColumnFilter> getLinearColumnFilter( int bufType, int dstType,
} }
Ptr<FilterEngine> createSeparableLinearFilter( cv::Ptr<cv::FilterEngine> cv::createSeparableLinearFilter(
int _srcType, int _dstType, int _srcType, int _dstType,
const Mat& _rowKernel, const Mat& _columnKernel, const InputArray& __rowKernel, const InputArray& __columnKernel,
Point _anchor, double _delta, Point _anchor, double _delta,
int _rowBorderType, int _columnBorderType, int _rowBorderType, int _columnBorderType,
const Scalar& _borderValue ) const Scalar& _borderValue )
{ {
Mat _rowKernel = __rowKernel.getMat(), _columnKernel = __columnKernel.getMat();
_srcType = CV_MAT_TYPE(_srcType); _srcType = CV_MAT_TYPE(_srcType);
_dstType = CV_MAT_TYPE(_dstType); _dstType = CV_MAT_TYPE(_dstType);
int sdepth = CV_MAT_DEPTH(_srcType), ddepth = CV_MAT_DEPTH(_dstType); int sdepth = CV_MAT_DEPTH(_srcType), ddepth = CV_MAT_DEPTH(_dstType);
@ -2742,6 +2752,9 @@ Ptr<FilterEngine> createSeparableLinearFilter(
* Non-separable linear filter * * Non-separable linear filter *
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
void preprocess2DKernel( const Mat& kernel, vector<Point>& coords, vector<uchar>& coeffs ) void preprocess2DKernel( const Mat& kernel, vector<Point>& coords, vector<uchar>& coeffs )
{ {
int i, j, k, nz = countNonZero(kernel), ktype = kernel.type(); int i, j, k, nz = countNonZero(kernel), ktype = kernel.type();
@ -2868,11 +2881,13 @@ template<typename ST, class CastOp, class VecOp> struct Filter2D : public BaseFi
VecOp vecOp; VecOp vecOp;
}; };
}
Ptr<BaseFilter> getLinearFilter(int srcType, int dstType, cv::Ptr<cv::BaseFilter> cv::getLinearFilter(int srcType, int dstType,
const Mat& _kernel, Point anchor, const InputArray& __kernel, Point anchor,
double delta, int bits) double delta, int bits)
{ {
Mat _kernel = __kernel.getMat();
int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(dstType); int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(dstType);
int cn = CV_MAT_CN(srcType), kdepth = _kernel.depth(); int cn = CV_MAT_CN(srcType), kdepth = _kernel.depth();
CV_Assert( cn == CV_MAT_CN(dstType) && ddepth >= sdepth ); CV_Assert( cn == CV_MAT_CN(dstType) && ddepth >= sdepth );
@ -2946,11 +2961,13 @@ Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,
} }
Ptr<FilterEngine> createLinearFilter( int _srcType, int _dstType, const Mat& _kernel, cv::Ptr<cv::FilterEngine> cv::createLinearFilter( int _srcType, int _dstType,
const InputArray& __kernel,
Point _anchor, double _delta, Point _anchor, double _delta,
int _rowBorderType, int _columnBorderType, int _rowBorderType, int _columnBorderType,
const Scalar& _borderValue ) const Scalar& _borderValue )
{ {
Mat _kernel = __kernel.getMat();
_srcType = CV_MAT_TYPE(_srcType); _srcType = CV_MAT_TYPE(_srcType);
_dstType = CV_MAT_TYPE(_dstType); _dstType = CV_MAT_TYPE(_dstType);
int cn = CV_MAT_CN(_srcType); int cn = CV_MAT_CN(_srcType);
@ -2977,10 +2994,12 @@ Ptr<FilterEngine> createLinearFilter( int _srcType, int _dstType, const Mat& _ke
} }
void filter2D( const Mat& src, Mat& dst, int ddepth, void cv::filter2D( const InputArray& _src, OutputArray _dst, int ddepth,
const Mat& kernel, Point anchor, const InputArray& _kernel, Point anchor,
double delta, int borderType ) double delta, int borderType )
{ {
Mat src = _src.getMat(), kernel = _kernel.getMat();
if( ddepth < 0 ) if( ddepth < 0 )
ddepth = src.depth(); ddepth = src.depth();
@ -2991,7 +3010,8 @@ void filter2D( const Mat& src, Mat& dst, int ddepth,
int dft_filter_size = 50; int dft_filter_size = 50;
#endif #endif
dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) ); _dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
Mat dst = _dst.getMat();
anchor = normalizeAnchor(anchor, kernel.size()); anchor = normalizeAnchor(anchor, kernel.size());
if( kernel.cols*kernel.rows >= dft_filter_size ) if( kernel.cols*kernel.rows >= dft_filter_size )
@ -3015,22 +3035,23 @@ void filter2D( const Mat& src, Mat& dst, int ddepth,
} }
void sepFilter2D( const Mat& src, Mat& dst, int ddepth, void cv::sepFilter2D( const InputArray& _src, OutputArray _dst, int ddepth,
const Mat& kernelX, const Mat& kernelY, Point anchor, const InputArray& _kernelX, const InputArray& _kernelY, Point anchor,
double delta, int borderType ) double delta, int borderType )
{ {
Mat src = _src.getMat(), kernelX = _kernelX.getMat(), kernelY = _kernelY.getMat();
if( ddepth < 0 ) if( ddepth < 0 )
ddepth = src.depth(); ddepth = src.depth();
dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) ); _dst.create( src.size(), CV_MAKETYPE(ddepth, src.channels()) );
Mat dst = _dst.getMat();
Ptr<FilterEngine> f = createSeparableLinearFilter(src.type(), Ptr<FilterEngine> f = createSeparableLinearFilter(src.type(),
dst.type(), kernelX, kernelY, anchor, delta, borderType & ~BORDER_ISOLATED ); dst.type(), kernelX, kernelY, anchor, delta, borderType & ~BORDER_ISOLATED );
f->apply(src, dst, Rect(0,0,-1,-1), Point(), (borderType & BORDER_ISOLATED) != 0 ); f->apply(src, dst, Rect(0,0,-1,-1), Point(), (borderType & BORDER_ISOLATED) != 0 );
} }
}
CV_IMPL void CV_IMPL void
cvFilter2D( const CvArr* srcarr, CvArr* dstarr, const CvMat* _kernel, CvPoint anchor ) cvFilter2D( const CvArr* srcarr, CvArr* dstarr, const CvMat* _kernel, CvPoint anchor )

@ -1114,25 +1114,25 @@ cvFloodFill( CvArr* arr, CvPoint seed_point,
} }
int cv::floodFill( Mat& image, Point seedPoint, int cv::floodFill( InputOutputArray _image, Point seedPoint,
Scalar newVal, Rect* rect, Scalar newVal, Rect* rect,
Scalar loDiff, Scalar upDiff, int flags ) Scalar loDiff, Scalar upDiff, int flags )
{ {
CvConnectedComp ccomp; CvConnectedComp ccomp;
CvMat _image = image; CvMat c_image = _image.getMat();
cvFloodFill(&_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, 0); cvFloodFill(&c_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, 0);
if( rect ) if( rect )
*rect = ccomp.rect; *rect = ccomp.rect;
return cvRound(ccomp.area); return cvRound(ccomp.area);
} }
int cv::floodFill( Mat& image, Mat& mask, int cv::floodFill( InputOutputArray _image, InputOutputArray _mask,
Point seedPoint, Scalar newVal, Rect* rect, Point seedPoint, Scalar newVal, Rect* rect,
Scalar loDiff, Scalar upDiff, int flags ) Scalar loDiff, Scalar upDiff, int flags )
{ {
CvConnectedComp ccomp; CvConnectedComp ccomp;
CvMat _image = image, _mask = mask; CvMat c_image = _image.getMat(), c_mask = _mask.getMat();
cvFloodFill(&_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, &_mask); cvFloodFill(&c_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, &c_mask);
if( rect ) if( rect )
*rect = ccomp.rect; *rect = ccomp.rect;
return cvRound(ccomp.area); return cvRound(ccomp.area);

@ -375,10 +375,10 @@ void initGMMs( const Mat& img, const Mat& mask, GMM& bgdGMM, GMM& fgdGMM )
CV_Assert( !bgdSamples.empty() && !fgdSamples.empty() ); CV_Assert( !bgdSamples.empty() && !fgdSamples.empty() );
Mat _bgdSamples( (int)bgdSamples.size(), 3, CV_32FC1, &bgdSamples[0][0] ); Mat _bgdSamples( (int)bgdSamples.size(), 3, CV_32FC1, &bgdSamples[0][0] );
kmeans( _bgdSamples, GMM::componentsCount, bgdLabels, kmeans( _bgdSamples, GMM::componentsCount, bgdLabels,
TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType, 0 ); TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType );
Mat _fgdSamples( (int)fgdSamples.size(), 3, CV_32FC1, &fgdSamples[0][0] ); Mat _fgdSamples( (int)fgdSamples.size(), 3, CV_32FC1, &fgdSamples[0][0] );
kmeans( _fgdSamples, GMM::componentsCount, fgdLabels, kmeans( _fgdSamples, GMM::componentsCount, fgdLabels,
TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType, 0 ); TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType );
bgdGMM.initLearning(); bgdGMM.initLearning();
for( int i = 0; i < (int)bgdSamples.size(); i++ ) for( int i = 0; i < (int)bgdSamples.size(); i++ )
@ -521,10 +521,15 @@ void estimateSegmentation( GCGraph<double>& graph, Mat& mask )
} }
} }
void cv::grabCut( const Mat& img, Mat& mask, Rect rect, void cv::grabCut( const InputArray& _img, InputOutputArray _mask, Rect rect,
Mat& bgdModel, Mat& fgdModel, InputOutputArray _bgdModel, InputOutputArray _fgdModel,
int iterCount, int mode ) int iterCount, int mode )
{ {
Mat img = _img.getMat();
Mat& mask = _mask.getMatRef();
Mat& bgdModel = _bgdModel.getMatRef();
Mat& fgdModel = _fgdModel.getMatRef();
if( img.empty() ) if( img.empty() )
CV_Error( CV_StsBadArg, "image is empty" ); CV_Error( CV_StsBadArg, "image is empty" );
if( img.type() != CV_8UC3 ) if( img.type() != CV_8UC3 )

@ -43,6 +43,10 @@
namespace cv namespace cv
{ {
template<> void Ptr<CvHistogram>::delete_obj()
{ cvReleaseHist(&obj); }
////////////////// Helper functions ////////////////////// ////////////////// Helper functions //////////////////////
static const size_t OUT_OF_RANGE = (size_t)1 << (sizeof(size_t)*8 - 2); static const size_t OUT_OF_RANGE = (size_t)1 << (sizeof(size_t)*8 - 2);
@ -586,18 +590,22 @@ calcHist_8u( vector<uchar*>& _ptrs, const vector<int>& _deltas,
} }
} }
}
void calcHist( const Mat* images, int nimages, const int* channels, void cv::calcHist( const Mat* images, int nimages, const int* channels,
const Mat& mask, Mat& hist, int dims, const int* histSize, const InputArray& _mask, OutputArray _hist, int dims, const int* histSize,
const float** ranges, bool uniform, bool accumulate ) const float** ranges, bool uniform, bool accumulate )
{ {
Mat mask = _mask.getMat();
CV_Assert(dims > 0 && histSize); CV_Assert(dims > 0 && histSize);
hist.create(dims, histSize, CV_32F);
Mat ihist = hist; uchar* histdata = _hist.getMat().data;
_hist.create(dims, histSize, CV_32F);
Mat hist = _hist.getMat(), ihist = hist;
ihist.flags = (ihist.flags & ~CV_MAT_TYPE_MASK)|CV_32S; ihist.flags = (ihist.flags & ~CV_MAT_TYPE_MASK)|CV_32S;
if( !accumulate ) if( !accumulate || histdata != hist.data )
hist = Scalar(0.); hist = Scalar(0.);
else else
hist.convertTo(ihist, CV_32S); hist.convertTo(ihist, CV_32S);
@ -626,6 +634,8 @@ void calcHist( const Mat* images, int nimages, const int* channels,
ihist.convertTo(hist, CV_32F); ihist.convertTo(hist, CV_32F);
} }
namespace cv
{
template<typename T> static void template<typename T> static void
calcSparseHist_( vector<uchar*>& _ptrs, const vector<int>& _deltas, calcSparseHist_( vector<uchar*>& _ptrs, const vector<int>& _deltas,
@ -803,11 +813,13 @@ static void calcHist( const Mat* images, int nimages, const int* channels,
} }
} }
}
void calcHist( const Mat* images, int nimages, const int* channels, void cv::calcHist( const Mat* images, int nimages, const int* channels,
const Mat& mask, SparseMat& hist, int dims, const int* histSize, const InputArray& _mask, SparseMat& hist, int dims, const int* histSize,
const float** ranges, bool uniform, bool accumulate ) const float** ranges, bool uniform, bool accumulate )
{ {
Mat mask = _mask.getMat();
calcHist( images, nimages, channels, mask, hist, dims, histSize, calcHist( images, nimages, channels, mask, hist, dims, histSize,
ranges, uniform, accumulate, false ); ranges, uniform, accumulate, false );
} }
@ -815,6 +827,8 @@ void calcHist( const Mat* images, int nimages, const int* channels,
/////////////////////////////////////// B A C K P R O J E C T //////////////////////////////////// /////////////////////////////////////// B A C K P R O J E C T ////////////////////////////////////
namespace cv
{
template<typename T, typename BT> static void template<typename T, typename BT> static void
calcBackProj_( vector<uchar*>& _ptrs, const vector<int>& _deltas, calcBackProj_( vector<uchar*>& _ptrs, const vector<int>& _deltas,
@ -1103,11 +1117,13 @@ calcBackProj_8u( vector<uchar*>& _ptrs, const vector<int>& _deltas,
} }
} }
}
void calcBackProject( const Mat* images, int nimages, const int* channels, void cv::calcBackProject( const Mat* images, int nimages, const int* channels,
const Mat& hist, Mat& backProject, const InputArray& _hist, OutputArray _backProject,
const float** ranges, double scale, bool uniform ) const float** ranges, double scale, bool uniform )
{ {
Mat hist = _hist.getMat();
vector<uchar*> ptrs; vector<uchar*> ptrs;
vector<int> deltas; vector<int> deltas;
vector<double> uniranges; vector<double> uniranges;
@ -1115,7 +1131,8 @@ void calcBackProject( const Mat* images, int nimages, const int* channels,
int dims = hist.dims == 2 && hist.size[1] == 1 ? 1 : hist.dims; int dims = hist.dims == 2 && hist.size[1] == 1 ? 1 : hist.dims;
CV_Assert( dims > 0 && hist.data ); CV_Assert( dims > 0 && hist.data );
backProject.create( images[0].size(), images[0].depth() ); _backProject.create( images[0].size(), images[0].depth() );
Mat backProject = _backProject.getMat();
histPrepareImages( images, nimages, channels, backProject, dims, hist.size, ranges, histPrepareImages( images, nimages, channels, backProject, dims, hist.size, ranges,
uniform, ptrs, deltas, imsize, uniranges ); uniform, ptrs, deltas, imsize, uniranges );
const double* _uniranges = uniform ? &uniranges[0] : 0; const double* _uniranges = uniform ? &uniranges[0] : 0;
@ -1132,6 +1149,9 @@ void calcBackProject( const Mat* images, int nimages, const int* channels,
} }
namespace cv
{
template<typename T, typename BT> static void template<typename T, typename BT> static void
calcSparseBackProj_( vector<uchar*>& _ptrs, const vector<int>& _deltas, calcSparseBackProj_( vector<uchar*>& _ptrs, const vector<int>& _deltas,
Size imsize, const SparseMat& hist, int dims, const float** _ranges, Size imsize, const SparseMat& hist, int dims, const float** _ranges,
@ -1260,8 +1280,9 @@ calcSparseBackProj_8u( vector<uchar*>& _ptrs, const vector<int>& _deltas,
} }
} }
}
void calcBackProject( const Mat* images, int nimages, const int* channels, void cv::calcBackProject( const Mat* images, int nimages, const int* channels,
const SparseMat& hist, Mat& backProject, const SparseMat& hist, Mat& backProject,
const float** ranges, double scale, bool uniform ) const float** ranges, double scale, bool uniform )
{ {
@ -1295,13 +1316,14 @@ void calcBackProject( const Mat* images, int nimages, const int* channels,
////////////////// C O M P A R E H I S T O G R A M S //////////////////////// ////////////////// C O M P A R E H I S T O G R A M S ////////////////////////
double compareHist( const Mat& H1, const Mat& H2, int method ) double cv::compareHist( const InputArray& _H1, const InputArray& _H2, int method )
{ {
Mat H1 = _H1.getMat(), H2 = _H2.getMat();
const Mat* arrays[] = {&H1, &H2, 0}; const Mat* arrays[] = {&H1, &H2, 0};
Mat planes[2]; Mat planes[2];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
double result = 0; double result = 0;
int i, len; int j, len = (int)it.size;
CV_Assert( H1.type() == H2.type() && H1.type() == CV_32F ); CV_Assert( H1.type() == H2.type() && H1.type() == CV_32F );
@ -1309,7 +1331,7 @@ double compareHist( const Mat& H1, const Mat& H2, int method )
CV_Assert( it.planes[0].isContinuous() && it.planes[1].isContinuous() ); CV_Assert( it.planes[0].isContinuous() && it.planes[1].isContinuous() );
for( i = 0; i < it.nplanes; i++, ++it ) for( size_t i = 0; i < it.nplanes; i++, ++it )
{ {
const float* h1 = (const float*)it.planes[0].data; const float* h1 = (const float*)it.planes[0].data;
const float* h2 = (const float*)it.planes[1].data; const float* h2 = (const float*)it.planes[1].data;
@ -1317,20 +1339,20 @@ double compareHist( const Mat& H1, const Mat& H2, int method )
if( method == CV_COMP_CHISQR ) if( method == CV_COMP_CHISQR )
{ {
for( i = 0; i < len; i++ ) for( j = 0; j < len; j++ )
{ {
double a = h1[i] - h2[i]; double a = h1[j] - h2[j];
double b = h1[i] + h2[i]; double b = h1[j] + h2[j];
if( fabs(b) > FLT_EPSILON ) if( fabs(b) > FLT_EPSILON )
result += a*a/b; result += a*a/b;
} }
} }
else if( method == CV_COMP_CORREL ) else if( method == CV_COMP_CORREL )
{ {
for( i = 0; i < len; i++ ) for( j = 0; j < len; j++ )
{ {
double a = h1[i]; double a = h1[j];
double b = h2[i]; double b = h2[j];
s12 += a*b; s12 += a*b;
s1 += a; s1 += a;
@ -1341,15 +1363,15 @@ double compareHist( const Mat& H1, const Mat& H2, int method )
} }
else if( method == CV_COMP_INTERSECT ) else if( method == CV_COMP_INTERSECT )
{ {
for( i = 0; i < len; i++ ) for( j = 0; j < len; j++ )
result += std::min(h1[i], h2[i]); result += std::min(h1[j], h2[j]);
} }
else if( method == CV_COMP_BHATTACHARYYA ) else if( method == CV_COMP_BHATTACHARYYA )
{ {
for( i = 0; i < len; i++ ) for( j = 0; j < len; j++ )
{ {
double a = h1[i]; double a = h1[j];
double b = h2[i]; double b = h2[j];
result += std::sqrt(a*b); result += std::sqrt(a*b);
s1 += a; s1 += a;
s2 += b; s2 += b;
@ -1361,9 +1383,7 @@ double compareHist( const Mat& H1, const Mat& H2, int method )
if( method == CV_COMP_CORREL ) if( method == CV_COMP_CORREL )
{ {
size_t total = 1; size_t total = H1.total();
for( i = 0; i < H1.dims; i++ )
total *= H1.size[i];
double scale = 1./total; double scale = 1./total;
double num = s12 - s1*s2*scale; double num = s12 - s1*s2*scale;
double denom2 = (s11 - s1*s1*scale)*(s22 - s2*s2*scale); double denom2 = (s11 - s1*s1*scale)*(s22 - s2*s2*scale);
@ -1380,7 +1400,7 @@ double compareHist( const Mat& H1, const Mat& H2, int method )
} }
double compareHist( const SparseMat& H1, const SparseMat& H2, int method ) double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
{ {
double result = 0; double result = 0;
int i, dims = H1.dims(); int i, dims = H1.dims();
@ -1491,12 +1511,6 @@ double compareHist( const SparseMat& H1, const SparseMat& H2, int method )
} }
template<> void Ptr<CvHistogram>::delete_obj()
{ cvReleaseHist(&obj); }
}
const int CV_HIST_DEFAULT_TYPE = CV_32F; const int CV_HIST_DEFAULT_TYPE = CV_32F;
/* Creates new histogram */ /* Creates new histogram */
@ -2395,11 +2409,13 @@ CV_IMPL void cvEqualizeHist( const CvArr* srcarr, CvArr* dstarr )
} }
void cv::equalizeHist( const Mat& src, Mat& dst ) void cv::equalizeHist( const InputArray& _src, OutputArray _dst )
{ {
dst.create( src.size(), src.type() ); Mat src = _src.getMat();
CvMat _src = src, _dst = dst; _dst.create( src.size(), src.type() );
cvEqualizeHist( &_src, &_dst ); Mat dst = _dst.getMat();
CvMat _csrc = src, _cdst = dst;
cvEqualizeHist( &_csrc, &_cdst );
} }
/* Implementation of RTTI and Generic Functions for CvHistogram */ /* Implementation of RTTI and Generic Functions for CvHistogram */

@ -1090,44 +1090,53 @@ namespace cv
const int STORAGE_SIZE = 1 << 12; const int STORAGE_SIZE = 1 << 12;
void HoughLines( const Mat& image, vector<Vec2f>& lines, static void seqToMat(const CvSeq* seq, OutputArray& _arr)
{
if( seq )
{
_arr.create(1, seq->total, seq->flags, -1, true);
Mat arr = _arr.getMat();
cvCvtSeqToArray(seq, arr.data);
}
else
_arr.release();
}
}
void cv::HoughLines( const InputArray& _image, OutputArray _lines,
double rho, double theta, int threshold, double rho, double theta, int threshold,
double srn, double stn ) double srn, double stn )
{ {
CvMemStorage* storage = cvCreateMemStorage(STORAGE_SIZE); Ptr<CvMemStorage> storage = cvCreateMemStorage(STORAGE_SIZE);
CvMat _image = image; CvMat c_image = _image.getMat();
CvSeq* seq = cvHoughLines2( &_image, storage, srn == 0 && stn == 0 ? CvSeq* seq = cvHoughLines2( &c_image, storage, srn == 0 && stn == 0 ?
CV_HOUGH_STANDARD : CV_HOUGH_MULTI_SCALE, CV_HOUGH_STANDARD : CV_HOUGH_MULTI_SCALE,
rho, theta, threshold, srn, stn ); rho, theta, threshold, srn, stn );
Seq<Vec2f>(seq).copyTo(lines); seqToMat(seq, _lines);
cvReleaseMemStorage(&storage);
} }
void HoughLinesP( Mat& image, vector<Vec4i>& lines, void cv::HoughLinesP( const InputArray& _image, OutputArray _lines,
double rho, double theta, int threshold, double rho, double theta, int threshold,
double minLineLength, double maxGap ) double minLineLength, double maxGap )
{ {
CvMemStorage* storage = cvCreateMemStorage(STORAGE_SIZE); Ptr<CvMemStorage> storage = cvCreateMemStorage(STORAGE_SIZE);
CvMat _image = image; CvMat c_image = _image.getMat();
CvSeq* seq = cvHoughLines2( &_image, storage, CV_HOUGH_PROBABILISTIC, CvSeq* seq = cvHoughLines2( &c_image, storage, CV_HOUGH_PROBABILISTIC,
rho, theta, threshold, minLineLength, maxGap ); rho, theta, threshold, minLineLength, maxGap );
Seq<Vec4i>(seq).copyTo(lines); seqToMat(seq, _lines);
cvReleaseMemStorage(&storage);
} }
void HoughCircles( const Mat& image, vector<Vec3f>& circles, void cv::HoughCircles( const InputArray& _image, OutputArray _circles,
int method, double dp, double min_dist, int method, double dp, double min_dist,
double param1, double param2, double param1, double param2,
int minRadius, int maxRadius ) int minRadius, int maxRadius )
{ {
CvMemStorage* storage = cvCreateMemStorage(STORAGE_SIZE); Ptr<CvMemStorage> storage = cvCreateMemStorage(STORAGE_SIZE);
CvMat _image = image; CvMat c_image = _image.getMat();
CvSeq* seq = cvHoughCircles( &_image, storage, method, CvSeq* seq = cvHoughCircles( &c_image, storage, method,
dp, min_dist, param1, param2, minRadius, maxRadius ); dp, min_dist, param1, param2, minRadius, maxRadius );
Seq<Vec3f>(seq).copyTo(circles); seqToMat(seq, _circles);
cvReleaseMemStorage(&storage);
}
} }
/* End of file. */ /* End of file. */

@ -1313,9 +1313,11 @@ typedef void (*ResizeAreaFastFunc)( const Mat& src, Mat& dst,
typedef void (*ResizeAreaFunc)( const Mat& src, Mat& dst, typedef void (*ResizeAreaFunc)( const Mat& src, Mat& dst,
const DecimateAlpha* xofs, int xofs_count ); const DecimateAlpha* xofs, int xofs_count );
}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
void resize( const Mat& src, Mat& dst, Size dsize, void cv::resize( const InputArray& _src, OutputArray _dst, Size dsize,
double inv_scale_x, double inv_scale_y, int interpolation ) double inv_scale_x, double inv_scale_y, int interpolation )
{ {
static ResizeFunc linear_tab[] = static ResizeFunc linear_tab[] =
@ -1420,6 +1422,7 @@ void resize( const Mat& src, Mat& dst, Size dsize,
0, resizeArea_<float, float>, resizeArea_<double, double>, 0 0, resizeArea_<float, float>, resizeArea_<double, double>, 0
}; };
Mat src = _src.getMat();
Size ssize = src.size(); Size ssize = src.size();
CV_Assert( ssize.area() > 0 ); CV_Assert( ssize.area() > 0 );
@ -1434,7 +1437,8 @@ void resize( const Mat& src, Mat& dst, Size dsize,
inv_scale_x = (double)dsize.width/src.cols; inv_scale_x = (double)dsize.width/src.cols;
inv_scale_y = (double)dsize.height/src.rows; inv_scale_y = (double)dsize.height/src.rows;
} }
dst.create(dsize, src.type()); _dst.create(dsize, src.type());
Mat dst = _dst.getMat();
int depth = src.depth(), cn = src.channels(); int depth = src.depth(), cn = src.channels();
double scale_x = 1./inv_scale_x, scale_y = 1./inv_scale_y; double scale_x = 1./inv_scale_x, scale_y = 1./inv_scale_y;
@ -1653,6 +1657,9 @@ void resize( const Mat& src, Mat& dst, Size dsize,
* General warping (affine, perspective, remap) * * General warping (affine, perspective, remap) *
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
template<typename T> template<typename T>
static void remapNearest( const Mat& _src, Mat& _dst, const Mat& _xy, static void remapNearest( const Mat& _src, Mat& _dst, const Mat& _xy,
int borderType, const Scalar& _borderValue ) int borderType, const Scalar& _borderValue )
@ -2392,7 +2399,10 @@ typedef void (*RemapFunc)(const Mat& _src, Mat& _dst, const Mat& _xy,
const Mat& _fxy, const void* _wtab, const Mat& _fxy, const void* _wtab,
int borderType, const Scalar& _borderValue); int borderType, const Scalar& _borderValue);
void remap( const Mat& src, Mat& dst, const Mat& map1, const Mat& map2, }
void cv::remap( const InputArray& _src, OutputArray _dst,
const InputArray& _map1, const InputArray& _map2,
int interpolation, int borderType, const Scalar& borderValue ) int interpolation, int borderType, const Scalar& borderValue )
{ {
static RemapNNFunc nn_tab[] = static RemapNNFunc nn_tab[] =
@ -2425,8 +2435,12 @@ void remap( const Mat& src, Mat& dst, const Mat& map1, const Mat& map2,
remapLanczos4<Cast<float, float>, float, 1>, 0, 0 remapLanczos4<Cast<float, float>, float, 1>, 0, 0
}; };
Mat src = _src.getMat(), map1 = _map1.getMat(), map2 = _map2.getMat();
CV_Assert( (!map2.data || map2.size() == map1.size())); CV_Assert( (!map2.data || map2.size() == map1.size()));
dst.create( map1.size(), src.type() );
_dst.create( map1.size(), src.type() );
Mat dst = _dst.getMat();
CV_Assert(dst.data != src.data); CV_Assert(dst.data != src.data);
int depth = src.depth(), map_depth = map1.depth(); int depth = src.depth(), map_depth = map1.depth();
@ -2650,9 +2664,11 @@ void remap( const Mat& src, Mat& dst, const Mat& map1, const Mat& map2,
} }
void convertMaps( const Mat& map1, const Mat& map2, Mat& dstmap1, Mat& dstmap2, void cv::convertMaps( const InputArray& _map1, const InputArray& _map2,
OutputArray _dstmap1, OutputArray _dstmap2,
int dstm1type, bool nninterpolate ) int dstm1type, bool nninterpolate )
{ {
Mat map1 = _map1.getMat(), map2 = _map2.getMat(), dstmap1, dstmap2;
Size size = map1.size(); Size size = map1.size();
const Mat *m1 = &map1, *m2 = &map2; const Mat *m1 = &map1, *m2 = &map2;
int m1type = m1->type(), m2type = m2->type(); int m1type = m1->type(), m2type = m2->type();
@ -2671,11 +2687,16 @@ void convertMaps( const Mat& map1, const Mat& map2, Mat& dstmap1, Mat& dstmap2,
if( dstm1type <= 0 ) if( dstm1type <= 0 )
dstm1type = m1type == CV_16SC2 ? CV_32FC2 : CV_16SC2; dstm1type = m1type == CV_16SC2 ? CV_32FC2 : CV_16SC2;
CV_Assert( dstm1type == CV_16SC2 || dstm1type == CV_32FC1 || dstm1type == CV_32FC2 ); CV_Assert( dstm1type == CV_16SC2 || dstm1type == CV_32FC1 || dstm1type == CV_32FC2 );
dstmap1.create( size, dstm1type ); _dstmap1.create( size, dstm1type );
dstmap1 = _dstmap1.getMat();
if( !nninterpolate && dstm1type != CV_32FC2 ) if( !nninterpolate && dstm1type != CV_32FC2 )
dstmap2.create( size, dstm1type == CV_16SC2 ? CV_16UC1 : CV_32FC1 ); {
_dstmap2.create( size, dstm1type == CV_16SC2 ? CV_16UC1 : CV_32FC1 );
dstmap2 = _dstmap2.getMat();
}
else else
dstmap2.release(); _dstmap2.release();
if( m1type == dstm1type || (nninterpolate && if( m1type == dstm1type || (nninterpolate &&
((m1type == CV_16SC2 && dstm1type == CV_32FC2) || ((m1type == CV_16SC2 && dstm1type == CV_32FC2) ||
@ -2782,10 +2803,13 @@ void convertMaps( const Mat& map1, const Mat& map2, Mat& dstmap1, Mat& dstmap2,
} }
void warpAffine( const Mat& src, Mat& dst, const Mat& M0, Size dsize, void cv::warpAffine( const InputArray& _src, OutputArray _dst,
const InputArray& _M0, Size dsize,
int flags, int borderType, const Scalar& borderValue ) int flags, int borderType, const Scalar& borderValue )
{ {
dst.create( dsize, src.type() ); Mat src = _src.getMat(), M0 = _M0.getMat();
_dst.create( dsize, src.type() );
Mat dst = _dst.getMat();
CV_Assert( dst.data != src.data && src.cols > 0 && src.rows > 0 ); CV_Assert( dst.data != src.data && src.cols > 0 && src.rows > 0 );
const int BLOCK_SZ = 64; const int BLOCK_SZ = 64;
@ -2917,10 +2941,13 @@ void warpAffine( const Mat& src, Mat& dst, const Mat& M0, Size dsize,
} }
void warpPerspective( const Mat& src, Mat& dst, const Mat& M0, Size dsize, void cv::warpPerspective( const InputArray& _src, OutputArray _dst, const InputArray& _M0,
int flags, int borderType, const Scalar& borderValue ) Size dsize, int flags, int borderType, const Scalar& borderValue )
{ {
dst.create( dsize, src.type() ); Mat src = _src.getMat(), M0 = _M0.getMat();
_dst.create( dsize, src.type() );
Mat dst = _dst.getMat();
CV_Assert( dst.data != src.data && src.cols > 0 && src.rows > 0 ); CV_Assert( dst.data != src.data && src.cols > 0 && src.rows > 0 );
const int BLOCK_SZ = 32; const int BLOCK_SZ = 32;
@ -2999,7 +3026,7 @@ void warpPerspective( const Mat& src, Mat& dst, const Mat& M0, Size dsize,
} }
Mat getRotationMatrix2D( Point2f center, double angle, double scale ) cv::Mat cv::getRotationMatrix2D( Point2f center, double angle, double scale )
{ {
angle *= CV_PI/180; angle *= CV_PI/180;
double alpha = cos(angle)*scale; double alpha = cos(angle)*scale;
@ -3042,7 +3069,7 @@ Mat getRotationMatrix2D( Point2f center, double angle, double scale )
* where: * where:
* cij - matrix coefficients, c22 = 1 * cij - matrix coefficients, c22 = 1
*/ */
Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] ) cv::Mat cv::getPerspectiveTransform( const Point2f src[], const Point2f dst[] )
{ {
Mat M(3, 3, CV_64F), X(8, 1, CV_64F, M.data); Mat M(3, 3, CV_64F), X(8, 1, CV_64F, M.data);
double a[8][8], b[8]; double a[8][8], b[8];
@ -3087,7 +3114,7 @@ Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] )
* where: * where:
* cij - matrix coefficients * cij - matrix coefficients
*/ */
Mat getAffineTransform( const Point2f src[], const Point2f dst[] ) cv::Mat cv::getAffineTransform( const Point2f src[], const Point2f dst[] )
{ {
Mat M(2, 3, CV_64F), X(6, 1, CV_64F, M.data); Mat M(2, 3, CV_64F), X(6, 1, CV_64F, M.data);
double a[6*6], b[6]; double a[6*6], b[6];
@ -3110,10 +3137,13 @@ Mat getAffineTransform( const Point2f src[], const Point2f dst[] )
return M; return M;
} }
void invertAffineTransform(const Mat& matM, Mat& _iM) void cv::invertAffineTransform(const InputArray& _matM, OutputArray __iM)
{ {
Mat matM = _matM.getMat();
CV_Assert(matM.rows == 2 && matM.cols == 3); CV_Assert(matM.rows == 2 && matM.cols == 3);
_iM.create(2, 3, matM.type()); __iM.create(2, 3, matM.type());
Mat _iM = __iM.getMat();
if( matM.type() == CV_32F ) if( matM.type() == CV_32F )
{ {
const float* M = (const float*)matM.data; const float* M = (const float*)matM.data;
@ -3148,8 +3178,6 @@ void invertAffineTransform(const Mat& matM, Mat& _iM)
CV_Error( CV_StsUnsupportedFormat, "" ); CV_Error( CV_StsUnsupportedFormat, "" );
} }
}
CV_IMPL void CV_IMPL void
cvResize( const CvArr* srcarr, CvArr* dstarr, int method ) cvResize( const CvArr* srcarr, CvArr* dstarr, int method )
{ {

@ -807,10 +807,11 @@ cvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_i
} }
} }
void cv::inpaint( const Mat& src, const Mat& mask, Mat& dst, void cv::inpaint( const InputArray& _src, const InputArray& _mask, OutputArray _dst,
double inpaintRange, int flags ) double inpaintRange, int flags )
{ {
dst.create( src.size(), src.type() ); Mat src = _src.getMat();
CvMat _src = src, _mask = mask, _dst = dst; _dst.create( src.size(), src.type() );
cvInpaint( &_src, &_mask, &_dst, inpaintRange, flags ); CvMat c_src = src, c_mask = _mask.getMat(), c_dst = _dst.getMat();
cvInpaint( &c_src, &c_mask, &c_dst, inpaintRange, flags );
} }

@ -601,13 +601,14 @@ Moments::operator CvMoments() const
return m; return m;
} }
} }
cv::Moments cv::moments( const Mat& array, bool binaryImage ) cv::Moments cv::moments( const InputArray& _array, bool binaryImage )
{ {
CvMoments om; CvMoments om;
CvMat _array = array; CvMat c_array = _array.getMat();
cvMoments(&_array, &om, binaryImage); cvMoments(&c_array, &om, binaryImage);
return om; return om;
} }

@ -822,9 +822,11 @@ template<class Op, class VecOp> struct MorphFilter : BaseFilter
VecOp vecOp; VecOp vecOp;
}; };
}
/////////////////////////////////// External Interface ///////////////////////////////////// /////////////////////////////////// External Interface /////////////////////////////////////
Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int ksize, int anchor) cv::Ptr<cv::BaseRowFilter> cv::getMorphologyRowFilter(int op, int type, int ksize, int anchor)
{ {
int depth = CV_MAT_DEPTH(type); int depth = CV_MAT_DEPTH(type);
if( anchor < 0 ) if( anchor < 0 )
@ -865,7 +867,7 @@ Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int ksize, int ancho
return Ptr<BaseRowFilter>(0); return Ptr<BaseRowFilter>(0);
} }
Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int anchor) cv::Ptr<cv::BaseColumnFilter> cv::getMorphologyColumnFilter(int op, int type, int ksize, int anchor)
{ {
int depth = CV_MAT_DEPTH(type); int depth = CV_MAT_DEPTH(type);
if( anchor < 0 ) if( anchor < 0 )
@ -907,8 +909,9 @@ Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int
} }
Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat& kernel, Point anchor) cv::Ptr<cv::BaseFilter> cv::getMorphologyFilter(int op, int type, const InputArray& _kernel, Point anchor)
{ {
Mat kernel = _kernel.getMat();
int depth = CV_MAT_DEPTH(type); int depth = CV_MAT_DEPTH(type);
anchor = normalizeAnchor(anchor, kernel.size()); anchor = normalizeAnchor(anchor, kernel.size());
CV_Assert( op == MORPH_ERODE || op == MORPH_DILATE ); CV_Assert( op == MORPH_ERODE || op == MORPH_DILATE );
@ -940,10 +943,11 @@ Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat& kernel, Point a
} }
Ptr<FilterEngine> createMorphologyFilter( int op, int type, const Mat& kernel, cv::Ptr<cv::FilterEngine> cv::createMorphologyFilter( int op, int type, const InputArray& _kernel,
Point anchor, int _rowBorderType, int _columnBorderType, Point anchor, int _rowBorderType, int _columnBorderType,
const Scalar& _borderValue ) const Scalar& _borderValue )
{ {
Mat kernel = _kernel.getMat();
anchor = normalizeAnchor(anchor, kernel.size()); anchor = normalizeAnchor(anchor, kernel.size());
Ptr<BaseRowFilter> rowFilter; Ptr<BaseRowFilter> rowFilter;
@ -978,7 +982,7 @@ Ptr<FilterEngine> createMorphologyFilter( int op, int type, const Mat& kernel,
} }
Mat getStructuringElement(int shape, Size ksize, Point anchor) cv::Mat cv::getStructuringElement(int shape, Size ksize, Point anchor)
{ {
int i, j; int i, j;
int r = 0, c = 0; int r = 0, c = 0;
@ -1031,31 +1035,36 @@ Mat getStructuringElement(int shape, Size ksize, Point anchor)
return elem; return elem;
} }
static void morphOp( int op, const Mat& src, Mat& dst, const Mat& _kernel, namespace cv
{
static void morphOp( int op, const InputArray& _src, OutputArray& _dst,
const InputArray& _kernel,
Point anchor, int iterations, Point anchor, int iterations,
int borderType, const Scalar& borderValue ) int borderType, const Scalar& borderValue )
{ {
Mat kernel; Mat src = _src.getMat(), kernel = _kernel.getMat();
Size ksize = _kernel.data ? _kernel.size() : Size(3,3); Size ksize = kernel.data ? kernel.size() : Size(3,3);
anchor = normalizeAnchor(anchor, ksize); anchor = normalizeAnchor(anchor, ksize);
CV_Assert( anchor.inside(Rect(0, 0, ksize.width, ksize.height)) ); CV_Assert( anchor.inside(Rect(0, 0, ksize.width, ksize.height)) );
if( iterations == 0 || _kernel.rows*_kernel.cols == 1 ) _dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();
if( iterations == 0 || kernel.rows*kernel.cols == 1 )
{ {
src.copyTo(dst); src.copyTo(dst);
return; return;
} }
dst.create( src.size(), src.type() ); if( !kernel.data )
if( !_kernel.data )
{ {
kernel = getStructuringElement(MORPH_RECT, Size(1+iterations*2,1+iterations*2)); kernel = getStructuringElement(MORPH_RECT, Size(1+iterations*2,1+iterations*2));
anchor = Point(iterations, iterations); anchor = Point(iterations, iterations);
iterations = 1; iterations = 1;
} }
else if( iterations > 1 && countNonZero(_kernel) == _kernel.rows*_kernel.cols ) else if( iterations > 1 && countNonZero(kernel) == kernel.rows*kernel.cols )
{ {
anchor = Point(anchor.x*iterations, anchor.y*iterations); anchor = Point(anchor.x*iterations, anchor.y*iterations);
kernel = getStructuringElement(MORPH_RECT, kernel = getStructuringElement(MORPH_RECT,
@ -1064,8 +1073,6 @@ static void morphOp( int op, const Mat& src, Mat& dst, const Mat& _kernel,
anchor); anchor);
iterations = 1; iterations = 1;
} }
else
kernel = _kernel;
Ptr<FilterEngine> f = createMorphologyFilter(op, src.type(), Ptr<FilterEngine> f = createMorphologyFilter(op, src.type(),
kernel, anchor, borderType, borderType, borderValue ); kernel, anchor, borderType, borderType, borderValue );
@ -1075,8 +1082,12 @@ static void morphOp( int op, const Mat& src, Mat& dst, const Mat& _kernel,
f->apply( dst, dst ); f->apply( dst, dst );
} }
template<> void Ptr<IplConvKernel>::delete_obj()
{ cvReleaseStructuringElement(&obj); }
void erode( const Mat& src, Mat& dst, const Mat& kernel, }
void cv::erode( const InputArray& src, OutputArray dst, const InputArray& kernel,
Point anchor, int iterations, Point anchor, int iterations,
int borderType, const Scalar& borderValue ) int borderType, const Scalar& borderValue )
{ {
@ -1084,7 +1095,7 @@ void erode( const Mat& src, Mat& dst, const Mat& kernel,
} }
void dilate( const Mat& src, Mat& dst, const Mat& kernel, void cv::dilate( const InputArray& src, OutputArray dst, const InputArray& kernel,
Point anchor, int iterations, Point anchor, int iterations,
int borderType, const Scalar& borderValue ) int borderType, const Scalar& borderValue )
{ {
@ -1092,11 +1103,14 @@ void dilate( const Mat& src, Mat& dst, const Mat& kernel,
} }
void morphologyEx( const Mat& src, Mat& dst, int op, const Mat& kernel, void cv::morphologyEx( const InputArray& _src, OutputArray _dst, int op,
Point anchor, int iterations, int borderType, const InputArray& kernel, Point anchor, int iterations,
const Scalar& borderValue ) int borderType, const Scalar& borderValue )
{ {
Mat temp; Mat src = _src.getMat(), temp;
_dst.create(src.size(), src.type());
Mat dst = _dst.getMat();
switch( op ) switch( op )
{ {
case MORPH_ERODE: case MORPH_ERODE:
@ -1137,13 +1151,6 @@ void morphologyEx( const Mat& src, Mat& dst, int op, const Mat& kernel,
} }
} }
template<> void Ptr<IplConvKernel>::delete_obj()
{ cvReleaseStructuringElement(&obj); }
}
CV_IMPL IplConvKernel * CV_IMPL IplConvKernel *
cvCreateStructuringElementEx( int cols, int rows, cvCreateStructuringElementEx( int cols, int rows,
int anchorX, int anchorY, int anchorX, int anchorY,

@ -399,11 +399,15 @@ pyrUp_( const Mat& _src, Mat& _dst )
typedef void (*PyrFunc)(const Mat&, Mat&); typedef void (*PyrFunc)(const Mat&, Mat&);
void pyrDown( const Mat& _src, Mat& _dst, const Size& _dsz ) }
void cv::pyrDown( const InputArray& _src, OutputArray _dst, const Size& _dsz )
{ {
Size dsz = _dsz == Size() ? Size((_src.cols + 1)/2, (_src.rows + 1)/2) : _dsz; Mat src = _src.getMat();
_dst.create( dsz, _src.type() ); Size dsz = _dsz == Size() ? Size((src.cols + 1)/2, (src.rows + 1)/2) : _dsz;
int depth = _src.depth(); _dst.create( dsz, src.type() );
Mat dst = _dst.getMat();
int depth = src.depth();
PyrFunc func = 0; PyrFunc func = 0;
if( depth == CV_8U ) if( depth == CV_8U )
func = pyrDown_<FixPtCast<uchar, 8>, PyrDownVec_32s8u>; func = pyrDown_<FixPtCast<uchar, 8>, PyrDownVec_32s8u>;
@ -416,14 +420,16 @@ void pyrDown( const Mat& _src, Mat& _dst, const Size& _dsz )
else else
CV_Error( CV_StsUnsupportedFormat, "" ); CV_Error( CV_StsUnsupportedFormat, "" );
func( _src, _dst ); func( src, dst );
} }
void pyrUp( const Mat& _src, Mat& _dst, const Size& _dsz ) void cv::pyrUp( const InputArray& _src, OutputArray _dst, const Size& _dsz )
{ {
Size dsz = _dsz == Size() ? Size(_src.cols*2, _src.rows*2) : _dsz; Mat src = _src.getMat();
_dst.create( dsz, _src.type() ); Size dsz = _dsz == Size() ? Size(src.cols*2, src.rows*2) : _dsz;
int depth = _src.depth(); _dst.create( dsz, src.type() );
Mat dst = _dst.getMat();
int depth = src.depth();
PyrFunc func = 0; PyrFunc func = 0;
if( depth == CV_8U ) if( depth == CV_8U )
func = pyrUp_<FixPtCast<uchar, 6>, NoVec<int, uchar> >; func = pyrUp_<FixPtCast<uchar, 6>, NoVec<int, uchar> >;
@ -436,17 +442,16 @@ void pyrUp( const Mat& _src, Mat& _dst, const Size& _dsz )
else else
CV_Error( CV_StsUnsupportedFormat, "" ); CV_Error( CV_StsUnsupportedFormat, "" );
func( _src, _dst ); func( src, dst );
} }
void buildPyramid( const Mat& _src, vector<Mat>& _dst, int maxlevel ) void cv::buildPyramid( const InputArray& _src, OutputArrayOfArrays _dst, int maxlevel )
{ {
_dst.resize( maxlevel + 1 ); Mat src = _src.getMat();
_dst[0] = _src; _dst.create( maxlevel + 1, 1, 0 );
_dst.getMatRef(0) = src;
for( int i = 1; i <= maxlevel; i++ ) for( int i = 1; i <= maxlevel; i++ )
pyrDown( _dst[i-1], _dst[i] ); pyrDown( _dst.getMatRef(i-1), _dst.getMatRef(i) );
}
} }
CV_IMPL void cvPyrDown( const void* srcarr, void* dstarr, int _filter ) CV_IMPL void cvPyrDown( const void* srcarr, void* dstarr, int _filter )

@ -868,13 +868,15 @@ cvGetQuadrangleSubPix( const void* srcarr, void* dstarr, const CvMat* mat )
} }
void cv::getRectSubPix( const Mat& image, Size patchSize, Point2f center, void cv::getRectSubPix( const InputArray& _image, Size patchSize, Point2f center,
Mat& patch, int patchType ) OutputArray _patch, int patchType )
{ {
patch.create(patchSize, patchType < 0 ? image.type() : Mat image = _image.getMat();
_patch.create(patchSize, patchType < 0 ? image.type() :
CV_MAKETYPE(CV_MAT_DEPTH(patchType),image.channels())); CV_MAKETYPE(CV_MAT_DEPTH(patchType),image.channels()));
CvMat _image = image, _patch = patch; Mat patch = _patch.getMat();
cvGetRectSubPix(&_image, &_patch, center); CvMat _cimage = image, _cpatch = patch;
cvGetRectSubPix(&_cimage, &_cpatch, center);
} }
/* End of file. */ /* End of file. */

@ -303,10 +303,10 @@ cvWatershed( const CvArr* srcarr, CvArr* dstarr )
} }
void cv::watershed( const Mat& src, Mat& markers ) void cv::watershed( const InputArray& src, InputOutputArray markers )
{ {
CvMat _src = src, _markers = markers; CvMat c_src = src.getMat(), c_markers = markers.getMat();
cvWatershed( &_src, &_markers ); cvWatershed( &c_src, &c_markers );
} }
@ -523,14 +523,16 @@ cvPyrMeanShiftFiltering( const CvArr* srcarr, CvArr* dstarr,
} }
} }
void cv::pyrMeanShiftFiltering( const Mat& src, Mat& dst, void cv::pyrMeanShiftFiltering( const InputArray& _src, OutputArray _dst,
double sp, double sr, int maxLevel, double sp, double sr, int maxLevel,
TermCriteria termcrit ) TermCriteria termcrit )
{ {
Mat src = _src.getMat();
if( src.empty() ) if( src.empty() )
return; return;
dst.create( src.size(), src.type() ); _dst.create( src.size(), src.type() );
CvMat _src = src, _dst = dst; CvMat c_src = src, c_dst = _dst.getMat();
cvPyrMeanShiftFiltering( &_src, &_dst, sp, sr, maxLevel, termcrit ); cvPyrMeanShiftFiltering( &c_src, &c_dst, sp, sr, maxLevel, termcrit );
} }

@ -197,7 +197,9 @@ template<typename ST, typename T> struct ColumnSum : public BaseColumnFilter
}; };
Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType, int ksize, int anchor) }
cv::Ptr<cv::BaseRowFilter> cv::getRowSumFilter(int srcType, int sumType, int ksize, int anchor)
{ {
int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType); int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) ); CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
@ -232,7 +234,7 @@ Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType, int ksize, int anch
} }
Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType, int ksize, cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
int anchor, double scale) int anchor, double scale)
{ {
int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType); int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
@ -272,7 +274,7 @@ Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType, int ksize,
} }
Ptr<FilterEngine> createBoxFilter( int srcType, int dstType, Size ksize, cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
Point anchor, bool normalize, int borderType ) Point anchor, bool normalize, int borderType )
{ {
int sdepth = CV_MAT_DEPTH(srcType); int sdepth = CV_MAT_DEPTH(srcType);
@ -292,14 +294,16 @@ Ptr<FilterEngine> createBoxFilter( int srcType, int dstType, Size ksize,
} }
void boxFilter( const Mat& src, Mat& dst, int ddepth, void cv::boxFilter( const InputArray& _src, OutputArray _dst, int ddepth,
Size ksize, Point anchor, Size ksize, Point anchor,
bool normalize, int borderType ) bool normalize, int borderType )
{ {
Mat src = _src.getMat();
int sdepth = src.depth(), cn = src.channels(); int sdepth = src.depth(), cn = src.channels();
if( ddepth < 0 ) if( ddepth < 0 )
ddepth = sdepth; ddepth = sdepth;
dst.create( src.size(), CV_MAKETYPE(ddepth, cn) ); _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
Mat dst = _dst.getMat();
if( borderType != BORDER_CONSTANT && normalize ) if( borderType != BORDER_CONSTANT && normalize )
{ {
if( src.rows == 1 ) if( src.rows == 1 )
@ -312,7 +316,7 @@ void boxFilter( const Mat& src, Mat& dst, int ddepth,
f->apply( src, dst ); f->apply( src, dst );
} }
void blur( const Mat& src, CV_OUT Mat& dst, void cv::blur( const InputArray& src, OutputArray dst,
Size ksize, Point anchor, int borderType ) Size ksize, Point anchor, int borderType )
{ {
boxFilter( src, dst, -1, ksize, anchor, true, borderType ); boxFilter( src, dst, -1, ksize, anchor, true, borderType );
@ -322,7 +326,7 @@ void blur( const Mat& src, CV_OUT Mat& dst,
Gaussian Blur Gaussian Blur
\****************************************************************************************/ \****************************************************************************************/
Mat getGaussianKernel( int n, double sigma, int ktype ) cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
{ {
const int SMALL_GAUSSIAN_SIZE = 7; const int SMALL_GAUSSIAN_SIZE = 7;
static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] = static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
@ -375,7 +379,7 @@ Mat getGaussianKernel( int n, double sigma, int ktype )
} }
Ptr<FilterEngine> createGaussianFilter( int type, Size ksize, cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
double sigma1, double sigma2, double sigma1, double sigma2,
int borderType ) int borderType )
{ {
@ -406,17 +410,20 @@ Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,
} }
void GaussianBlur( const Mat& src, Mat& dst, Size ksize, void cv::GaussianBlur( const InputArray& _src, OutputArray _dst, Size ksize,
double sigma1, double sigma2, double sigma1, double sigma2,
int borderType ) int borderType )
{ {
Mat src = _src.getMat();
_dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();
if( ksize.width == 1 && ksize.height == 1 ) if( ksize.width == 1 && ksize.height == 1 )
{ {
src.copyTo(dst); src.copyTo(dst);
return; return;
} }
dst.create( src.size(), src.type() );
if( borderType != BORDER_CONSTANT ) if( borderType != BORDER_CONSTANT )
{ {
if( src.rows == 1 ) if( src.rows == 1 )
@ -433,6 +440,9 @@ void GaussianBlur( const Mat& src, Mat& dst, Size ksize,
Median Filter Median Filter
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
#if _MSC_VER >= 1200 #if _MSC_VER >= 1200
#pragma warning( disable: 4244 ) #pragma warning( disable: 4244 )
#endif #endif
@ -1207,9 +1217,14 @@ medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
} }
} }
}
void medianBlur( const Mat& src0, Mat& dst, int ksize ) void cv::medianBlur( const InputArray& _src0, OutputArray _dst, int ksize )
{ {
Mat src0 = _src0.getMat();
_dst.create( src0.size(), src0.type() );
Mat dst = _dst.getMat();
if( ksize <= 1 ) if( ksize <= 1 )
{ {
src0.copyTo(dst); src0.copyTo(dst);
@ -1226,7 +1241,6 @@ void medianBlur( const Mat& src0, Mat& dst, int ksize )
#endif #endif
); );
dst.create( src0.size(), src0.type() );
Mat src; Mat src;
if( useSortNet ) if( useSortNet )
{ {
@ -1266,6 +1280,9 @@ void medianBlur( const Mat& src0, Mat& dst, int ksize )
Bilateral Filtering Bilateral Filtering
\****************************************************************************************/ \****************************************************************************************/
namespace cv
{
static void static void
bilateralFilter_8u( const Mat& src, Mat& dst, int d, bilateralFilter_8u( const Mat& src, Mat& dst, int d,
double sigma_color, double sigma_space, double sigma_color, double sigma_space,
@ -1497,12 +1514,16 @@ bilateralFilter_32f( const Mat& src, Mat& dst, int d,
} }
} }
}
void bilateralFilter( const Mat& src, Mat& dst, int d, void cv::bilateralFilter( const InputArray& _src, OutputArray _dst, int d,
double sigmaColor, double sigmaSpace, double sigmaColor, double sigmaSpace,
int borderType ) int borderType )
{ {
dst.create( src.size(), src.type() ); Mat src = _src.getMat();
_dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();
if( src.depth() == CV_8U ) if( src.depth() == CV_8U )
bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType ); bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
else if( src.depth() == CV_32F ) else if( src.depth() == CV_32F )
@ -1512,8 +1533,6 @@ void bilateralFilter( const Mat& src, Mat& dst, int d,
"Bilateral filtering is only implemented for 8u and 32f images" ); "Bilateral filtering is only implemented for 8u and 32f images" );
} }
}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
CV_IMPL void CV_IMPL void

@ -45,28 +45,17 @@
namespace cv namespace cv
{ {
template<typename QT> inline QT sqr(uchar a) { return a*a; }
template<typename QT> inline QT sqr(float a) { return a*a; }
template<typename QT> inline QT sqr(double a) { return a*a; }
template<> inline double sqr(uchar a) { return CV_8TO32F_SQR(a); }
template<typename T, typename ST, typename QT> template<typename T, typename ST, typename QT>
void integral_( const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted ) void integral_( const T* src, size_t srcstep, ST* sum, size_t sumstep,
QT* sqsum, size_t sqsumstep, ST* tilted, size_t tiltedstep,
Size size, int cn )
{ {
int cn = _src.channels();
Size size = _src.size();
int x, y, k; int x, y, k;
const T* src = (const T*)_src.data; srcstep /= sizeof(T);
ST* sum = (ST*)_sum.data; sumstep /= sizeof(ST);
ST* tilted = (ST*)_tilted.data; tiltedstep /= sizeof(ST);
QT* sqsum = (QT*)_sqsum.data; sqsumstep /= sizeof(QT);
int srcstep = (int)(_src.step/sizeof(T));
int sumstep = (int)(_sum.step/sizeof(ST));
int tiltedstep = (int)(_tilted.step/sizeof(ST));
int sqsumstep = (int)(_sqsum.step/sizeof(QT));
size.width *= cn; size.width *= cn;
@ -113,7 +102,7 @@ void integral_( const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted )
{ {
T it = src[x]; T it = src[x];
s += it; s += it;
sq += sqr<QT>(it); sq += (QT)it*it;
ST t = sum[x - sumstep] + s; ST t = sum[x - sumstep] + s;
QT tq = sqsum[x - sqsumstep] + sq; QT tq = sqsum[x - sqsumstep] + sq;
sum[x] = t; sum[x] = t;
@ -128,44 +117,54 @@ void integral_( const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted )
ST* buf = _buf; ST* buf = _buf;
ST s; ST s;
QT sq; QT sq;
for( k = 0; k < cn; k++, src++, sum++, tilted++, sqsum++, buf++ ) for( k = 0; k < cn; k++, src++, sum++, tilted++, buf++ )
{ {
sum[-cn] = tilted[-cn] = 0; sum[-cn] = tilted[-cn] = 0;
sqsum[-cn] = 0;
for( x = 0, s = 0, sq = 0; x < size.width; x += cn ) for( x = 0, s = 0, sq = 0; x < size.width; x += cn )
{ {
T it = src[x]; T it = src[x];
buf[x] = tilted[x] = it; buf[x] = tilted[x] = it;
s += it; s += it;
sq += sqr<QT>(it); sq += (QT)it*it;
sum[x] = s; sum[x] = s;
if( sqsum )
sqsum[x] = sq; sqsum[x] = sq;
} }
if( size.width == cn ) if( size.width == cn )
buf[cn] = 0; buf[cn] = 0;
if( sqsum )
{
sqsum[-cn] = 0;
sqsum++;
}
} }
for( y = 1; y < size.height; y++ ) for( y = 1; y < size.height; y++ )
{ {
src += srcstep - cn; src += srcstep - cn;
sum += sumstep - cn; sum += sumstep - cn;
sqsum += sqsumstep - cn;
tilted += tiltedstep - cn; tilted += tiltedstep - cn;
buf += -cn; buf += -cn;
for( k = 0; k < cn; k++, src++, sum++, sqsum++, tilted++, buf++ ) if( sqsum )
sqsum += sqsumstep - cn;
for( k = 0; k < cn; k++, src++, sum++, tilted++, buf++ )
{ {
T it = src[0]; T it = src[0];
ST t0 = s = it; ST t0 = s = it;
QT tq0 = sq = sqr<QT>(it); QT tq0 = sq = (QT)it*it;
sum[-cn] = 0; sum[-cn] = 0;
if( sqsum )
sqsum[-cn] = 0; sqsum[-cn] = 0;
tilted[-cn] = tilted[-tiltedstep]; tilted[-cn] = tilted[-tiltedstep];
sum[0] = sum[-sumstep] + t0; sum[0] = sum[-sumstep] + t0;
if( sqsum )
sqsum[0] = sqsum[-sqsumstep] + tq0; sqsum[0] = sqsum[-sqsumstep] + tq0;
tilted[0] = tilted[-tiltedstep] + t0 + buf[cn]; tilted[0] = tilted[-tiltedstep] + t0 + buf[cn];
@ -174,10 +173,11 @@ void integral_( const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted )
ST t1 = buf[x]; ST t1 = buf[x];
buf[x - cn] = t1 + t0; buf[x - cn] = t1 + t0;
t0 = it = src[x]; t0 = it = src[x];
tq0 = sqr<QT>(it); tq0 = (QT)it*it;
s += t0; s += t0;
sq += tq0; sq += tq0;
sum[x] = sum[x - sumstep] + s; sum[x] = sum[x - sumstep] + s;
if( sqsum )
sqsum[x] = sqsum[x - sqsumstep] + sq; sqsum[x] = sqsum[x - sqsumstep] + sq;
t1 += buf[x + cn] + t0 + tilted[x - tiltedstep - cn]; t1 += buf[x + cn] + t0 + tilted[x - tiltedstep - cn];
tilted[x] = t1; tilted[x] = t1;
@ -188,79 +188,96 @@ void integral_( const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted )
ST t1 = buf[x]; ST t1 = buf[x];
buf[x - cn] = t1 + t0; buf[x - cn] = t1 + t0;
t0 = it = src[x]; t0 = it = src[x];
tq0 = sqr<QT>(it); tq0 = (QT)it*it;
s += t0; s += t0;
sq += tq0; sq += tq0;
sum[x] = sum[x - sumstep] + s; sum[x] = sum[x - sumstep] + s;
if( sqsum )
sqsum[x] = sqsum[x - sqsumstep] + sq; sqsum[x] = sqsum[x - sqsumstep] + sq;
tilted[x] = t0 + t1 + tilted[x - tiltedstep - cn]; tilted[x] = t0 + t1 + tilted[x - tiltedstep - cn];
buf[x] = t0; buf[x] = t0;
} }
if( sqsum )
sqsum++;
} }
} }
} }
} }
typedef void (*IntegralFunc)(const Mat& _src, Mat& _sum, Mat& _sqsum, Mat& _tilted );
static void #define DEF_INTEGRAL_FUNC(suffix, T, ST, QT) \
integral( const Mat& src, Mat& sum, Mat* _sqsum, Mat* _tilted, int sdepth ) void integral_##suffix( T* src, size_t srcstep, ST* sum, size_t sumstep, QT* sqsum, size_t sqsumstep, \
ST* tilted, size_t tiltedstep, Size size, int cn ) \
{ integral_(src, srcstep, sum, sumstep, sqsum, sqsumstep, tilted, tiltedstep, size, cn); }
DEF_INTEGRAL_FUNC(8u32s, uchar, int, double)
DEF_INTEGRAL_FUNC(8u32f, uchar, float, double)
DEF_INTEGRAL_FUNC(8u64f, uchar, double, double)
DEF_INTEGRAL_FUNC(32f, float, float, float)
DEF_INTEGRAL_FUNC(32f64f, float, double, double)
DEF_INTEGRAL_FUNC(64f, double, double, double)
typedef void (*IntegralFunc)(const uchar* src, size_t srcstep, uchar* sum, size_t sumstep,
uchar* sqsum, size_t sqsumstep, uchar* tilted, size_t tstep,
Size size, int cn );
}
void cv::integral( const InputArray& _src, OutputArray _sum, OutputArray _sqsum, OutputArray _tilted, int sdepth )
{ {
Mat src = _src.getMat(), sum, sqsum, tilted;
int depth = src.depth(), cn = src.channels(); int depth = src.depth(), cn = src.channels();
Size isize(src.cols + 1, src.rows+1); Size isize(src.cols + 1, src.rows+1);
Mat sqsum, tilted;
if( sdepth <= 0 ) if( sdepth <= 0 )
sdepth = depth == CV_8U ? CV_32S : CV_64F; sdepth = depth == CV_8U ? CV_32S : CV_64F;
sdepth = CV_MAT_DEPTH(sdepth); sdepth = CV_MAT_DEPTH(sdepth);
sum.create( isize, CV_MAKETYPE(sdepth, cn) ); _sum.create( isize, CV_MAKETYPE(sdepth, cn) );
sum = _sum.getMat();
if( _tilted )
_tilted->create( isize, CV_MAKETYPE(sdepth, cn) );
else
_tilted = &tilted;
if( !_sqsum ) if( _tilted.needed() )
_sqsum = &sqsum; {
_tilted.create( isize, CV_MAKETYPE(sdepth, cn) );
tilted = _tilted.getMat();
}
if( _sqsum != &sqsum || _tilted->data ) if( _sqsum.needed() )
_sqsum->create( isize, CV_MAKETYPE(CV_64F, cn) ); {
_sqsum.create( isize, CV_MAKETYPE(CV_64F, cn) );
sqsum = _sqsum.getMat();
}
IntegralFunc func = 0; IntegralFunc func = 0;
if( depth == CV_8U && sdepth == CV_32S ) if( depth == CV_8U && sdepth == CV_32S )
func = integral_<uchar, int, double>; func = (IntegralFunc)integral_8u32s;
else if( depth == CV_8U && sdepth == CV_32F ) else if( depth == CV_8U && sdepth == CV_32F )
func = integral_<uchar, float, double>; func = (IntegralFunc)integral_8u32f;
else if( depth == CV_8U && sdepth == CV_64F ) else if( depth == CV_8U && sdepth == CV_64F )
func = integral_<uchar, double, double>; func = (IntegralFunc)integral_8u64f;
else if( depth == CV_32F && sdepth == CV_32F ) else if( depth == CV_32F && sdepth == CV_32F )
func = integral_<float, float, double>; func = (IntegralFunc)integral_32f;
else if( depth == CV_32F && sdepth == CV_64F ) else if( depth == CV_32F && sdepth == CV_64F )
func = integral_<float, double, double>; func = (IntegralFunc)integral_32f64f;
else if( depth == CV_64F && sdepth == CV_64F ) else if( depth == CV_64F && sdepth == CV_64F )
func = integral_<double, double, double>; func = (IntegralFunc)integral_64f;
else else
CV_Error( CV_StsUnsupportedFormat, "" ); CV_Error( CV_StsUnsupportedFormat, "" );
func( src, sum, *_sqsum, *_tilted ); func( src.data, src.step, sum.data, sum.step, sqsum.data, sqsum.step,
tilted.data, tilted.step, src.size(), cn );
} }
void integral( const Mat& src, Mat& sum, int sdepth ) void cv::integral( const InputArray& src, OutputArray sum, int sdepth )
{ {
integral( src, sum, 0, 0, sdepth ); integral( src, sum, OutputArray(), OutputArray(), sdepth );
} }
void integral( const Mat& src, Mat& sum, Mat& sqsum, int sdepth ) void cv::integral( const InputArray& src, OutputArray sum, OutputArray sqsum, int sdepth )
{ {
integral( src, sum, &sqsum, 0, sdepth ); integral( src, sum, sqsum, OutputArray(), sdepth );
}
void integral( const Mat& src, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth )
{
integral( src, sum, &sqsum, &tilted, sdepth );
}
} }
@ -283,7 +300,8 @@ cvIntegral( const CvArr* image, CvArr* sumImage,
tilted0 = tilted = cv::cvarrToMat(tiltedSumImage); tilted0 = tilted = cv::cvarrToMat(tiltedSumImage);
ptilted = &tilted; ptilted = &tilted;
} }
cv::integral( src, sum, psqsum, ptilted, sum.depth() ); cv::integral( src, sum, psqsum ? cv::OutputArray(*psqsum) : cv::OutputArray(),
ptilted ? cv::OutputArray(*ptilted) : cv::OutputArray(), sum.depth() );
CV_Assert( sum.data == sum0.data && sqsum.data == sqsum0.data && tilted.data == tilted0.data ); CV_Assert( sum.data == sum0.data && sqsum.data == sqsum0.data && tilted.data == tilted0.data );
} }

@ -233,10 +233,11 @@ cv::crossCorr( const Mat& img, const Mat& templ, Mat& corr,
icvCrossCorr( &_img, &_templ, &_corr, anchor, delta, borderType ); icvCrossCorr( &_img, &_templ, &_corr, anchor, delta, borderType );
}*/ }*/
}
/*****************************************************************************************/ /*****************************************************************************************/
void matchTemplate( const Mat& _img, const Mat& _templ, Mat& result, int method ) void cv::matchTemplate( const InputArray& _img, const InputArray& _templ, OutputArray _result, int method )
{ {
CV_Assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED ); CV_Assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED );
@ -246,17 +247,19 @@ void matchTemplate( const Mat& _img, const Mat& _templ, Mat& result, int method
method == CV_TM_SQDIFF_NORMED || method == CV_TM_SQDIFF_NORMED ||
method == CV_TM_CCOEFF_NORMED; method == CV_TM_CCOEFF_NORMED;
Mat img = _img, templ = _templ; Mat img = _img.getMat(), templ = _templ.getMat();
if( img.rows < templ.rows || img.cols < templ.cols ) if( img.rows < templ.rows || img.cols < templ.cols )
std::swap(img, templ); std::swap(img, templ);
CV_Assert( (img.depth() == CV_8U || img.depth() == CV_32F) && CV_Assert( (img.depth() == CV_8U || img.depth() == CV_32F) &&
img.type() == templ.type() ); img.type() == templ.type() );
Size corrSize(img.cols - templ.cols + 1, img.rows - templ.rows + 1);
_result.create(corrSize, CV_32F);
Mat result = _result.getMat();
int cn = img.channels(); int cn = img.channels();
crossCorr( img, templ, result, crossCorr( img, templ, result, result.size(), result.type(), Point(0,0), 0, 0);
Size(img.cols - templ.cols + 1, img.rows - templ.rows + 1),
CV_32F, Point(0,0), 0, 0);
if( method == CV_TM_CCORR ) if( method == CV_TM_CCORR )
return; return;
@ -368,8 +371,6 @@ void matchTemplate( const Mat& _img, const Mat& _templ, Mat& result, int method
} }
} }
}
CV_IMPL void CV_IMPL void
cvMatchTemplate( const CvArr* _img, const CvArr* _templ, CvArr* _result, int method ) cvMatchTemplate( const CvArr* _img, const CvArr* _templ, CvArr* _result, int method )

@ -475,20 +475,24 @@ getThreshVal_Otsu_8u( const Mat& _src )
return max_val; return max_val;
} }
}
double threshold( const Mat& _src, Mat& _dst, double thresh, double maxval, int type ) double cv::threshold( const InputArray& _src, OutputArray _dst, double thresh, double maxval, int type )
{ {
Mat src = _src.getMat();
bool use_otsu = (type & THRESH_OTSU) != 0; bool use_otsu = (type & THRESH_OTSU) != 0;
type &= THRESH_MASK; type &= THRESH_MASK;
if( use_otsu ) if( use_otsu )
{ {
CV_Assert( _src.type() == CV_8UC1 ); CV_Assert( src.type() == CV_8UC1 );
thresh = getThreshVal_Otsu_8u(_src); thresh = getThreshVal_Otsu_8u(src);
} }
_dst.create( _src.size(), _src.type() ); _dst.create( src.size(), src.type() );
if( _src.depth() == CV_8U ) Mat dst = _dst.getMat();
if( src.depth() == CV_8U )
{ {
int ithresh = cvFloor(thresh); int ithresh = cvFloor(thresh);
thresh = ithresh; thresh = ithresh;
@ -506,16 +510,16 @@ double threshold( const Mat& _src, Mat& _dst, double thresh, double maxval, int
int v = type == THRESH_BINARY ? (ithresh >= 255 ? 0 : imaxval) : int v = type == THRESH_BINARY ? (ithresh >= 255 ? 0 : imaxval) :
type == THRESH_BINARY_INV ? (ithresh >= 255 ? imaxval : 0) : type == THRESH_BINARY_INV ? (ithresh >= 255 ? imaxval : 0) :
type == THRESH_TRUNC ? imaxval : 0; type == THRESH_TRUNC ? imaxval : 0;
_dst = Scalar::all(v); dst = Scalar::all(v);
} }
else else
_src.copyTo(_dst); src.copyTo(dst);
} }
else else
thresh_8u( _src, _dst, (uchar)ithresh, (uchar)imaxval, type ); thresh_8u( src, dst, (uchar)ithresh, (uchar)imaxval, type );
} }
else if( _src.depth() == CV_32F ) else if( src.depth() == CV_32F )
thresh_32f( _src, _dst, (float)thresh, (float)maxval, type ); thresh_32f( src, dst, (float)thresh, (float)maxval, type );
else else
CV_Error( CV_StsUnsupportedFormat, "" ); CV_Error( CV_StsUnsupportedFormat, "" );
@ -523,31 +527,33 @@ double threshold( const Mat& _src, Mat& _dst, double thresh, double maxval, int
} }
void adaptiveThreshold( const Mat& _src, Mat& _dst, double maxValue, void cv::adaptiveThreshold( const InputArray& _src, OutputArray _dst, double maxValue,
int method, int type, int blockSize, double delta ) int method, int type, int blockSize, double delta )
{ {
CV_Assert( _src.type() == CV_8UC1 ); Mat src = _src.getMat();
CV_Assert( src.type() == CV_8UC1 );
CV_Assert( blockSize % 2 == 1 && blockSize > 1 ); CV_Assert( blockSize % 2 == 1 && blockSize > 1 );
Size size = _src.size(); Size size = src.size();
_dst.create( size, _src.type() ); _dst.create( size, src.type() );
Mat dst = _dst.getMat();
if( maxValue < 0 ) if( maxValue < 0 )
{ {
_dst = Scalar(0); dst = Scalar(0);
return; return;
} }
Mat _mean; Mat mean;
if( _src.data != _dst.data ) if( src.data != dst.data )
_mean = _dst; mean = dst;
if( method == ADAPTIVE_THRESH_MEAN_C ) if( method == ADAPTIVE_THRESH_MEAN_C )
boxFilter( _src, _mean, _src.type(), Size(blockSize, blockSize), boxFilter( src, mean, src.type(), Size(blockSize, blockSize),
Point(-1,-1), true, BORDER_REPLICATE ); Point(-1,-1), true, BORDER_REPLICATE );
else if( method == ADAPTIVE_THRESH_GAUSSIAN_C ) else if( method == ADAPTIVE_THRESH_GAUSSIAN_C )
GaussianBlur( _src, _mean, Size(blockSize, blockSize), 0, 0, BORDER_REPLICATE ); GaussianBlur( src, mean, Size(blockSize, blockSize), 0, 0, BORDER_REPLICATE );
else else
CV_Error( CV_StsBadFlag, "Unknown/unsupported adaptive threshold method" ); CV_Error( CV_StsBadFlag, "Unknown/unsupported adaptive threshold method" );
@ -565,7 +571,7 @@ void adaptiveThreshold( const Mat& _src, Mat& _dst, double maxValue,
else else
CV_Error( CV_StsBadFlag, "Unknown/unsupported threshold type" ); CV_Error( CV_StsBadFlag, "Unknown/unsupported threshold type" );
if( _src.isContinuous() && _mean.isContinuous() && _dst.isContinuous() ) if( src.isContinuous() && mean.isContinuous() && dst.isContinuous() )
{ {
size.width *= size.height; size.width *= size.height;
size.height = 1; size.height = 1;
@ -573,15 +579,13 @@ void adaptiveThreshold( const Mat& _src, Mat& _dst, double maxValue,
for( i = 0; i < size.height; i++ ) for( i = 0; i < size.height; i++ )
{ {
const uchar* src = _src.data + _src.step*i; const uchar* sdata = src.data + src.step*i;
const uchar* mean = _mean.data + _mean.step*i; const uchar* mdata = mean.data + mean.step*i;
uchar* dst = _dst.data + _dst.step*i; uchar* ddata = dst.data + dst.step*i;
for( j = 0; j < size.width; j++ ) for( j = 0; j < size.width; j++ )
dst[j] = tab[src[j] - mean[j] + 255]; ddata[j] = tab[sdata[j] - mdata[j] + 255];
}
} }
} }
CV_IMPL double CV_IMPL double

@ -42,12 +42,10 @@
#include "precomp.hpp" #include "precomp.hpp"
namespace cv cv::Mat cv::getDefaultNewCameraMatrix( const InputArray& _cameraMatrix, Size imgsize,
{
Mat getDefaultNewCameraMatrix( const Mat& cameraMatrix, Size imgsize,
bool centerPrincipalPoint ) bool centerPrincipalPoint )
{ {
Mat cameraMatrix = _cameraMatrix.getMat();
if( !centerPrincipalPoint && cameraMatrix.type() == CV_64F ) if( !centerPrincipalPoint && cameraMatrix.type() == CV_64F )
return cameraMatrix; return cameraMatrix;
@ -61,35 +59,42 @@ Mat getDefaultNewCameraMatrix( const Mat& cameraMatrix, Size imgsize,
return newCameraMatrix; return newCameraMatrix;
} }
void initUndistortRectifyMap( const Mat& _cameraMatrix, const Mat& _distCoeffs, void cv::initUndistortRectifyMap( const InputArray& _cameraMatrix, const InputArray& _distCoeffs,
const Mat& matR, const Mat& _newCameraMatrix, const InputArray& _matR, const InputArray& _newCameraMatrix,
Size size, int m1type, Mat& map1, Mat& map2 ) Size size, int m1type, OutputArray _map1, OutputArray _map2 )
{ {
Mat cameraMatrix = _cameraMatrix.getMat(), distCoeffs = _distCoeffs.getMat();
Mat matR = _matR.getMat(), newCameraMatrix = _newCameraMatrix.getMat();
if( m1type <= 0 ) if( m1type <= 0 )
m1type = CV_16SC2; m1type = CV_16SC2;
CV_Assert( m1type == CV_16SC2 || m1type == CV_32FC1 || m1type == CV_32FC2 ); CV_Assert( m1type == CV_16SC2 || m1type == CV_32FC1 || m1type == CV_32FC2 );
map1.create( size, m1type ); _map1.create( size, m1type );
Mat map1 = _map1.getMat(), map2;
if( m1type != CV_32FC2 ) if( m1type != CV_32FC2 )
map2.create( size, m1type == CV_16SC2 ? CV_16UC1 : CV_32FC1 ); {
_map2.create( size, m1type == CV_16SC2 ? CV_16UC1 : CV_32FC1 );
map2 = _map2.getMat();
}
else else
map2.release(); _map2.release();
Mat_<double> R = Mat_<double>::eye(3, 3), distCoeffs; Mat_<double> R = Mat_<double>::eye(3, 3);
Mat_<double> A = Mat_<double>(_cameraMatrix), Ar; Mat_<double> A = Mat_<double>(cameraMatrix), Ar;
if( _newCameraMatrix.data ) if( newCameraMatrix.data )
Ar = Mat_<double>(_newCameraMatrix); Ar = Mat_<double>(newCameraMatrix);
else else
Ar = getDefaultNewCameraMatrix( A, size, true ); Ar = getDefaultNewCameraMatrix( A, size, true );
if( matR.data ) if( matR.data )
R = Mat_<double>(matR); R = Mat_<double>(matR);
if( _distCoeffs.data ) if( distCoeffs.data )
distCoeffs = Mat_<double>(_distCoeffs); distCoeffs = Mat_<double>(distCoeffs);
else else
{ {
distCoeffs.create(8, 1); distCoeffs.create(8, 1, CV_64F);
distCoeffs = 0.; distCoeffs = 0.;
} }
@ -156,28 +161,33 @@ void initUndistortRectifyMap( const Mat& _cameraMatrix, const Mat& _distCoeffs,
} }
void undistort( const Mat& src, Mat& dst, const Mat& _cameraMatrix, void cv::undistort( const InputArray& _src, OutputArray _dst, const InputArray& _cameraMatrix,
const Mat& _distCoeffs, const Mat& _newCameraMatrix ) const InputArray& _distCoeffs, const InputArray& _newCameraMatrix )
{ {
dst.create( src.size(), src.type() ); Mat src = _src.getMat(), cameraMatrix = _cameraMatrix.getMat();
Mat distCoeffs = _distCoeffs.getMat(), newCameraMatrix = _newCameraMatrix.getMat();
_dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();
CV_Assert( dst.data != src.data ); CV_Assert( dst.data != src.data );
int stripe_size0 = std::min(std::max(1, (1 << 12) / std::max(src.cols, 1)), src.rows); int stripe_size0 = std::min(std::max(1, (1 << 12) / std::max(src.cols, 1)), src.rows);
Mat map1(stripe_size0, src.cols, CV_16SC2), map2(stripe_size0, src.cols, CV_16UC1); Mat map1(stripe_size0, src.cols, CV_16SC2), map2(stripe_size0, src.cols, CV_16UC1);
Mat_<double> A, distCoeffs, Ar, I = Mat_<double>::eye(3,3); Mat_<double> A, Ar, I = Mat_<double>::eye(3,3);
_cameraMatrix.convertTo(A, CV_64F); cameraMatrix.convertTo(A, CV_64F);
if( _distCoeffs.data ) if( distCoeffs.data )
distCoeffs = Mat_<double>(_distCoeffs); distCoeffs = Mat_<double>(distCoeffs);
else else
{ {
distCoeffs.create(5, 1); distCoeffs.create(5, 1, CV_64F);
distCoeffs = 0.; distCoeffs = 0.;
} }
if( _newCameraMatrix.data ) if( newCameraMatrix.data )
_newCameraMatrix.convertTo(Ar, CV_64F); newCameraMatrix.convertTo(Ar, CV_64F);
else else
A.copyTo(Ar); A.copyTo(Ar);
@ -196,8 +206,6 @@ void undistort( const Mat& src, Mat& dst, const Mat& _cameraMatrix,
} }
} }
}
CV_IMPL void CV_IMPL void
cvUndistort2( const CvArr* srcarr, CvArr* dstarr, const CvMat* Aarr, const CvMat* dist_coeffs, const CvMat* newAarr ) cvUndistort2( const CvArr* srcarr, CvArr* dstarr, const CvMat* Aarr, const CvMat* dist_coeffs, const CvMat* newAarr )
@ -373,48 +381,34 @@ void cvUndistortPoints( const CvMat* _src, CvMat* _dst, const CvMat* _cameraMatr
} }
namespace cv void cv::undistortPoints( const InputArray& _src, OutputArray _dst,
const InputArray& _cameraMatrix,
const InputArray& _distCoeffs,
const InputArray& _Rmat,
const InputArray& _Pmat )
{ {
Mat src = _src.getMat(), cameraMatrix = _cameraMatrix.getMat();
Mat distCoeffs = _distCoeffs.getMat(), R = _Rmat.getMat(), P = _Pmat.getMat();
void undistortPoints( const Mat& src, Mat& dst,
const Mat& cameraMatrix, const Mat& distCoeffs,
const Mat& R, const Mat& P )
{
CV_Assert( src.isContinuous() && (src.depth() == CV_32F || src.depth() == CV_64F) && CV_Assert( src.isContinuous() && (src.depth() == CV_32F || src.depth() == CV_64F) &&
((src.rows == 1 && src.channels() == 2) || src.cols*src.channels() == 2)); ((src.rows == 1 && src.channels() == 2) || src.cols*src.channels() == 2));
dst.create(src.size(), src.type()); _dst.create(src.size(), src.type(), -1, true);
CvMat _src = src, _dst = dst, _cameraMatrix = cameraMatrix; Mat dst = _dst.getMat();
CvMat matR, matP, _distCoeffs, *pR=0, *pP=0, *pD=0;
if( R.data )
pR = &(matR = R);
if( P.data )
pP = &(matP = P);
if( distCoeffs.data )
pD = &(_distCoeffs = distCoeffs);
cvUndistortPoints(&_src, &_dst, &_cameraMatrix, pD, pR, pP);
}
void undistortPoints( const Mat& src, std::vector<Point2f>& dst,
const Mat& cameraMatrix, const Mat& distCoeffs,
const Mat& R, const Mat& P )
{
size_t sz = src.cols*src.rows*src.channels()/2;
CV_Assert( src.isContinuous() && src.depth() == CV_32F &&
((src.rows == 1 && src.channels() == 2) || src.cols*src.channels() == 2));
dst.resize(sz); CvMat _csrc = src, _cdst = dst, _ccameraMatrix = cameraMatrix;
CvMat _src = src, _dst = Mat(dst), _cameraMatrix = cameraMatrix; CvMat matR, matP, _cdistCoeffs, *pR=0, *pP=0, *pD=0;
CvMat matR, matP, _distCoeffs, *pR=0, *pP=0, *pD=0;
if( R.data ) if( R.data )
pR = &(matR = R); pR = &(matR = R);
if( P.data ) if( P.data )
pP = &(matP = P); pP = &(matP = P);
if( distCoeffs.data ) if( distCoeffs.data )
pD = &(_distCoeffs = distCoeffs); pD = &(_cdistCoeffs = distCoeffs);
cvUndistortPoints(&_src, &_dst, &_cameraMatrix, pD, pR, pP); cvUndistortPoints(&_csrc, &_cdst, &_ccameraMatrix, pD, pR, pP);
} }
namespace cv
{
static Point2f mapPointSpherical(const Point2f& p, float alpha, Vec4d* J, int projType) static Point2f mapPointSpherical(const Point2f& p, float alpha, Vec4d* J, int projType)
{ {
@ -492,11 +486,13 @@ static Point2f invMapPointSpherical(Point2f _p, float alpha, int projType)
return i < maxiter ? Point2f((float)q[0], (float)q[1]) : Point2f(-FLT_MAX, -FLT_MAX); return i < maxiter ? Point2f((float)q[0], (float)q[1]) : Point2f(-FLT_MAX, -FLT_MAX);
} }
}
float initWideAngleProjMap( const Mat& cameraMatrix0, const Mat& distCoeffs0, float cv::initWideAngleProjMap( const InputArray& _cameraMatrix0, const InputArray& _distCoeffs0,
Size imageSize, int destImageWidth, int m1type, Size imageSize, int destImageWidth, int m1type,
Mat& map1, Mat& map2, int projType, double _alpha ) OutputArray _map1, OutputArray _map2, int projType, double _alpha )
{ {
Mat cameraMatrix0 = _cameraMatrix0.getMat(), distCoeffs0 = _distCoeffs0.getMat();
double k[8] = {0,0,0,0,0,0,0,0}, M[9]={0,0,0,0,0,0,0,0,0}; double k[8] = {0,0,0,0,0,0,0,0}, M[9]={0,0,0,0,0,0,0,0,0};
Mat distCoeffs(distCoeffs0.rows, distCoeffs0.cols, CV_MAKETYPE(CV_64F,distCoeffs0.channels()), k); Mat distCoeffs(distCoeffs0.rows, distCoeffs0.cols, CV_MAKETYPE(CV_64F,distCoeffs0.channels()), k);
Mat cameraMatrix(3,3,CV_64F,M); Mat cameraMatrix(3,3,CV_64F,M);
@ -562,15 +558,15 @@ float initWideAngleProjMap( const Mat& cameraMatrix0, const Mat& distCoeffs0,
if(m1type == CV_32FC2) if(m1type == CV_32FC2)
{ {
_map1.create(mapxy.size(), mapxy.type());
Mat map1 = _map1.getMat();
mapxy.copyTo(map1); mapxy.copyTo(map1);
map2.release(); _map2.release();
} }
else else
convertMaps(mapxy, Mat(), map1, map2, m1type, false); convertMaps(mapxy, Mat(), _map1, _map2, m1type, false);
return scale; return scale;
} }
}
/* End of file */ /* End of file */

@ -195,13 +195,17 @@ static void copyMakeConstBorder_8u( const uchar* src, size_t srcstep, Size srcro
memcpy(dst + (i + srcroi.height)*dststep, constBuf, dstroi.width); memcpy(dst + (i + srcroi.height)*dststep, constBuf, dstroi.width);
} }
}
void copyMakeBorder( const Mat& src, Mat& dst, int top, int bottom, void cv::copyMakeBorder( const InputArray& _src, OutputArray _dst, int top, int bottom,
int left, int right, int borderType, const Scalar& value ) int left, int right, int borderType, const Scalar& value )
{ {
Mat src = _src.getMat();
CV_Assert( top >= 0 && bottom >= 0 && left >= 0 && right >= 0 ); CV_Assert( top >= 0 && bottom >= 0 && left >= 0 && right >= 0 );
dst.create( src.rows + top + bottom, src.cols + left + right, src.type() ); _dst.create( src.rows + top + bottom, src.cols + left + right, src.type() );
Mat dst = _dst.getMat();
if( borderType != BORDER_CONSTANT ) if( borderType != BORDER_CONSTANT )
copyMakeBorder_8u( src.data, src.step, src.size(), copyMakeBorder_8u( src.data, src.step, src.size(),
dst.data, dst.step, dst.size(), dst.data, dst.step, dst.size(),
@ -216,8 +220,6 @@ void copyMakeBorder( const Mat& src, Mat& dst, int top, int bottom,
} }
} }
}
CV_IMPL void CV_IMPL void
cvCopyMakeBorder( const CvArr* srcarr, CvArr* dstarr, CvPoint offset, cvCopyMakeBorder( const CvArr* srcarr, CvArr* dstarr, CvPoint offset,

@ -524,7 +524,7 @@ int CV_WarpAffineTest::prepare_test_case( int test_case_idx )
angle = cvtest::randReal(rng)*360; angle = cvtest::randReal(rng)*360;
scale = ((double)dst.rows/src.rows + (double)dst.cols/src.cols)*0.5; scale = ((double)dst.rows/src.rows + (double)dst.cols/src.cols)*0.5;
getRotationMatrix2D(center, angle, scale).convertTo(mat, mat.depth()); getRotationMatrix2D(center, angle, scale).convertTo(mat, mat.depth());
rng.fill( tmp, CV_RAND_NORMAL, cvScalarAll(1.), cvScalarAll(0.01) ); rng.fill( tmp, CV_RAND_NORMAL, Scalar::all(1.), Scalar::all(0.01) );
cv::max(tmp, 0.9, tmp); cv::max(tmp, 0.9, tmp);
cv::min(tmp, 1.1, tmp); cv::min(tmp, 1.1, tmp);
cv::multiply(tmp, mat, mat, 1.); cv::multiply(tmp, mat, mat, 1.);
@ -639,7 +639,7 @@ int CV_WarpPerspectiveTest::prepare_test_case( int test_case_idx )
float buf[16]; float buf[16];
Mat tmp( 1, 16, CV_32FC1, buf ); Mat tmp( 1, 16, CV_32FC1, buf );
rng.fill( tmp, CV_RAND_NORMAL, cvScalarAll(0.), cvScalarAll(0.1) ); rng.fill( tmp, CV_RAND_NORMAL, Scalar::all(0.), Scalar::all(0.1) );
for( i = 0; i < 4; i++ ) for( i = 0; i < 4; i++ )
{ {

@ -1228,7 +1228,7 @@ int CvANN_MLP::train_rprop( CvVectors x0, CvVectors u, const double* sw )
__BEGIN__; __BEGIN__;
int i, ivcount, ovcount, l_count, total = 0, max_iter, buf_sz, dcount0, dcount=0; int i, ivcount, ovcount, l_count, total = 0, max_iter, buf_sz, dcount0;
double *buf_ptr; double *buf_ptr;
double prev_E = DBL_MAX*0.5, epsilon; double prev_E = DBL_MAX*0.5, epsilon;
double dw_plus, dw_minus, dw_min, dw_max; double dw_plus, dw_minus, dw_min, dw_max;
@ -1294,10 +1294,7 @@ int CvANN_MLP::train_rprop( CvVectors x0, CvVectors u, const double* sw )
*/ */
for( iter = 0; iter < max_iter; iter++ ) for( iter = 0; iter < max_iter; iter++ )
{ {
int n1, n2, si, j, k; int n1, n2, j, k;
double* w;
CvMat _w, _dEdw, hdr1, hdr2, ghdr1, ghdr2, _df;
CvMat *x1, *x2, *grad1, *grad2, *temp;
double E = 0; double E = 0;
// first, iterate through all the samples and compute dEdw // first, iterate through all the samples and compute dEdw

@ -355,8 +355,6 @@ float CvKNearest::find_nearest( const CvMat* _samples, int k, CvMat* _results,
float result = 0.f; float result = 0.f;
const int max_blk_count = 128, max_buf_sz = 1 << 12; const int max_blk_count = 128, max_buf_sz = 1 << 12;
int i, count, count_scale, blk_count0, blk_count = 0, buf_sz, k1;
if( !samples ) if( !samples )
CV_Error( CV_StsError, "The search tree must be constructed first using train method" ); CV_Error( CV_StsError, "The search tree must be constructed first using train method" );
@ -395,15 +393,15 @@ float CvKNearest::find_nearest( const CvMat* _samples, int k, CvMat* _results,
"The distances from the neighbors (if present) must be floating-point matrix of <num_samples> x <k> size" ); "The distances from the neighbors (if present) must be floating-point matrix of <num_samples> x <k> size" );
} }
count = _samples->rows; int count = _samples->rows;
count_scale = k*2; int count_scale = k*2;
blk_count0 = MIN( count, max_blk_count ); int blk_count0 = MIN( count, max_blk_count );
buf_sz = MIN( blk_count0 * count_scale, max_buf_sz ); int buf_sz = MIN( blk_count0 * count_scale, max_buf_sz );
blk_count0 = MAX( buf_sz/count_scale, 1 ); blk_count0 = MAX( buf_sz/count_scale, 1 );
blk_count0 += blk_count0 % 2; blk_count0 += blk_count0 % 2;
blk_count0 = MIN( blk_count0, count ); blk_count0 = MIN( blk_count0, count );
buf_sz = blk_count0 * count_scale + k; buf_sz = blk_count0 * count_scale + k;
k1 = get_sample_count(); int k1 = get_sample_count();
k1 = MIN( k1, k ); k1 = MIN( k1, k );
cv::parallel_for(cv::BlockedRange(0, count), P1(this, buf_sz, k, _samples, _neighbors, k1, cv::parallel_for(cv::BlockedRange(0, count), P1(this, buf_sz, k, _samples, _neighbors, k1,

@ -203,7 +203,7 @@ void CV_KMeansTest::run( int /*start_from*/ )
int code = cvtest::TS::OK; int code = cvtest::TS::OK;
Mat bestLabels; Mat bestLabels;
// 1. flag==KMEANS_PP_CENTERS // 1. flag==KMEANS_PP_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_PP_CENTERS, 0 ); kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_PP_CENTERS, OutputArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );
@ -211,7 +211,7 @@ void CV_KMeansTest::run( int /*start_from*/ )
} }
// 2. flag==KMEANS_RANDOM_CENTERS // 2. flag==KMEANS_RANDOM_CENTERS
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_RANDOM_CENTERS, 0 ); kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_RANDOM_CENTERS, OutputArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );
@ -223,7 +223,7 @@ void CV_KMeansTest::run( int /*start_from*/ )
RNG rng; RNG rng;
for( int i = 0; i < 0.5f * pointsCount; i++ ) for( int i = 0; i < 0.5f * pointsCount; i++ )
bestLabels.at<int>( rng.next() % pointsCount, 0 ) = rng.next() % 3; bestLabels.at<int>( rng.next() % pointsCount, 0 ) = rng.next() % 3;
kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_USE_INITIAL_LABELS, 0 ); kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_USE_INITIAL_LABELS, OutputArray() );
if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) if( calcErr( bestLabels, labels, sizes, false ) > 0.01f )
{ {
ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); ts->printf( cvtest::TS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" );

@ -184,7 +184,7 @@ bool PlanarObjectDetector::operator()(const vector<Mat>& pyr, const vector<KeyPo
return false; return false;
vector<uchar> mask; vector<uchar> mask;
matH = findHomography(Mat(fromPt), Mat(toPt), mask, RANSAC, 10); matH = findHomography(fromPt, toPt, RANSAC, 10, mask);
if( matH.data ) if( matH.data )
{ {
const Mat_<double>& H = matH; const Mat_<double>& H = matH;

@ -24,20 +24,6 @@ using cv::Rect;
class CV_EXPORTS TS; class CV_EXPORTS TS;
enum
{
TYPE_MASK_8U = 1 << CV_8U,
TYPE_MASK_8S = 1 << CV_8S,
TYPE_MASK_16U = 1 << CV_16U,
TYPE_MASK_16S = 1 << CV_16S,
TYPE_MASK_32S = 1 << CV_32S,
TYPE_MASK_32F = 1 << CV_32F,
TYPE_MASK_64F = 1 << CV_64F,
TYPE_MASK_ALL = (TYPE_MASK_64F<<1)-1,
TYPE_MASK_ALL_BUT_8S = TYPE_MASK_ALL & ~TYPE_MASK_8S,
TYPE_MASK_FLT = TYPE_MASK_32F + TYPE_MASK_64F
};
CV_EXPORTS int64 readSeed(const char* str); CV_EXPORTS int64 readSeed(const char* str);
CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 ); CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );

@ -71,7 +71,7 @@ int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels)
{ {
int channels = rng.uniform(minChannels, maxChannels+1); int channels = rng.uniform(minChannels, maxChannels+1);
int depth = 0; int depth = 0;
CV_Assert((typeMask & TYPE_MASK_ALL) != 0); CV_Assert((typeMask & DEPTH_MASK_ALL) != 0);
for(;;) for(;;)
{ {
depth = rng.uniform(CV_8U, CV_64F+1); depth = rng.uniform(CV_8U, CV_64F+1);

@ -358,7 +358,7 @@ public:
//! the virtual destructor //! the virtual destructor
virtual ~BackgroundSubtractor(); virtual ~BackgroundSubtractor();
//! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image. //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image.
CV_WRAP_AS(apply) virtual void operator()(const Mat& image, CV_OUT Mat& fgmask, CV_WRAP_AS(apply) virtual void operator()(const InputArray& image, OutputArray fgmask,
double learningRate=0); double learningRate=0);
}; };
@ -383,7 +383,7 @@ public:
//! the destructor //! the destructor
virtual ~BackgroundSubtractorMOG(); virtual ~BackgroundSubtractorMOG();
//! the update operator //! the update operator
virtual void operator()(const Mat& image, Mat& fgmask, double learningRate=0); virtual void operator()(const InputArray& image, OutputArray fgmask, double learningRate=0);
//! re-initiaization method //! re-initiaization method
virtual void initialize(Size frameSize, int frameType); virtual void initialize(Size frameSize, int frameType);
@ -400,52 +400,73 @@ public:
}; };
class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor class BackgroundSubtractorMOG2 : public BackgroundSubtractor
{ {
public: public:
//! the default constructor //! the default constructor
CV_WRAP BackgroundSubtractorMOG2(); BackgroundSubtractorMOG2();
//! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength //! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength
CV_WRAP BackgroundSubtractorMOG2(double alphaT, BackgroundSubtractorMOG2(int history, float varThreshold, bool bShadowDetection=1);
double sigma=15,
int nmixtures=5,
bool postFiltering=false,
double minArea=15,
bool detectShadows=true,
bool removeForeground=false,
double Tb=16,
double Tg=9,
double TB=0.9,
double CT=0.05,
int shadowOutputValue=127,
double tau=0.5);
//! the destructor //! the destructor
virtual ~BackgroundSubtractorMOG2(); virtual ~BackgroundSubtractorMOG2();
//! the update operator //! the update operator
virtual void operator()(const Mat& image, Mat& fgmask, double learningRate=0); virtual void operator()(const InputArray& image, OutputArray fgmask, double learningRate=-1);
//! re-initiaization method //! re-initiaization method
virtual void initialize(Size frameSize, virtual void initialize(Size frameSize, int frameType);
double alphaT,
double sigma=15, Size frameSize;
int nmixtures=5, int frameType;
bool postFiltering=false, Mat bgmodel;
double minArea=15, Mat bgmodelUsedModes;//keep track of number of modes per pixel
bool detectShadows=true, int nframes;
bool removeForeground=false, int history;
int nmixtures;
double Tb=16, //! here it is the maximum allowed number of mixture comonents.
double Tg=9, //! Actual number is determined dynamically per pixel
double TB=0.9, float varThreshold;
double CT=0.05, // threshold on the squared Mahalan. dist. to decide if it is well described
//by the background model or not. Related to Cthr from the paper.
int nShadowDetection=127, //This does not influence the update of the background. A typical value could be 4 sigma
double tau=0.5); //and that is varThreshold=4*4=16; Corresponds to Tb in the paper.
void* model; /////////////////////////
//less important parameters - things you might change but be carefull
////////////////////////
float backgroundRatio;
//corresponds to fTB=1-cf from the paper
//TB - threshold when the component becomes significant enough to be included into
//the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.
//For alpha=0.001 it means that the mode should exist for approximately 105 frames before
//it is considered foreground
//float noiseSigma;
float varThresholdGen;
//correspondts to Tg - threshold on the squared Mahalan. dist. to decide
//when a sample is close to the existing components. If it is not close
//to any a new component will be generated. I use 3 sigma => Tg=3*3=9.
//Smaller Tg leads to more generated components and higher Tg might make
//lead to small number of components but they can grow too large
float fVarInit;
float fVarMin;
float fVarMax;
//initial variance for the newly generated components.
//It will will influence the speed of adaptation. A good guess should be made.
//A simple way is to estimate the typical standard deviation from the images.
//I used here 10 as a reasonable value
// min and max can be used to further control the variance
float fCT;//CT - complexity reduction prior
//this is related to the number of samples needed to accept that a component
//actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get
//the standard Stauffer&Grimson algorithm (maybe not exact but very similar)
//shadow detection parameters
bool bShadowDetection;//default 1 - do shadow detection
unsigned char nShadowDetection;//do shadow detection - insert this value as the detection result - 127 default value
float fTau;
// Tau - shadow threshold. The shadow is detected if the pixel is darker
//version of the background. Tau is a threshold on how much darker the shadow can be.
//Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow
//See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.
}; };
} }

@ -244,30 +244,30 @@ namespace cv
{ {
//! updates motion history image using the current silhouette //! updates motion history image using the current silhouette
CV_EXPORTS_W void updateMotionHistory( const Mat& silhouette, Mat& mhi, CV_EXPORTS_W void updateMotionHistory( const InputArray& silhouette, InputOutputArray mhi,
double timestamp, double duration ); double timestamp, double duration );
//! computes the motion gradient orientation image from the motion history image //! computes the motion gradient orientation image from the motion history image
CV_EXPORTS_W void calcMotionGradient( const Mat& mhi, CV_OUT Mat& mask, CV_EXPORTS_W void calcMotionGradient( const InputArray& mhi, OutputArray mask,
CV_OUT Mat& orientation, OutputArray orientation,
double delta1, double delta2, double delta1, double delta2,
int apertureSize=3 ); int apertureSize=3 );
//! computes the global orientation of the selected motion history image part //! computes the global orientation of the selected motion history image part
CV_EXPORTS_W double calcGlobalOrientation( const Mat& orientation, const Mat& mask, CV_EXPORTS_W double calcGlobalOrientation( const InputArray& orientation, const InputArray& mask,
const Mat& mhi, double timestamp, const InputArray& mhi, double timestamp,
double duration ); double duration );
CV_EXPORTS_W void segmentMotion(const Mat& mhi, Mat& segmask, CV_EXPORTS_W void segmentMotion(const InputArray& mhi, OutputArray segmask,
vector<Rect>& boundingRects, vector<Rect>& boundingRects,
double timestamp, double segThresh); double timestamp, double segThresh);
//! updates the object tracking window using CAMSHIFT algorithm //! updates the object tracking window using CAMSHIFT algorithm
CV_EXPORTS_W RotatedRect CamShift( const Mat& probImage, CV_IN_OUT Rect& window, CV_EXPORTS_W RotatedRect CamShift( const InputArray& probImage, CV_IN_OUT Rect& window,
TermCriteria criteria ); TermCriteria criteria );
//! updates the object tracking window using meanshift algorithm //! updates the object tracking window using meanshift algorithm
CV_EXPORTS_W int meanShift( const Mat& probImage, CV_IN_OUT Rect& window, CV_EXPORTS_W int meanShift( const InputArray& probImage, CV_IN_OUT Rect& window,
TermCriteria criteria ); TermCriteria criteria );
/*! /*!
@ -315,9 +315,9 @@ public:
enum { OPTFLOW_USE_INITIAL_FLOW=4, OPTFLOW_FARNEBACK_GAUSSIAN=256 }; enum { OPTFLOW_USE_INITIAL_FLOW=4, OPTFLOW_FARNEBACK_GAUSSIAN=256 };
//! computes sparse optical flow using multi-scale Lucas-Kanade algorithm //! computes sparse optical flow using multi-scale Lucas-Kanade algorithm
CV_EXPORTS_W void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg, CV_EXPORTS_W void calcOpticalFlowPyrLK( const InputArray& prevImg, const InputArray& nextImg,
const vector<Point2f>& prevPts, CV_OUT vector<Point2f>& nextPts, const InputArray& prevPts, CV_OUT InputOutputArray nextPts,
CV_OUT vector<uchar>& status, CV_OUT vector<float>& err, OutputArray status, OutputArray err,
Size winSize=Size(15,15), int maxLevel=3, Size winSize=Size(15,15), int maxLevel=3,
TermCriteria criteria=TermCriteria( TermCriteria criteria=TermCriteria(
TermCriteria::COUNT+TermCriteria::EPS, TermCriteria::COUNT+TermCriteria::EPS,
@ -326,10 +326,15 @@ CV_EXPORTS_W void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg,
int flags=0 ); int flags=0 );
//! computes dense optical flow using Farneback algorithm //! computes dense optical flow using Farneback algorithm
CV_EXPORTS_W void calcOpticalFlowFarneback( const Mat& prev, const Mat& next, CV_EXPORTS_W void calcOpticalFlowFarneback( const InputArray& prev, const InputArray& next,
CV_OUT Mat& flow, double pyr_scale, int levels, int winsize, CV_OUT InputOutputArray flow, double pyr_scale, int levels, int winsize,
int iterations, int poly_n, double poly_sigma, int flags ); int iterations, int poly_n, double poly_sigma, int flags );
//! estimates the best-fit Euqcidean, similarity, affine or perspective transformation
// that maps one 2D point set to another or one image to another.
CV_EXPORTS_W Mat estimateRigidTransform( const InputArray& src, const InputArray& dst,
bool fullAffine);
} }
#endif #endif

@ -59,7 +59,7 @@ namespace cv
{ {
BackgroundSubtractor::~BackgroundSubtractor() {} BackgroundSubtractor::~BackgroundSubtractor() {}
void BackgroundSubtractor::operator()(const Mat&, Mat&, double) void BackgroundSubtractor::operator()(const InputArray&, OutputArray, double)
{ {
} }
@ -381,15 +381,17 @@ static void process8uC3( BackgroundSubtractorMOG& obj, const Mat& image, Mat& fg
} }
} }
void BackgroundSubtractorMOG::operator()(const Mat& image, Mat& fgmask, double learningRate) void BackgroundSubtractorMOG::operator()(const InputArray& _image, OutputArray _fgmask, double learningRate)
{ {
Mat image = _image.getMat();
bool needToInitialize = nframes == 0 || learningRate >= 1 || image.size() != frameSize || image.type() != frameType; bool needToInitialize = nframes == 0 || learningRate >= 1 || image.size() != frameSize || image.type() != frameType;
if( needToInitialize ) if( needToInitialize )
initialize(image.size(), image.type()); initialize(image.size(), image.type());
CV_Assert( image.depth() == CV_8U ); CV_Assert( image.depth() == CV_8U );
fgmask.create( image.size(), CV_8U ); _fgmask.create( image.size(), CV_8U );
Mat fgmask = _fgmask.getMat();
++nframes; ++nframes;
learningRate = learningRate >= 0 && nframes > 1 ? learningRate : 1./min( nframes, history ); learningRate = learningRate >= 0 && nframes > 1 ? learningRate : 1./min( nframes, history );

File diff suppressed because it is too large Load Diff

@ -289,29 +289,25 @@ cvCamShift( const void* imgProb, CvRect windowIn,
return itersUsed; return itersUsed;
} }
namespace cv
{
RotatedRect CamShift( const Mat& probImage, Rect& window, cv::RotatedRect cv::CamShift( const InputArray& _probImage, Rect& window,
TermCriteria criteria ) TermCriteria criteria )
{ {
CvConnectedComp comp; CvConnectedComp comp;
CvBox2D box; CvBox2D box;
CvMat _probImage = probImage; CvMat c_probImage = _probImage.getMat();
cvCamShift(&_probImage, window, (CvTermCriteria)criteria, &comp, &box); cvCamShift(&c_probImage, window, (CvTermCriteria)criteria, &comp, &box);
window = comp.rect; window = comp.rect;
return RotatedRect(Point2f(box.center), Size2f(box.size), box.angle); return RotatedRect(Point2f(box.center), Size2f(box.size), box.angle);
} }
int meanShift( const Mat& probImage, Rect& window, TermCriteria criteria ) int cv::meanShift( const InputArray& _probImage, Rect& window, TermCriteria criteria )
{ {
CvConnectedComp comp; CvConnectedComp comp;
CvMat _probImage = probImage; CvMat c_probImage = _probImage.getMat();
int iters = cvMeanShift(&_probImage, window, (CvTermCriteria)criteria, &comp ); int iters = cvMeanShift(&c_probImage, window, (CvTermCriteria)criteria, &comp );
window = comp.rect; window = comp.rect;
return iters; return iters;
} }
}
/* End of file. */ /* End of file. */

@ -42,18 +42,15 @@
#include <float.h> #include <float.h>
#include <stdio.h> #include <stdio.h>
namespace cv void cv::calcOpticalFlowPyrLK( const InputArray& _prevImg, const InputArray& _nextImg,
{ const InputArray& _prevPts, InputOutputArray _nextPts,
OutputArray _status, OutputArray _err,
void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg,
const vector<Point2f>& prevPts,
vector<Point2f>& nextPts,
vector<uchar>& status, vector<float>& err,
Size winSize, int maxLevel, Size winSize, int maxLevel,
TermCriteria criteria, TermCriteria criteria,
double derivLambda, double derivLambda,
int flags ) int flags )
{ {
Mat prevImg = _prevImg.getMat(), nextImg = _nextImg.getMat(), prevPtsMat = _prevPts.getMat();
derivLambda = std::min(std::max(derivLambda, 0.), 1.); derivLambda = std::min(std::max(derivLambda, 0.), 1.);
double lambda1 = 1. - derivLambda, lambda2 = derivLambda; double lambda1 = 1. - derivLambda, lambda2 = derivLambda;
const int derivKernelSize = 3; const int derivKernelSize = 3;
@ -66,15 +63,33 @@ void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg,
CV_Assert( prevImg.size() == nextImg.size() && CV_Assert( prevImg.size() == nextImg.size() &&
prevImg.type() == nextImg.type() ); prevImg.type() == nextImg.type() );
size_t npoints = prevPts.size(); size_t npoints = prevPtsMat.total();
nextPts.resize(npoints);
status.resize(npoints);
for( size_t i = 0; i < npoints; i++ )
status[i] = true;
err.resize(npoints);
if( npoints == 0 ) if( npoints == 0 )
{
_nextPts.release();
_status.release();
_err.release();
return; return;
}
CV_Assert( prevPtsMat.isContinuous() );
const Point2f* prevPts = (const Point2f*)prevPtsMat.data;
_nextPts.create((int)npoints, 1, prevPtsMat.type(), -1, true);
Mat nextPtsMat = _nextPts.getMat();
CV_Assert( nextPtsMat.isContinuous() );
Point2f* nextPts = (Point2f*)nextPtsMat.data;
_status.create((int)npoints, 1, CV_8U, -1, true);
Mat statusMat = _status.getMat();
CV_Assert( statusMat.isContinuous() );
uchar* status = statusMat.data;
for( size_t i = 0; i < npoints; i++ )
status[i] = true;
_err.create((int)npoints, 1, CV_32F, -1, true);
Mat errMat = _err.getMat();
CV_Assert( errMat.isContinuous() );
float* err = (float*)errMat.data;
vector<Mat> prevPyr, nextPyr; vector<Mat> prevPyr, nextPyr;
@ -334,8 +349,6 @@ void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg,
} }
} }
}
static void static void
intersect( CvPoint2D32f pt, CvSize win_size, CvSize imgSize, intersect( CvPoint2D32f pt, CvSize win_size, CvSize imgSize,
CvPoint* min_pt, CvPoint* max_pt ) CvPoint* min_pt, CvPoint* max_pt )
@ -1852,18 +1865,14 @@ cvEstimateRigidTransform( const CvArr* matA, const CvArr* matB, CvMat* matM, int
return 1; return 1;
} }
namespace cv cv::Mat cv::estimateRigidTransform( const InputArray& A,
{ const InputArray& B,
Mat estimateRigidTransform( const Mat& A,
const Mat& B,
bool fullAffine ) bool fullAffine )
{ {
Mat M(2, 3, CV_64F); Mat M(2, 3, CV_64F);
CvMat matA = A, matB = B, matM = M; CvMat matA = A.getMat(), matB = B.getMat(), matM = M;
cvEstimateRigidTransform(&matA, &matB, &matM, fullAffine); cvEstimateRigidTransform(&matA, &matB, &matM, fullAffine);
return M; return M;
} }
}
/* End of file. */ /* End of file. */

@ -442,38 +442,40 @@ cvSegmentMotion( const CvArr* mhiimg, CvArr* segmask, CvMemStorage* storage,
} }
void cv::updateMotionHistory( const Mat& silhouette, Mat& mhi, void cv::updateMotionHistory( const InputArray& _silhouette, InputOutputArray _mhi,
double timestamp, double duration ) double timestamp, double duration )
{ {
CvMat _silhouette = silhouette, _mhi = mhi; CvMat c_silhouette = _silhouette.getMat(), c_mhi = _mhi.getMat();
cvUpdateMotionHistory( &_silhouette, &_mhi, timestamp, duration ); cvUpdateMotionHistory( &c_silhouette, &c_mhi, timestamp, duration );
} }
void cv::calcMotionGradient( const Mat& mhi, Mat& mask, void cv::calcMotionGradient( const InputArray& _mhi, OutputArray _mask,
Mat& orientation, OutputArray _orientation,
double delta1, double delta2, double delta1, double delta2,
int aperture_size ) int aperture_size )
{ {
mask.create(mhi.size(), CV_8U); Mat mhi = _mhi.getMat();
orientation.create(mhi.size(), CV_32F); _mask.create(mhi.size(), CV_8U);
CvMat _mhi = mhi, _mask = mask, _orientation = orientation; _orientation.create(mhi.size(), CV_32F);
cvCalcMotionGradient(&_mhi, &_mask, &_orientation, delta1, delta2, aperture_size); CvMat c_mhi = mhi, c_mask = _mask.getMat(), c_orientation = _orientation.getMat();
cvCalcMotionGradient(&c_mhi, &c_mask, &c_orientation, delta1, delta2, aperture_size);
} }
double cv::calcGlobalOrientation( const Mat& orientation, const Mat& mask, double cv::calcGlobalOrientation( const InputArray& _orientation, const InputArray& _mask,
const Mat& mhi, double timestamp, const InputArray& _mhi, double timestamp,
double duration ) double duration )
{ {
CvMat _orientation = orientation, _mask = mask, _mhi = mhi; CvMat c_orientation = _orientation.getMat(), c_mask = _mask.getMat(), c_mhi = _mhi.getMat();
return cvCalcGlobalOrientation(&_orientation, &_mask, &_mhi, timestamp, duration); return cvCalcGlobalOrientation(&c_orientation, &c_mask, &c_mhi, timestamp, duration);
} }
void cv::segmentMotion(const Mat& mhi, Mat& segmask, void cv::segmentMotion(const InputArray& _mhi, OutputArray _segmask,
vector<Rect>& boundingRects, vector<Rect>& boundingRects,
double timestamp, double segThresh) double timestamp, double segThresh)
{ {
segmask.create(mhi.size(), CV_32F); Mat mhi = _mhi.getMat();
CvMat c_mhi = mhi, c_segmask = segmask; _segmask.create(mhi.size(), CV_32F);
CvMat c_mhi = mhi, c_segmask = _segmask.getMat();
Ptr<CvMemStorage> storage = cvCreateMemStorage(); Ptr<CvMemStorage> storage = cvCreateMemStorage();
Seq<CvConnectedComp> comps = cvSegmentMotion(&c_mhi, &c_segmask, storage, timestamp, segThresh); Seq<CvConnectedComp> comps = cvSegmentMotion(&c_mhi, &c_segmask, storage, timestamp, segThresh);
Seq<CvConnectedComp>::const_iterator it(comps); Seq<CvConnectedComp>::const_iterator it(comps);

@ -561,22 +561,24 @@ FarnebackUpdateFlow_GaussianBlur( const Mat& _R0, const Mat& _R1,
} }
} }
}
void calcOpticalFlowFarneback( const Mat& prev0, const Mat& next0, void cv::calcOpticalFlowFarneback( const InputArray& _prev0, const InputArray& _next0,
Mat& flow0, double pyr_scale, int levels, int winsize, OutputArray _flow0, double pyr_scale, int levels, int winsize,
int iterations, int poly_n, double poly_sigma, int flags ) int iterations, int poly_n, double poly_sigma, int flags )
{ {
Mat prev0 = _prev0.getMat(), next0 = _next0.getMat();
const int min_size = 32; const int min_size = 32;
const Mat* img[2] = { &prev0, &next0 }; const Mat* img[2] = { &prev0, &next0 };
Mat fimg;
int i, k; int i, k;
double scale; double scale;
Mat prevFlow, flow; Mat prevFlow, flow, fimg;
CV_Assert( prev0.size() == next0.size() && prev0.channels() == next0.channels() && CV_Assert( prev0.size() == next0.size() && prev0.channels() == next0.channels() &&
prev0.channels() == 1 && pyr_scale < 1 ); prev0.channels() == 1 && pyr_scale < 1 );
flow0.create( prev0.size(), CV_32FC2 ); _flow0.create( prev0.size(), CV_32FC2 );
Mat flow0 = _flow0.getMat();
for( k = 0, scale = 1; k < levels; k++ ) for( k = 0, scale = 1; k < levels; k++ )
{ {
@ -643,7 +645,6 @@ void calcOpticalFlowFarneback( const Mat& prev0, const Mat& next0,
} }
} }
}
CV_IMPL void cvCalcOpticalFlowFarneback( CV_IMPL void cvCalcOpticalFlowFarneback(
const CvArr* _prev, const CvArr* _next, const CvArr* _prev, const CvArr* _next,

@ -169,12 +169,15 @@ double CV_UpdateMHITest::get_success_error_level( int /*test_case_idx*/, int /*i
void CV_UpdateMHITest::run_func() void CV_UpdateMHITest::run_func()
{ {
cvUpdateMotionHistory( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], timestamp, duration ); CvMat m = test_mat[INPUT_OUTPUT][0];
cv::updateMotionHistory( test_mat[INPUT][0], test_mat[INPUT_OUTPUT][0], timestamp, duration);
m = test_mat[INPUT_OUTPUT][0];
} }
void CV_UpdateMHITest::prepare_to_validation( int /*test_case_idx*/ ) void CV_UpdateMHITest::prepare_to_validation( int /*test_case_idx*/ )
{ {
CvMat m0 = test_mat[REF_INPUT_OUTPUT][0];
test_updateMHI( test_mat[INPUT][0], test_mat[REF_INPUT_OUTPUT][0], timestamp, duration ); test_updateMHI( test_mat[INPUT][0], test_mat[REF_INPUT_OUTPUT][0], timestamp, duration );
} }
@ -290,8 +293,10 @@ double CV_MHIGradientTest::get_success_error_level( int /*test_case_idx*/, int /
void CV_MHIGradientTest::run_func() void CV_MHIGradientTest::run_func()
{ {
cvCalcMotionGradient( test_array[INPUT][0], test_array[OUTPUT][0], cv::calcMotionGradient(test_mat[INPUT][0], test_mat[OUTPUT][0],
test_array[OUTPUT][1], delta1, delta2, aperture_size ); test_mat[OUTPUT][1], delta1, delta2, aperture_size );
//cvCalcMotionGradient( test_array[INPUT][0], test_array[OUTPUT][0],
// test_array[OUTPUT][1], delta1, delta2, aperture_size );
} }
@ -453,8 +458,10 @@ double CV_MHIGlobalOrientTest::get_success_error_level( int /*test_case_idx*/, i
void CV_MHIGlobalOrientTest::run_func() void CV_MHIGlobalOrientTest::run_func()
{ {
angle = cvCalcGlobalOrientation( test_array[INPUT][2], test_array[INPUT][1], //angle = cvCalcGlobalOrientation( test_array[INPUT][2], test_array[INPUT][1],
test_array[INPUT][0], timestamp, duration ); // test_array[INPUT][0], timestamp, duration );
angle = cv::calcGlobalOrientation(test_mat[INPUT][2], test_mat[INPUT][1],
test_mat[INPUT][0], timestamp, duration );
} }

Loading…
Cancel
Save