diff --git a/apps/traincascade/boost.cpp b/apps/traincascade/boost.cpp index 29ac4bc9af..732704a4a2 100644 --- a/apps/traincascade/boost.cpp +++ b/apps/traincascade/boost.cpp @@ -957,7 +957,7 @@ void CvCascadeBoostTree::write( FileStorage &fs, const Mat& featureMap ) int subsetN = (maxCatCount + 31)/32; queue internalNodesQueue; int size = (int)pow( 2.f, (float)ensemble->get_params().max_depth); - Ptr leafVals = new float[size]; + std::vector leafVals(size); int leafValIdx = 0; int internalNodeIdx = 1; CvDTreeNode* tempNode; diff --git a/apps/traincascade/cascadeclassifier.cpp b/apps/traincascade/cascadeclassifier.cpp index 3983a614fd..5c96b45f76 100644 --- a/apps/traincascade/cascadeclassifier.cpp +++ b/apps/traincascade/cascadeclassifier.cpp @@ -159,10 +159,10 @@ bool CvCascadeClassifier::train( const string _cascadeDirName, cascadeParams = _cascadeParams; featureParams = CvFeatureParams::create(cascadeParams.featureType); featureParams->init(_featureParams); - stageParams = new CvCascadeBoostParams; + stageParams = makePtr(); *stageParams = _stageParams; featureEvaluator = CvFeatureEvaluator::create(cascadeParams.featureType); - featureEvaluator->init( (CvFeatureParams*)featureParams, numPos + numNeg, cascadeParams.winSize ); + featureEvaluator->init( featureParams, numPos + numNeg, cascadeParams.winSize ); stageClassifiers.reserve( numStages ); } cout << "PARAMETERS:" << endl; @@ -206,10 +206,10 @@ bool CvCascadeClassifier::train( const string _cascadeDirName, break; } - CvCascadeBoost* tempStage = new CvCascadeBoost; - bool isStageTrained = tempStage->train( (CvFeatureEvaluator*)featureEvaluator, + Ptr tempStage = makePtr(); + bool isStageTrained = tempStage->train( featureEvaluator, curNumSamples, _precalcValBufSize, _precalcIdxBufSize, - *((CvCascadeBoostParams*)stageParams) ); + *stageParams ); cout << "END>" << endl; if(!isStageTrained) @@ -325,7 +325,7 @@ void CvCascadeClassifier::writeParams( FileStorage &fs ) const void CvCascadeClassifier::writeFeatures( FileStorage &fs, const Mat& featureMap ) const { - ((CvFeatureEvaluator*)((Ptr)featureEvaluator))->writeFeatures( fs, featureMap ); + featureEvaluator->writeFeatures( fs, featureMap ); } void CvCascadeClassifier::writeStages( FileStorage &fs, const Mat& featureMap ) const @@ -339,7 +339,7 @@ void CvCascadeClassifier::writeStages( FileStorage &fs, const Mat& featureMap ) sprintf( cmnt, "stage %d", i ); cvWriteComment( fs.fs, cmnt, 0 ); fs << "{"; - ((CvCascadeBoost*)((Ptr)*it))->write( fs, featureMap ); + (*it)->write( fs, featureMap ); fs << "}"; } fs << "]"; @@ -350,7 +350,7 @@ bool CvCascadeClassifier::readParams( const FileNode &node ) if ( !node.isMap() || !cascadeParams.read( node ) ) return false; - stageParams = new CvCascadeBoostParams; + stageParams = makePtr(); FileNode rnode = node[CC_STAGE_PARAMS]; if ( !stageParams->read( rnode ) ) return false; @@ -371,12 +371,9 @@ bool CvCascadeClassifier::readStages( const FileNode &node) FileNodeIterator it = rnode.begin(); for( int i = 0; i < min( (int)rnode.size(), numStages ); i++, it++ ) { - CvCascadeBoost* tempStage = new CvCascadeBoost; - if ( !tempStage->read( *it, (CvFeatureEvaluator *)featureEvaluator, *((CvCascadeBoostParams*)stageParams) ) ) - { - delete tempStage; + Ptr tempStage = makePtr(); + if ( !tempStage->read( *it, featureEvaluator, *stageParams) ) return false; - } stageClassifiers.push_back(tempStage); } return true; @@ -453,7 +450,7 @@ void CvCascadeClassifier::save( const string filename, bool baseFormat ) fs << "{"; fs << ICV_HAAR_FEATURE_NAME << "{"; - ((CvHaarEvaluator*)((CvFeatureEvaluator*)featureEvaluator))->writeFeature( fs, tempNode->split->var_idx ); + ((CvHaarEvaluator*)featureEvaluator.get())->writeFeature( fs, tempNode->split->var_idx ); fs << "}"; fs << ICV_HAAR_THRESHOLD_NAME << tempNode->split->ord.c; @@ -499,7 +496,7 @@ bool CvCascadeClassifier::load( const string cascadeDirName ) if ( !readParams( node ) ) return false; featureEvaluator = CvFeatureEvaluator::create(cascadeParams.featureType); - featureEvaluator->init( ((CvFeatureParams*)featureParams), numPos + numNeg, cascadeParams.winSize ); + featureEvaluator->init( featureParams, numPos + numNeg, cascadeParams.winSize ); fs.release(); char buf[10]; @@ -510,11 +507,10 @@ bool CvCascadeClassifier::load( const string cascadeDirName ) node = fs.getFirstTopLevelNode(); if ( !fs.isOpened() ) break; - CvCascadeBoost *tempStage = new CvCascadeBoost; + Ptr tempStage = makePtr(); - if ( !tempStage->read( node, (CvFeatureEvaluator*)featureEvaluator, *((CvCascadeBoostParams*)stageParams )) ) + if ( !tempStage->read( node, featureEvaluator, *stageParams )) { - delete tempStage; fs.release(); break; } @@ -531,7 +527,7 @@ void CvCascadeClassifier::getUsedFeaturesIdxMap( Mat& featureMap ) for( vector< Ptr >::const_iterator it = stageClassifiers.begin(); it != stageClassifiers.end(); it++ ) - ((CvCascadeBoost*)((Ptr)(*it)))->markUsedFeaturesInMap( featureMap ); + (*it)->markUsedFeaturesInMap( featureMap ); for( int fi = 0, idx = 0; fi < varCount; fi++ ) if ( featureMap.at(0, fi) >= 0 ) diff --git a/apps/traincascade/traincascade.cpp b/apps/traincascade/traincascade.cpp index 7b8fcddd84..a896c216c9 100644 --- a/apps/traincascade/traincascade.cpp +++ b/apps/traincascade/traincascade.cpp @@ -18,9 +18,9 @@ int main( int argc, char* argv[] ) CvCascadeParams cascadeParams; CvCascadeBoostParams stageParams; - Ptr featureParams[] = { Ptr(new CvHaarFeatureParams), - Ptr(new CvLBPFeatureParams), - Ptr(new CvHOGFeatureParams) + Ptr featureParams[] = { makePtr(), + makePtr(), + makePtr() }; int fc = sizeof(featureParams)/sizeof(featureParams[0]); if( argc == 1 ) diff --git a/modules/bioinspired/src/opencl/retina_kernel.cl b/modules/bioinspired/src/opencl/retina_kernel.cl index 6da4219d9c..1eac50324a 100644 --- a/modules/bioinspired/src/opencl/retina_kernel.cl +++ b/modules/bioinspired/src/opencl/retina_kernel.cl @@ -114,19 +114,34 @@ kernel void horizontalAnticausalFilter( global float * optr = output + mad24(gid + 1, elements_per_row, - 1 + out_offset / 4); - float4 result = (float4)(0), out_v4; + float4 result_v4 = (float4)(0), out_v4; + float result = 0; // we assume elements_per_row is multple of 4 - for(int i = 0; i < elements_per_row / 4; ++i, optr -= 4) + for(int i = 0; i < 4; ++ i, -- optr) + { + if(i < elements_per_row - cols) + { + *optr = result; + } + else + { + result = *optr + _a * result; + *optr = result; + } + } + result_v4.x = result; + optr -= 3; + for(int i = 1; i < elements_per_row / 4; ++i, optr -= 4) { // shift left, `offset` is type `size_t` so it cannot be negative - out_v4 = vload4(0, optr - 3); + out_v4 = vload4(0, optr); - result.w = out_v4.w + _a * result.x; - result.z = out_v4.z + _a * result.w; - result.y = out_v4.y + _a * result.z; - result.x = out_v4.x + _a * result.y; + result_v4.w = out_v4.w + _a * result_v4.x; + result_v4.z = out_v4.z + _a * result_v4.w; + result_v4.y = out_v4.y + _a * result_v4.z; + result_v4.x = out_v4.x + _a * result_v4.y; - vstore4(result, 0, optr - 3); + vstore4(result_v4, 0, optr); } } @@ -207,18 +222,34 @@ kernel void horizontalAnticausalFilter_Irregular( buffer + mad24(rows - gid, elements_per_row, -1 + buffer_offset / 4); float4 buf_v4, out_v4, res_v4 = (float4)(0); - - for(int i = 0; i < elements_per_row / 4; ++i, optr -= 4, bptr -= 4) + float result = 0; + // we assume elements_per_row is multple of 4 + for(int i = 0; i < 4; ++ i, -- optr, -- bptr) { - buf_v4 = vload4(0, bptr - 3); - out_v4 = vload4(0, optr - 3); + if(i < elements_per_row - cols) + { + *optr = result; + } + else + { + result = *optr + *bptr * result; + *optr = result; + } + } + res_v4.x = result; + optr -= 3; + bptr -= 3; + for(int i = 0; i < elements_per_row / 4 - 1; ++i, optr -= 4, bptr -= 4) + { + buf_v4 = vload4(0, bptr); + out_v4 = vload4(0, optr); res_v4.w = out_v4.w + buf_v4.w * res_v4.x; res_v4.z = out_v4.z + buf_v4.z * res_v4.w; res_v4.y = out_v4.y + buf_v4.y * res_v4.z; res_v4.x = out_v4.x + buf_v4.x * res_v4.y; - vstore4(res_v4, 0, optr - 3); + vstore4(res_v4, 0, optr); } } diff --git a/modules/bioinspired/src/retina.cpp b/modules/bioinspired/src/retina.cpp index 75e4b841ff..4604331076 100644 --- a/modules/bioinspired/src/retina.cpp +++ b/modules/bioinspired/src/retina.cpp @@ -295,8 +295,10 @@ private: }; // smart pointers allocation : -Ptr createRetina(Size inputSize){ return new RetinaImpl(inputSize); } -Ptr createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght){return new RetinaImpl(inputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);} +Ptr createRetina(Size inputSize){ return makePtr(inputSize); } +Ptr createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght){ + return makePtr(inputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght); +} // RetinaImpl code diff --git a/modules/bioinspired/src/retina_ocl.cpp b/modules/bioinspired/src/retina_ocl.cpp index 8f1f2694ef..41169561fb 100644 --- a/modules/bioinspired/src/retina_ocl.cpp +++ b/modules/bioinspired/src/retina_ocl.cpp @@ -1149,7 +1149,7 @@ void RetinaColor::_initColorSampling() // computing photoreceptors local density MAKE_OCLMAT_SLICES(_RGBmosaic, 3); MAKE_OCLMAT_SLICES(_colorLocalDensity, 3); - + _colorLocalDensity.setTo(0); _spatiotemporalLPfilter(_RGBmosaic_slices[0], _colorLocalDensity_slices[0]); _spatiotemporalLPfilter(_RGBmosaic_slices[1], _colorLocalDensity_slices[1]); _spatiotemporalLPfilter(_RGBmosaic_slices[2], _colorLocalDensity_slices[2]); @@ -1639,10 +1639,10 @@ void RetinaFilter::_processRetinaParvoMagnoMapping() } } /* namespace ocl */ -Ptr createRetina_OCL(Size getInputSize){ return new ocl::RetinaOCLImpl(getInputSize); } +Ptr createRetina_OCL(Size getInputSize){ return makePtr(getInputSize); } Ptr createRetina_OCL(Size getInputSize, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) { - return new ocl::RetinaOCLImpl(getInputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght); + return makePtr(getInputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght); } } /* namespace bioinspired */ diff --git a/modules/bioinspired/src/retinafasttonemapping.cpp b/modules/bioinspired/src/retinafasttonemapping.cpp index 468bedb9a1..2713d7449c 100644 --- a/modules/bioinspired/src/retinafasttonemapping.cpp +++ b/modules/bioinspired/src/retinafasttonemapping.cpp @@ -114,9 +114,9 @@ public: _imageOutput.resize(nbPixels*3); _temp2.resize(nbPixels); // allocate the main filter with 2 setup sets properties (one for each low pass filter - _multiuseFilter = new BasicRetinaFilter(imageInput.height, imageInput.width, 2); + _multiuseFilter = makePtr(imageInput.height, imageInput.width, 2); // allocate the color manager (multiplexer/demultiplexer - _colorEngine = new RetinaColor(imageInput.height, imageInput.width); + _colorEngine = makePtr(imageInput.height, imageInput.width); // setup filter behaviors with default values setup(); } @@ -309,7 +309,7 @@ bool _convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray &out CV_EXPORTS Ptr createRetinaFastToneMapping(Size inputSize) { - return new RetinaFastToneMappingImpl(inputSize); + return makePtr(inputSize); } }// end of namespace bioinspired diff --git a/modules/bioinspired/test/test_retina_ocl.cpp b/modules/bioinspired/test/test_retina_ocl.cpp index a732d7e37e..b09ce50366 100644 --- a/modules/bioinspired/test/test_retina_ocl.cpp +++ b/modules/bioinspired/test/test_retina_ocl.cpp @@ -49,7 +49,7 @@ #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" -#if defined(HAVE_OPENCV_OCL) && defined(HAVE_OPENCL) +#if defined(HAVE_OPENCV_OCL) #include "opencv2/ocl.hpp" #define RETINA_ITERATIONS 5 diff --git a/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst b/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst index 30f3102a7f..cb30dc36d5 100644 --- a/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst +++ b/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst @@ -515,7 +515,7 @@ findCirclesGrid ------------------- Finds centers in the grid of circles. -.. ocv:function:: bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, const Ptr &blobDetector = new SimpleBlobDetector() ) +.. ocv:function:: bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, const Ptr &blobDetector = makePtr() ) .. ocv:pyfunction:: cv2.findCirclesGrid(image, patternSize[, centers[, flags[, blobDetector]]]) -> retval, centers diff --git a/modules/calib3d/include/opencv2/calib3d.hpp b/modules/calib3d/include/opencv2/calib3d.hpp index 2486eb19a8..f5ccb54a71 100644 --- a/modules/calib3d/include/opencv2/calib3d.hpp +++ b/modules/calib3d/include/opencv2/calib3d.hpp @@ -180,7 +180,7 @@ CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSiz //! finds circles' grid pattern of the specified size in the image CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, - const Ptr &blobDetector = new SimpleBlobDetector()); + const Ptr &blobDetector = makePtr()); //! finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern. CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, diff --git a/modules/calib3d/perf/perf_pnp.cpp b/modules/calib3d/perf/perf_pnp.cpp index e881557298..7a7acb052d 100644 --- a/modules/calib3d/perf/perf_pnp.cpp +++ b/modules/calib3d/perf/perf_pnp.cpp @@ -130,7 +130,7 @@ PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(4, 3*9, 7*13)) #ifdef HAVE_TBB // limit concurrency to get determenistic result - cv::Ptr one_thread = new tbb::task_scheduler_init(1); + tbb::task_scheduler_init one_thread(1); #endif TEST_CYCLE() diff --git a/modules/calib3d/src/calibinit.cpp b/modules/calib3d/src/calibinit.cpp index b93b4951ed..844fde4999 100644 --- a/modules/calib3d/src/calibinit.cpp +++ b/modules/calib3d/src/calibinit.cpp @@ -271,8 +271,8 @@ int cvFindChessboardCorners( const void* arr, CvSize pattern_size, if( !out_corners ) CV_Error( CV_StsNullPtr, "Null pointer to corners" ); - storage = cvCreateMemStorage(0); - thresh_img = cvCreateMat( img->rows, img->cols, CV_8UC1 ); + storage.reset(cvCreateMemStorage(0)); + thresh_img.reset(cvCreateMat( img->rows, img->cols, CV_8UC1 )); #ifdef DEBUG_CHESSBOARD dbg_img = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3 ); @@ -284,7 +284,7 @@ int cvFindChessboardCorners( const void* arr, CvSize pattern_size, { // equalize the input image histogram - // that should make the contrast between "black" and "white" areas big enough - norm_img = cvCreateMat( img->rows, img->cols, CV_8UC1 ); + norm_img.reset(cvCreateMat( img->rows, img->cols, CV_8UC1 )); if( CV_MAT_CN(img->type) != 1 ) { @@ -541,12 +541,12 @@ int cvFindChessboardCorners( const void* arr, CvSize pattern_size, cv::Ptr gray; if( CV_MAT_CN(img->type) != 1 ) { - gray = cvCreateMat(img->rows, img->cols, CV_8UC1); + gray.reset(cvCreateMat(img->rows, img->cols, CV_8UC1)); cvCvtColor(img, gray, CV_BGR2GRAY); } else { - gray = cvCloneMat(img); + gray.reset(cvCloneMat(img)); } int wsize = 2; cvFindCornerSubPix( gray, out_corners, pattern_size.width*pattern_size.height, @@ -627,7 +627,7 @@ icvOrderFoundConnectedQuads( int quad_count, CvCBQuad **quads, int *all_count, CvCBQuad **all_quads, CvCBCorner **corners, CvSize pattern_size, CvMemStorage* storage ) { - cv::Ptr temp_storage = cvCreateChildMemStorage( storage ); + cv::Ptr temp_storage(cvCreateChildMemStorage( storage )); CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage ); // first find an interior quad @@ -1109,7 +1109,7 @@ icvCleanFoundConnectedQuads( int quad_count, CvCBQuad **quad_group, CvSize patte // create an array of quadrangle centers cv::AutoBuffer centers( quad_count ); - cv::Ptr temp_storage = cvCreateMemStorage(0); + cv::Ptr temp_storage(cvCreateMemStorage(0)); for( i = 0; i < quad_count; i++ ) { @@ -1205,7 +1205,7 @@ static int icvFindConnectedQuads( CvCBQuad *quad, int quad_count, CvCBQuad **out_group, int group_idx, CvMemStorage* storage ) { - cv::Ptr temp_storage = cvCreateChildMemStorage( storage ); + cv::Ptr temp_storage(cvCreateChildMemStorage( storage )); CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage ); int i, count = 0; @@ -1674,7 +1674,7 @@ icvGenerateQuads( CvCBQuad **out_quads, CvCBCorner **out_corners, min_size = 25; //cvRound( image->cols * image->rows * .03 * 0.01 * 0.92 ); // create temporary storage for contours and the sequence of pointers to found quadrangles - temp_storage = cvCreateChildMemStorage( storage ); + temp_storage.reset(cvCreateChildMemStorage( storage )); root = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvSeq*), temp_storage ); // initialize contour retrieving routine diff --git a/modules/calib3d/src/calibration.cpp b/modules/calib3d/src/calibration.cpp index bb78635752..132220d404 100644 --- a/modules/calib3d/src/calibration.cpp +++ b/modules/calib3d/src/calibration.cpp @@ -568,7 +568,7 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, (objectPoints->rows == count && CV_MAT_CN(objectPoints->type)*objectPoints->cols == 3) || (objectPoints->rows == 3 && CV_MAT_CN(objectPoints->type) == 1 && objectPoints->cols == count))) { - matM = cvCreateMat( objectPoints->rows, objectPoints->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(objectPoints->type)) ); + matM.reset(cvCreateMat( objectPoints->rows, objectPoints->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(objectPoints->type)) )); cvConvert(objectPoints, matM); } else @@ -584,7 +584,7 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, (imagePoints->rows == count && CV_MAT_CN(imagePoints->type)*imagePoints->cols == 2) || (imagePoints->rows == 2 && CV_MAT_CN(imagePoints->type) == 1 && imagePoints->cols == count))) { - _m = cvCreateMat( imagePoints->rows, imagePoints->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(imagePoints->type)) ); + _m.reset(cvCreateMat( imagePoints->rows, imagePoints->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(imagePoints->type)) )); cvConvert(imagePoints, _m); } else @@ -664,10 +664,10 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, if( CV_MAT_TYPE(dpdr->type) == CV_64FC1 ) { - _dpdr = cvCloneMat(dpdr); + _dpdr.reset(cvCloneMat(dpdr)); } else - _dpdr = cvCreateMat( 2*count, 3, CV_64FC1 ); + _dpdr.reset(cvCreateMat( 2*count, 3, CV_64FC1 )); dpdr_p = _dpdr->data.db; dpdr_step = _dpdr->step/sizeof(dpdr_p[0]); } @@ -682,10 +682,10 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, if( CV_MAT_TYPE(dpdt->type) == CV_64FC1 ) { - _dpdt = cvCloneMat(dpdt); + _dpdt.reset(cvCloneMat(dpdt)); } else - _dpdt = cvCreateMat( 2*count, 3, CV_64FC1 ); + _dpdt.reset(cvCreateMat( 2*count, 3, CV_64FC1 )); dpdt_p = _dpdt->data.db; dpdt_step = _dpdt->step/sizeof(dpdt_p[0]); } @@ -699,10 +699,10 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, if( CV_MAT_TYPE(dpdf->type) == CV_64FC1 ) { - _dpdf = cvCloneMat(dpdf); + _dpdf.reset(cvCloneMat(dpdf)); } else - _dpdf = cvCreateMat( 2*count, 2, CV_64FC1 ); + _dpdf.reset(cvCreateMat( 2*count, 2, CV_64FC1 )); dpdf_p = _dpdf->data.db; dpdf_step = _dpdf->step/sizeof(dpdf_p[0]); } @@ -716,10 +716,10 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, if( CV_MAT_TYPE(dpdc->type) == CV_64FC1 ) { - _dpdc = cvCloneMat(dpdc); + _dpdc.reset(cvCloneMat(dpdc)); } else - _dpdc = cvCreateMat( 2*count, 2, CV_64FC1 ); + _dpdc.reset(cvCreateMat( 2*count, 2, CV_64FC1 )); dpdc_p = _dpdc->data.db; dpdc_step = _dpdc->step/sizeof(dpdc_p[0]); } @@ -736,10 +736,10 @@ CV_IMPL void cvProjectPoints2( const CvMat* objectPoints, if( CV_MAT_TYPE(dpdk->type) == CV_64FC1 ) { - _dpdk = cvCloneMat(dpdk); + _dpdk.reset(cvCloneMat(dpdk)); } else - _dpdk = cvCreateMat( dpdk->rows, dpdk->cols, CV_64FC1 ); + _dpdk.reset(cvCreateMat( dpdk->rows, dpdk->cols, CV_64FC1 )); dpdk_p = _dpdk->data.db; dpdk_step = _dpdk->step/sizeof(dpdk_p[0]); } @@ -950,8 +950,8 @@ CV_IMPL void cvFindExtrinsicCameraParams2( const CvMat* objectPoints, CV_IS_MAT(A) && CV_IS_MAT(rvec) && CV_IS_MAT(tvec) ); count = MAX(objectPoints->cols, objectPoints->rows); - matM = cvCreateMat( 1, count, CV_64FC3 ); - _m = cvCreateMat( 1, count, CV_64FC2 ); + matM.reset(cvCreateMat( 1, count, CV_64FC3 )); + _m.reset(cvCreateMat( 1, count, CV_64FC2 )); cvConvertPointsHomogeneous( objectPoints, matM ); cvConvertPointsHomogeneous( imagePoints, _m ); @@ -963,8 +963,8 @@ CV_IMPL void cvFindExtrinsicCameraParams2( const CvMat* objectPoints, CV_Assert( (CV_MAT_DEPTH(tvec->type) == CV_64F || CV_MAT_DEPTH(tvec->type) == CV_32F) && (tvec->rows == 1 || tvec->cols == 1) && tvec->rows*tvec->cols*CV_MAT_CN(tvec->type) == 3 ); - _mn = cvCreateMat( 1, count, CV_64FC2 ); - _Mxy = cvCreateMat( 1, count, CV_64FC2 ); + _mn.reset(cvCreateMat( 1, count, CV_64FC2 )); + _Mxy.reset(cvCreateMat( 1, count, CV_64FC2 )); // normalize image points // (unapply the intrinsic matrix transformation and distortion) @@ -1055,7 +1055,7 @@ CV_IMPL void cvFindExtrinsicCameraParams2( const CvMat* objectPoints, CvPoint3D64f* M = (CvPoint3D64f*)matM->data.db; CvPoint2D64f* mn = (CvPoint2D64f*)_mn->data.db; - matL = cvCreateMat( 2*count, 12, CV_64F ); + matL.reset(cvCreateMat( 2*count, 12, CV_64F )); L = matL->data.db; for( i = 0; i < count; i++, L += 24 ) @@ -1162,11 +1162,11 @@ CV_IMPL void cvInitIntrinsicParams2D( const CvMat* objectPoints, if( objectPoints->rows != 1 || imagePoints->rows != 1 ) CV_Error( CV_StsBadSize, "object points and image points must be a single-row matrices" ); - matA = cvCreateMat( 2*nimages, 2, CV_64F ); - _b = cvCreateMat( 2*nimages, 1, CV_64F ); + matA.reset(cvCreateMat( 2*nimages, 2, CV_64F )); + _b.reset(cvCreateMat( 2*nimages, 1, CV_64F )); a[2] = (imageSize.width - 1)*0.5; a[5] = (imageSize.height - 1)*0.5; - _allH = cvCreateMat( nimages, 9, CV_64F ); + _allH.reset(cvCreateMat( nimages, 9, CV_64F )); // extract vanishing points in order to obtain initial value for the focal length for( i = 0, pos = 0; i < nimages; i++, pos += ni ) @@ -1310,16 +1310,16 @@ CV_IMPL double cvCalibrateCamera2( const CvMat* objectPoints, total += ni; } - matM = cvCreateMat( 1, total, CV_64FC3 ); - _m = cvCreateMat( 1, total, CV_64FC2 ); + matM.reset(cvCreateMat( 1, total, CV_64FC3 )); + _m.reset(cvCreateMat( 1, total, CV_64FC2 )); cvConvertPointsHomogeneous( objectPoints, matM ); cvConvertPointsHomogeneous( imagePoints, _m ); nparams = NINTRINSIC + nimages*6; - _Ji = cvCreateMat( maxPoints*2, NINTRINSIC, CV_64FC1 ); - _Je = cvCreateMat( maxPoints*2, 6, CV_64FC1 ); - _err = cvCreateMat( maxPoints*2, 1, CV_64FC1 ); + _Ji.reset(cvCreateMat( maxPoints*2, NINTRINSIC, CV_64FC1 )); + _Je.reset(cvCreateMat( maxPoints*2, 6, CV_64FC1 )); + _err.reset(cvCreateMat( maxPoints*2, 1, CV_64FC1 )); cvZero( _Ji ); _k = cvMat( distCoeffs->rows, distCoeffs->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(distCoeffs->type)), k); @@ -1662,7 +1662,7 @@ double cvStereoCalibrate( const CvMat* _objectPoints, const CvMat* _imagePoints1 CV_MAT_TYPE(_npoints->type) == CV_32SC1 ); nimages = _npoints->cols + _npoints->rows - 1; - npoints = cvCreateMat( _npoints->rows, _npoints->cols, _npoints->type ); + npoints.reset(cvCreateMat( _npoints->rows, _npoints->cols, _npoints->type )); cvCopy( _npoints, npoints ); for( i = 0, pointsTotal = 0; i < nimages; i++ ) @@ -1671,8 +1671,8 @@ double cvStereoCalibrate( const CvMat* _objectPoints, const CvMat* _imagePoints1 pointsTotal += npoints->data.i[i]; } - objectPoints = cvCreateMat( _objectPoints->rows, _objectPoints->cols, - CV_64FC(CV_MAT_CN(_objectPoints->type))); + objectPoints.reset(cvCreateMat( _objectPoints->rows, _objectPoints->cols, + CV_64FC(CV_MAT_CN(_objectPoints->type)))); cvConvert( _objectPoints, objectPoints ); cvReshape( objectPoints, objectPoints, 3, 1 ); @@ -1691,7 +1691,7 @@ double cvStereoCalibrate( const CvMat* _objectPoints, const CvMat* _imagePoints1 K[k] = cvMat(3,3,CV_64F,A[k]); Dist[k] = cvMat(1,8,CV_64F,dk[k]); - imagePoints[k] = cvCreateMat( points->rows, points->cols, CV_64FC(CV_MAT_CN(points->type))); + imagePoints[k].reset(cvCreateMat( points->rows, points->cols, CV_64FC(CV_MAT_CN(points->type)))); cvConvert( points, imagePoints[k] ); cvReshape( imagePoints[k], imagePoints[k], 2, 1 ); @@ -1729,10 +1729,10 @@ double cvStereoCalibrate( const CvMat* _objectPoints, const CvMat* _imagePoints1 recomputeIntrinsics = (flags & CV_CALIB_FIX_INTRINSIC) == 0; - err = cvCreateMat( maxPoints*2, 1, CV_64F ); - Je = cvCreateMat( maxPoints*2, 6, CV_64F ); - J_LR = cvCreateMat( maxPoints*2, 6, CV_64F ); - Ji = cvCreateMat( maxPoints*2, NINTRINSIC, CV_64F ); + err.reset(cvCreateMat( maxPoints*2, 1, CV_64F )); + Je.reset(cvCreateMat( maxPoints*2, 6, CV_64F )); + J_LR.reset(cvCreateMat( maxPoints*2, 6, CV_64F )); + Ji.reset(cvCreateMat( maxPoints*2, NINTRINSIC, CV_64F )); cvZero( Ji ); // we optimize for the inter-camera R(3),t(3), then, optionally, @@ -1740,7 +1740,7 @@ double cvStereoCalibrate( const CvMat* _objectPoints, const CvMat* _imagePoints1 nparams = 6*(nimages+1) + (recomputeIntrinsics ? NINTRINSIC*2 : 0); // storage for initial [om(R){i}|t{i}] (in order to compute the median for each component) - RT0 = cvCreateMat( 6, nimages, CV_64F ); + RT0.reset(cvCreateMat( 6, nimages, CV_64F )); solver.init( nparams, 0, termCrit ); if( recomputeIntrinsics ) @@ -2080,7 +2080,7 @@ icvGetRectangles( const CvMat* cameraMatrix, const CvMat* distCoeffs, { const int N = 9; int x, y, k; - cv::Ptr _pts = cvCreateMat(1, N*N, CV_32FC2); + cv::Ptr _pts(cvCreateMat(1, N*N, CV_32FC2)); CvPoint2D32f* pts = (CvPoint2D32f*)(_pts->data.ptr); for( y = k = 0; y < N; y++ ) @@ -2439,10 +2439,10 @@ CV_IMPL int cvStereoRectifyUncalibrated( npoints = _points1->rows * _points1->cols * CV_MAT_CN(_points1->type) / 2; - _m1 = cvCreateMat( _points1->rows, _points1->cols, CV_64FC(CV_MAT_CN(_points1->type)) ); - _m2 = cvCreateMat( _points2->rows, _points2->cols, CV_64FC(CV_MAT_CN(_points2->type)) ); - _lines1 = cvCreateMat( 1, npoints, CV_64FC3 ); - _lines2 = cvCreateMat( 1, npoints, CV_64FC3 ); + _m1.reset(cvCreateMat( _points1->rows, _points1->cols, CV_64FC(CV_MAT_CN(_points1->type)) )); + _m2.reset(cvCreateMat( _points2->rows, _points2->cols, CV_64FC(CV_MAT_CN(_points2->type)) )); + _lines1.reset(cvCreateMat( 1, npoints, CV_64FC3 )); + _lines2.reset(cvCreateMat( 1, npoints, CV_64FC3 )); cvConvert( F0, &F ); diff --git a/modules/calib3d/src/compat_ptsetreg.cpp b/modules/calib3d/src/compat_ptsetreg.cpp index db3fc99561..e8f4108580 100644 --- a/modules/calib3d/src/compat_ptsetreg.cpp +++ b/modules/calib3d/src/compat_ptsetreg.cpp @@ -53,7 +53,6 @@ using cv::Ptr; CvLevMarq::CvLevMarq() { - mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr(); lambdaLg10 = 0; state = DONE; criteria = cvTermCriteria(0,0,0); iters = 0; @@ -62,7 +61,6 @@ CvLevMarq::CvLevMarq() CvLevMarq::CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria0, bool _completeSymmFlag ) { - mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr(); init(nparams, nerrs, criteria0, _completeSymmFlag); } @@ -89,19 +87,19 @@ void CvLevMarq::init( int nparams, int nerrs, CvTermCriteria criteria0, bool _co { if( !param || param->rows != nparams || nerrs != (err ? err->rows : 0) ) clear(); - mask = cvCreateMat( nparams, 1, CV_8U ); + mask.reset(cvCreateMat( nparams, 1, CV_8U )); cvSet(mask, cvScalarAll(1)); - prevParam = cvCreateMat( nparams, 1, CV_64F ); - param = cvCreateMat( nparams, 1, CV_64F ); - JtJ = cvCreateMat( nparams, nparams, CV_64F ); - JtJN = cvCreateMat( nparams, nparams, CV_64F ); - JtJV = cvCreateMat( nparams, nparams, CV_64F ); - JtJW = cvCreateMat( nparams, 1, CV_64F ); - JtErr = cvCreateMat( nparams, 1, CV_64F ); + prevParam.reset(cvCreateMat( nparams, 1, CV_64F )); + param.reset(cvCreateMat( nparams, 1, CV_64F )); + JtJ.reset(cvCreateMat( nparams, nparams, CV_64F )); + JtJN.reset(cvCreateMat( nparams, nparams, CV_64F )); + JtJV.reset(cvCreateMat( nparams, nparams, CV_64F )); + JtJW.reset(cvCreateMat( nparams, 1, CV_64F )); + JtErr.reset(cvCreateMat( nparams, 1, CV_64F )); if( nerrs > 0 ) { - J = cvCreateMat( nerrs, nparams, CV_64F ); - err = cvCreateMat( nerrs, 1, CV_64F ); + J.reset(cvCreateMat( nerrs, nparams, CV_64F )); + err.reset(cvCreateMat( nerrs, 1, CV_64F )); } prevErrNorm = DBL_MAX; lambdaLg10 = -3; @@ -196,7 +194,7 @@ bool CvLevMarq::updateAlt( const CvMat*& _param, CvMat*& _JtJ, CvMat*& _JtErr, d { double change; - CV_Assert( err.empty() ); + CV_Assert( !err ); if( state == DONE ) { _param = param; diff --git a/modules/calib3d/src/five-point.cpp b/modules/calib3d/src/five-point.cpp index 88fb402726..9922247008 100644 --- a/modules/calib3d/src/five-point.cpp +++ b/modules/calib3d/src/five-point.cpp @@ -436,9 +436,9 @@ cv::Mat cv::findEssentialMat( InputArray _points1, InputArray _points2, double f Mat E; if( method == RANSAC ) - createRANSACPointSetRegistrator(new EMEstimatorCallback, 5, threshold, prob)->run(points1, points2, E, _mask); + createRANSACPointSetRegistrator(makePtr(), 5, threshold, prob)->run(points1, points2, E, _mask); else - createLMeDSPointSetRegistrator(new EMEstimatorCallback, 5, prob)->run(points1, points2, E, _mask); + createLMeDSPointSetRegistrator(makePtr(), 5, prob)->run(points1, points2, E, _mask); return E; } diff --git a/modules/calib3d/src/fundam.cpp b/modules/calib3d/src/fundam.cpp index 27378c53be..d1c6e8cd0b 100644 --- a/modules/calib3d/src/fundam.cpp +++ b/modules/calib3d/src/fundam.cpp @@ -307,7 +307,7 @@ cv::Mat cv::findHomography( InputArray _points1, InputArray _points2, if( ransacReprojThreshold <= 0 ) ransacReprojThreshold = defaultRANSACReprojThreshold; - Ptr cb = new HomographyEstimatorCallback; + Ptr cb = makePtr(); if( method == 0 || npoints == 4 ) { @@ -334,7 +334,7 @@ cv::Mat cv::findHomography( InputArray _points1, InputArray _points2, if( method == RANSAC || method == LMEDS ) cb->runKernel( src, dst, H ); Mat H8(8, 1, CV_64F, H.ptr()); - createLMSolver(new HomographyRefineCallback(src, dst), 10)->run(H8); + createLMSolver(makePtr(src, dst), 10)->run(H8); } } @@ -686,7 +686,7 @@ cv::Mat cv::findFundamentalMat( InputArray _points1, InputArray _points2, if( npoints < 7 ) return Mat(); - Ptr cb = new FMEstimatorCallback; + Ptr cb = makePtr(); int result; if( npoints == 7 || method == FM_8POINT ) diff --git a/modules/calib3d/src/levmarq.cpp b/modules/calib3d/src/levmarq.cpp index 31b96d098b..55704132cf 100644 --- a/modules/calib3d/src/levmarq.cpp +++ b/modules/calib3d/src/levmarq.cpp @@ -95,7 +95,7 @@ public: int ptype = param0.type(); CV_Assert( (param0.cols == 1 || param0.rows == 1) && (ptype == CV_32F || ptype == CV_64F)); - CV_Assert( !cb.empty() ); + CV_Assert( cb ); int lx = param0.rows + param0.cols - 1; param0.convertTo(x, CV_64F); @@ -220,7 +220,7 @@ CV_INIT_ALGORITHM(LMSolverImpl, "LMSolver", Ptr createLMSolver(const Ptr& cb, int maxIters) { CV_Assert( !LMSolverImpl_info_auto.name().empty() ); - return new LMSolverImpl(cb, maxIters); + return makePtr(cb, maxIters); } } diff --git a/modules/calib3d/src/ptsetreg.cpp b/modules/calib3d/src/ptsetreg.cpp index da2da56c7a..aa361a9118 100644 --- a/modules/calib3d/src/ptsetreg.cpp +++ b/modules/calib3d/src/ptsetreg.cpp @@ -171,7 +171,7 @@ public: RNG rng((uint64)-1); - CV_Assert( !cb.empty() ); + CV_Assert( cb ); CV_Assert( confidence > 0 && confidence < 1 ); CV_Assert( count >= 0 && count2 == count ); @@ -288,7 +288,7 @@ public: RNG rng((uint64)-1); - CV_Assert( !cb.empty() ); + CV_Assert( cb ); CV_Assert( confidence > 0 && confidence < 1 ); CV_Assert( count >= 0 && count2 == count ); @@ -397,7 +397,8 @@ Ptr createRANSACPointSetRegistrator(const Ptr( + new RANSACPointSetRegistrator(_cb, _modelPoints, _threshold, _confidence, _maxIters)); } @@ -405,7 +406,8 @@ Ptr createLMeDSPointSetRegistrator(const Ptr( + new LMeDSPointSetRegistrator(_cb, _modelPoints, _confidence, _maxIters)); } class Affine3DEstimatorCallback : public PointSetRegistrator::Callback @@ -532,5 +534,5 @@ int cv::estimateAffine3D(InputArray _from, InputArray _to, param1 = param1 <= 0 ? 3 : param1; param2 = (param2 < epsilon) ? 0.99 : (param2 > 1 - epsilon) ? 0.99 : param2; - return createRANSACPointSetRegistrator(new Affine3DEstimatorCallback, 4, param1, param2)->run(dFrom, dTo, _out, _inliers); + return createRANSACPointSetRegistrator(makePtr(), 4, param1, param2)->run(dFrom, dTo, _out, _inliers); } diff --git a/modules/calib3d/src/stereobm.cpp b/modules/calib3d/src/stereobm.cpp index 1fc193a0a9..ee131db76d 100644 --- a/modules/calib3d/src/stereobm.cpp +++ b/modules/calib3d/src/stereobm.cpp @@ -991,7 +991,7 @@ const char* StereoBMImpl::name_ = "StereoMatcher.BM"; cv::Ptr cv::createStereoBM(int _numDisparities, int _SADWindowSize) { - return new StereoBMImpl(_numDisparities, _SADWindowSize); + return makePtr(_numDisparities, _SADWindowSize); } /* End of file. */ diff --git a/modules/calib3d/src/stereosgbm.cpp b/modules/calib3d/src/stereosgbm.cpp index 700b70684a..6d75d8f53d 100644 --- a/modules/calib3d/src/stereosgbm.cpp +++ b/modules/calib3d/src/stereosgbm.cpp @@ -947,11 +947,12 @@ Ptr createStereoSGBM(int minDisparity, int numDisparities, int SADWi int speckleWindowSize, int speckleRange, int mode) { - return new StereoSGBMImpl(minDisparity, numDisparities, SADWindowSize, - P1, P2, disp12MaxDiff, - preFilterCap, uniquenessRatio, - speckleWindowSize, speckleRange, - mode); + return Ptr( + new StereoSGBMImpl(minDisparity, numDisparities, SADWindowSize, + P1, P2, disp12MaxDiff, + preFilterCap, uniquenessRatio, + speckleWindowSize, speckleRange, + mode)); } Rect getValidDisparityROI( Rect roi1, Rect roi2, diff --git a/modules/calib3d/src/triangulate.cpp b/modules/calib3d/src/triangulate.cpp index 59c7c0f2be..b0af3dc466 100644 --- a/modules/calib3d/src/triangulate.cpp +++ b/modules/calib3d/src/triangulate.cpp @@ -240,32 +240,32 @@ cvCorrectMatches(CvMat *F_, CvMat *points1_, CvMat *points2_, CvMat *new_points1 } // Make sure F uses double precision - F = cvCreateMat(3,3,CV_64FC1); + F.reset(cvCreateMat(3,3,CV_64FC1)); cvConvert(F_, F); // Make sure points1 uses double precision - points1 = cvCreateMat(points1_->rows,points1_->cols,CV_64FC2); + points1.reset(cvCreateMat(points1_->rows,points1_->cols,CV_64FC2)); cvConvert(points1_, points1); // Make sure points2 uses double precision - points2 = cvCreateMat(points2_->rows,points2_->cols,CV_64FC2); + points2.reset(cvCreateMat(points2_->rows,points2_->cols,CV_64FC2)); cvConvert(points2_, points2); - tmp33 = cvCreateMat(3,3,CV_64FC1); - tmp31 = cvCreateMat(3,1,CV_64FC1), tmp31_2 = cvCreateMat(3,1,CV_64FC1); - T1i = cvCreateMat(3,3,CV_64FC1), T2i = cvCreateMat(3,3,CV_64FC1); - R1 = cvCreateMat(3,3,CV_64FC1), R2 = cvCreateMat(3,3,CV_64FC1); - TFT = cvCreateMat(3,3,CV_64FC1), TFTt = cvCreateMat(3,3,CV_64FC1), RTFTR = cvCreateMat(3,3,CV_64FC1); - U = cvCreateMat(3,3,CV_64FC1); - S = cvCreateMat(3,3,CV_64FC1); - V = cvCreateMat(3,3,CV_64FC1); - e1 = cvCreateMat(3,1,CV_64FC1), e2 = cvCreateMat(3,1,CV_64FC1); + tmp33.reset(cvCreateMat(3,3,CV_64FC1)); + tmp31.reset(cvCreateMat(3,1,CV_64FC1)), tmp31_2.reset(cvCreateMat(3,1,CV_64FC1)); + T1i.reset(cvCreateMat(3,3,CV_64FC1)), T2i.reset(cvCreateMat(3,3,CV_64FC1)); + R1.reset(cvCreateMat(3,3,CV_64FC1)), R2.reset(cvCreateMat(3,3,CV_64FC1)); + TFT.reset(cvCreateMat(3,3,CV_64FC1)), TFTt.reset(cvCreateMat(3,3,CV_64FC1)), RTFTR.reset(cvCreateMat(3,3,CV_64FC1)); + U.reset(cvCreateMat(3,3,CV_64FC1)); + S.reset(cvCreateMat(3,3,CV_64FC1)); + V.reset(cvCreateMat(3,3,CV_64FC1)); + e1.reset(cvCreateMat(3,1,CV_64FC1)), e2.reset(cvCreateMat(3,1,CV_64FC1)); double x1, y1, x2, y2; double scale; double f1, f2, a, b, c, d; - polynomial = cvCreateMat(1,7,CV_64FC1); - result = cvCreateMat(1,6,CV_64FC2); + polynomial.reset(cvCreateMat(1,7,CV_64FC1)); + result.reset(cvCreateMat(1,6,CV_64FC2)); double t_min, s_val, t, s; for (int p = 0; p < points1->cols; ++p) { // Replace F by T2-t * F * T1-t diff --git a/modules/calib3d/test/test_solvepnp_ransac.cpp b/modules/calib3d/test/test_solvepnp_ransac.cpp index 4d00d805b5..ae744a4d7e 100644 --- a/modules/calib3d/test/test_solvepnp_ransac.cpp +++ b/modules/calib3d/test/test_solvepnp_ransac.cpp @@ -276,7 +276,7 @@ TEST(DISABLED_Calib3d_SolvePnPRansac, concurrency) { // limit concurrency to get determenistic result cv::theRNG().state = 20121010; - cv::Ptr one_thread = new tbb::task_scheduler_init(1); + tbb::task_scheduler_init one_thread(1); solvePnPRansac(object, image, camera_mat, dist_coef, rvec1, tvec1); } @@ -295,7 +295,7 @@ TEST(DISABLED_Calib3d_SolvePnPRansac, concurrency) { // single thread again cv::theRNG().state = 20121010; - cv::Ptr one_thread = new tbb::task_scheduler_init(1); + tbb::task_scheduler_init one_thread(1); solvePnPRansac(object, image, camera_mat, dist_coef, rvec2, tvec2); } diff --git a/modules/contrib/src/detection_based_tracker.cpp b/modules/contrib/src/detection_based_tracker.cpp index 91bb0b1710..27807290af 100644 --- a/modules/contrib/src/detection_based_tracker.cpp +++ b/modules/contrib/src/detection_based_tracker.cpp @@ -128,7 +128,7 @@ cv::DetectionBasedTracker::SeparateDetectionWork::SeparateDetectionWork(Detectio stateThread(STATE_THREAD_STOPPED), timeWhenDetectingThreadStartedWork(-1) { - CV_Assert(!_detector.empty()); + CV_Assert(_detector); cascadeInThread = _detector; @@ -462,11 +462,11 @@ cv::DetectionBasedTracker::DetectionBasedTracker(cv::Ptr mainDetector cascadeForTracking(trackingDetector) { CV_Assert( (params.maxTrackLifetime >= 0) -// && (!mainDetector.empty()) - && (!trackingDetector.empty()) ); +// && mainDetector + && trackingDetector ); - if (!mainDetector.empty()) { - separateDetectionWork = new SeparateDetectionWork(*this, mainDetector); + if (mainDetector) { + separateDetectionWork.reset(new SeparateDetectionWork(*this, mainDetector)); } weightsPositionsSmoothing.push_back(1); @@ -483,7 +483,7 @@ void DetectionBasedTracker::process(const Mat& imageGray) { CV_Assert(imageGray.type()==CV_8UC1); - if ( (!separateDetectionWork.empty()) && (!separateDetectionWork->isWorking()) ) { + if ( separateDetectionWork && !separateDetectionWork->isWorking() ) { separateDetectionWork->run(); } @@ -501,7 +501,7 @@ void DetectionBasedTracker::process(const Mat& imageGray) std::vector rectsWhereRegions; bool shouldHandleResult=false; - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { shouldHandleResult = separateDetectionWork->communicateWithDetectingThread(imageGray, rectsWhereRegions); } @@ -589,7 +589,7 @@ void cv::DetectionBasedTracker::getObjects(std::vector& result) const bool cv::DetectionBasedTracker::run() { - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { return separateDetectionWork->run(); } return false; @@ -597,14 +597,14 @@ bool cv::DetectionBasedTracker::run() void cv::DetectionBasedTracker::stop() { - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { separateDetectionWork->stop(); } } void cv::DetectionBasedTracker::resetTracking() { - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { separateDetectionWork->resetTracking(); } trackedObjects.clear(); @@ -876,11 +876,11 @@ bool cv::DetectionBasedTracker::setParameters(const Parameters& params) return false; } - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { separateDetectionWork->lock(); } parameters=params; - if (!separateDetectionWork.empty()) { + if (separateDetectionWork) { separateDetectionWork->unlock(); } return true; diff --git a/modules/contrib/src/facerec.cpp b/modules/contrib/src/facerec.cpp index d1050ebb76..1bea74e89e 100644 --- a/modules/contrib/src/facerec.cpp +++ b/modules/contrib/src/facerec.cpp @@ -851,18 +851,18 @@ int LBPH::predict(InputArray _src) const { Ptr createEigenFaceRecognizer(int num_components, double threshold) { - return new Eigenfaces(num_components, threshold); + return makePtr(num_components, threshold); } Ptr createFisherFaceRecognizer(int num_components, double threshold) { - return new Fisherfaces(num_components, threshold); + return makePtr(num_components, threshold); } Ptr createLBPHFaceRecognizer(int radius, int neighbors, int grid_x, int grid_y, double threshold) { - return new LBPH(radius, neighbors, grid_x, grid_y, threshold); + return makePtr(radius, neighbors, grid_x, grid_y, threshold); } CV_INIT_ALGORITHM(Eigenfaces, "FaceRecognizer.Eigenfaces", @@ -894,7 +894,7 @@ CV_INIT_ALGORITHM(LBPH, "FaceRecognizer.LBPH", bool initModule_contrib() { - Ptr efaces = createEigenfaces_hidden(), ffaces = createFisherfaces_hidden(), lbph = createLBPH_hidden(); + Ptr efaces = createEigenfaces_ptr_hidden(), ffaces = createFisherfaces_ptr_hidden(), lbph = createLBPH_ptr_hidden(); return efaces->info() != 0 && ffaces->info() != 0 && lbph->info() != 0; } diff --git a/modules/contrib/src/featuretracker.cpp b/modules/contrib/src/featuretracker.cpp index e14c55c23f..795c1a08fa 100644 --- a/modules/contrib/src/featuretracker.cpp +++ b/modules/contrib/src/featuretracker.cpp @@ -54,7 +54,7 @@ CvFeatureTracker::CvFeatureTracker(CvFeatureTrackerParams _params) : { case CvFeatureTrackerParams::SIFT: dd = Algorithm::create("Feature2D.SIFT"); - if( dd.empty() ) + if( !dd ) CV_Error(CV_StsNotImplemented, "OpenCV has been compiled without SIFT support"); dd->set("nOctaveLayers", 5); dd->set("contrastThreshold", 0.04); @@ -62,7 +62,7 @@ CvFeatureTracker::CvFeatureTracker(CvFeatureTrackerParams _params) : break; case CvFeatureTrackerParams::SURF: dd = Algorithm::create("Feature2D.SURF"); - if( dd.empty() ) + if( !dd ) CV_Error(CV_StsNotImplemented, "OpenCV has been compiled without SURF support"); dd->set("hessianThreshold", 400); dd->set("nOctaves", 3); @@ -73,7 +73,7 @@ CvFeatureTracker::CvFeatureTracker(CvFeatureTrackerParams _params) : break; } - matcher = new BFMatcher(NORM_L2); + matcher = makePtr(int(NORM_L2)); } CvFeatureTracker::~CvFeatureTracker() diff --git a/modules/core/doc/basic_structures.rst b/modules/core/doc/basic_structures.rst index 353d404f7d..93e7ca479c 100644 --- a/modules/core/doc/basic_structures.rst +++ b/modules/core/doc/basic_structures.rst @@ -638,6 +638,48 @@ The keypoint constructors :param _class_id: object id +KeyPoint::convert +-------------------- + +This method converts vector of keypoints to vector of points or the reverse, where each keypoint is assigned the same size and the same orientation. + +.. ocv:function:: void KeyPoint::convert(const std::vector& keypoints, std::vector& points2f, const std::vector& keypointIndexes=std::vector()) + +.. ocv:function:: void KeyPoint::convert(const std::vector& points2f, std::vector& keypoints, float size=1, float response=1, int octave=0, int class_id=-1) + +.. ocv:pyfunction:: cv2.KeyPoint_convert(keypoints[, keypointIndexes]) -> points2f + +.. ocv:pyfunction:: cv2.KeyPoint_convert(points2f[, size[, response[, octave[, class_id]]]]) -> keypoints + + :param keypoints: Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB + + :param points2f: Array of (x,y) coordinates of each keypoint + + :param keypointIndexes: Array of indexes of keypoints to be converted to points. (Acts like a mask to convert only specified keypoints) + + :param _size: keypoint diameter + + :param _response: keypoint detector response on the keypoint (that is, strength of the keypoint) + + :param _octave: pyramid octave in which the keypoint has been detected + + :param _class_id: object id + + +KeyPoint::overlap +-------------------- + +This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint regions' intersection and area of keypoint regions' union (considering keypoint region as circle). If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. + +.. ocv:function:: float KeyPoint::overlap(const KeyPoint& kp1, const KeyPoint& kp2) + +.. ocv:pyfunction:: cv2.KeyPoint_overlap(kp1, kp2) -> retval + + :param kp1: First keypoint + + :param kp2: Second keypoint + + DMatch ------ .. ocv:class:: DMatch @@ -668,187 +710,328 @@ train descriptor index, train image index, and distance between descriptors. :: }; - -.. _Ptr: - Ptr --- .. ocv:class:: Ptr -Template class for smart reference-counting pointers :: +Template class for smart pointers with shared ownership. :: - template class Ptr + template + struct Ptr { - public: - // default constructor + typedef T element_type; + Ptr(); - // constructor that wraps the object pointer - Ptr(_Tp* _obj); - // destructor: calls release() + + template + explicit Ptr(Y* p); + template + Ptr(Y* p, D d); + + Ptr(const Ptr& o); + template + Ptr(const Ptr& o); + template + Ptr(const Ptr& o, T* p); + ~Ptr(); - // copy constructor; increments ptr's reference counter - Ptr(const Ptr& ptr); - // assignment operator; decrements own reference counter - // (with release()) and increments ptr's reference counter - Ptr& operator = (const Ptr& ptr); - // increments reference counter - void addref(); - // decrements reference counter; when it becomes 0, - // delete_obj() is called + + Ptr& operator = (const Ptr& o); + template + Ptr& operator = (const Ptr& o); + void release(); - // user-specified custom object deletion operation. - // by default, "delete obj;" is called - void delete_obj(); - // returns true if obj == 0; + + template + void reset(Y* p); + template + void reset(Y* p, D d); + + void swap(Ptr& o); + + T* get() const; + + T& operator * () const; + T* operator -> () const; + operator T* () const; + bool empty() const; - // provide access to the object fields and methods - _Tp* operator -> (); - const _Tp* operator -> () const; - - // return the underlying object pointer; - // thanks to the methods, the Ptr<_Tp> can be - // used instead of _Tp* - operator _Tp* (); - operator const _Tp*() const; - protected: - // the encapsulated object pointer - _Tp* obj; - // the associated reference counter - int* refcount; + template + Ptr staticCast() const; + template + Ptr constCast() const; + template + Ptr dynamicCast() const; }; -The ``Ptr<_Tp>`` class is a template class that wraps pointers of the corresponding type. It is -similar to ``shared_ptr`` that is part of the Boost library -(http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm) and also part of the -`C++0x `_ standard. +A ``Ptr`` pretends to be a pointer to an object of type T. +Unlike an ordinary pointer, however, the object will be automatically +cleaned up once all ``Ptr`` instances pointing to it are destroyed. -This class provides the following options: +``Ptr`` is similar to ``boost::shared_ptr`` that is part of the Boost library +(http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm) +and ``std::shared_ptr`` from the `C++11 `_ standard. + +This class provides the following advantages: * Default constructor, copy constructor, and assignment operator for an arbitrary C++ class - or a C structure. For some objects, like files, windows, mutexes, sockets, and others, a copy + or C structure. For some objects, like files, windows, mutexes, sockets, and others, a copy constructor or an assignment operator are difficult to define. For some other objects, like complex classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally, some of complex OpenCV and your own data structures may be written in C. - However, copy constructors and default constructors can simplify programming a lot.Besides, - they are often required (for example, by STL containers). By wrapping a pointer to such a - complex object ``TObj`` to ``Ptr``, you automatically get all of the necessary + However, copy constructors and default constructors can simplify programming a lot. Besides, + they are often required (for example, by STL containers). By using a ``Ptr`` to such an + object instead of the object itself, you automatically get all of the necessary constructors and the assignment operator. * *O(1)* complexity of the above-mentioned operations. While some structures, like ``std::vector``, provide a copy constructor and an assignment operator, the operations may take a considerable - amount of time if the data structures are large. But if the structures are put into ``Ptr<>``, + amount of time if the data structures are large. But if the structures are put into a ``Ptr``, the overhead is small and independent of the data size. * - Automatic destruction, even for C structures. See the example below with ``FILE*``. + Automatic and customizable cleanup, even for C structures. See the example below with ``FILE*``. * Heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers can store only objects of the same type and the same size. The classical solution to store objects - of different types in the same container is to store pointers to the base class ``base_class_t*`` - instead but then you loose the automatic memory management. Again, by using ``Ptr()`` - instead of the raw pointers, you can solve the problem. + of different types in the same container is to store pointers to the base class (``Base*``) + instead but then you lose the automatic memory management. Again, by using ``Ptr`` + instead of raw pointers, you can solve the problem. -The ``Ptr`` class treats the wrapped object as a black box. The reference counter is allocated and -managed separately. The only thing the pointer class needs to know about the object is how to -deallocate it. This knowledge is encapsulated in the ``Ptr::delete_obj()`` method that is called when -the reference counter becomes 0. If the object is a C++ class instance, no additional coding is -needed, because the default implementation of this method calls ``delete obj;``. However, if the -object is deallocated in a different way, the specialized method should be created. For example, -if you want to wrap ``FILE``, the ``delete_obj`` may be implemented as follows: :: +A ``Ptr`` is said to *own* a pointer - that is, for each ``Ptr`` there is a pointer that will be deleted +once all ``Ptr`` instances that own it are destroyed. The owned pointer may be null, in which case nothing is deleted. +Each ``Ptr`` also *stores* a pointer. The stored pointer is the pointer the ``Ptr`` pretends to be; +that is, the one you get when you use :ocv:func:`Ptr::get` or the conversion to ``T*``. It's usually +the same as the owned pointer, but if you use casts or the general shared-ownership constructor, the two may diverge: +the ``Ptr`` will still own the original pointer, but will itself point to something else. - template<> inline void Ptr::delete_obj() - { - fclose(obj); // no need to clear the pointer afterwards, - // it is done externally. - } - ... +The owned pointer is treated as a black box. The only thing ``Ptr`` needs to know about it is how to +delete it. This knowledge is encapsulated in the *deleter* - an auxiliary object that is associated +with the owned pointer and shared between all ``Ptr`` instances that own it. The default deleter is +an instance of ``DefaultDeleter``, which uses the standard C++ ``delete`` operator; as such it +will work with any pointer allocated with the standard ``new`` operator. - // now use it: - Ptr f(fopen("myfile.txt", "r")); - if(f.empty()) - throw ...; +However, if the pointer must be deleted in a different way, you must specify a custom deleter upon +``Ptr`` construction. A deleter is simply a callable object that accepts the pointer as its sole argument. +For example, if you want to wrap ``FILE``, you may do so as follows:: + + Ptr f(fopen("myfile.txt", "w"), fclose); + if(!f) throw ...; fprintf(f, ....); ... - // the file will be closed automatically by the Ptr destructor. + // the file will be closed automatically by f's destructor. +Alternatively, if you want all pointers of a particular type to be deleted the same way, +you can specialize ``DefaultDeleter::operator()`` for that type, like this:: -.. note:: The reference increment/decrement operations are implemented as atomic operations, - and therefore it is normally safe to use the classes in multi-threaded applications. - The same is true for :ocv:class:`Mat` and other C++ OpenCV classes that operate on - the reference counters. + namespace cv { + template<> void DefaultDeleter::operator ()(FILE * obj) const + { + fclose(obj); + } + } -Ptr::Ptr --------- -Various Ptr constructors. +For convenience, the following types from the OpenCV C API already have such a specialization +that calls the appropriate release function: + +* ``CvCapture`` +* :ocv:struct:`CvDTreeSplit` +* :ocv:struct:`CvFileStorage` +* ``CvHaarClassifierCascade`` +* :ocv:struct:`CvMat` +* :ocv:struct:`CvMatND` +* :ocv:struct:`CvMemStorage` +* :ocv:struct:`CvSparseMat` +* ``CvVideoWriter`` +* :ocv:struct:`IplImage` + +.. note:: The shared ownership mechanism is implemented with reference counting. As such, + cyclic ownership (e.g. when object ``a`` contains a ``Ptr`` to object ``b``, which + contains a ``Ptr`` to object ``a``) will lead to all involved objects never being + cleaned up. Avoid such situations. + +.. note:: It is safe to concurrently read (but not write) a ``Ptr`` instance from multiple threads + and therefore it is normally safe to use it in multi-threaded applications. + The same is true for :ocv:class:`Mat` and other C++ OpenCV classes that use internal + reference counts. + +Ptr::Ptr (null) +------------------ .. ocv:function:: Ptr::Ptr() -.. ocv:function:: Ptr::Ptr(_Tp* _obj) -.. ocv:function:: Ptr::Ptr(const Ptr& ptr) - :param _obj: Object for copy. - :param ptr: Object for copy. + The default constructor creates a null ``Ptr`` - one that owns and stores a null pointer. + +Ptr::Ptr (assuming ownership) +----------------------------- + +.. ocv:function:: template Ptr::Ptr(Y* p) +.. ocv:function:: template Ptr::Ptr(Y* p, D d) + + :param d: Deleter to use for the owned pointer. + :param p: Pointer to own. + + If ``p`` is null, these are equivalent to the default constructor. + + Otherwise, these constructors assume ownership of ``p`` - that is, the created ``Ptr`` owns + and stores ``p`` and assumes it is the sole owner of it. Don't use them if ``p`` is already + owned by another ``Ptr``, or else ``p`` will get deleted twice. + + With the first constructor, ``DefaultDeleter()`` becomes the associated deleter (so ``p`` + will eventually be deleted with the standard ``delete`` operator). ``Y`` must be a complete + type at the point of invocation. + + With the second constructor, ``d`` becomes the associated deleter. + + ``Y*`` must be convertible to ``T*``. + + .. note:: It is often easier to use :ocv:func:`makePtr` instead. + +Ptr::Ptr (sharing ownership) +---------------------------- + +.. ocv:function:: Ptr::Ptr(const Ptr& o) +.. ocv:function:: template Ptr::Ptr(const Ptr& o) +.. ocv:function:: template Ptr::Ptr(const Ptr& o, T* p) + + :param o: ``Ptr`` to share ownership with. + :param p: Pointer to store. + + These constructors create a ``Ptr`` that shares ownership with another ``Ptr`` - that is, + own the same pointer as ``o``. + + With the first two, the same pointer is stored, as well; for the second, ``Y*`` must be convertible to ``T*``. + + With the third, ``p`` is stored, and ``Y`` may be any type. This constructor allows to have completely + unrelated owned and stored pointers, and should be used with care to avoid confusion. A relatively + benign use is to create a non-owning ``Ptr``, like this:: + + ptr = Ptr(Ptr(), dont_delete_me); // owns nothing; will not delete the pointer. Ptr::~Ptr --------- -The Ptr destructor. .. ocv:function:: Ptr::~Ptr() + The destructor is equivalent to calling :ocv:func:`Ptr::release`. + Ptr::operator = ---------------- -Assignment operator. -.. ocv:function:: Ptr& Ptr::operator = (const Ptr& ptr) +.. ocv:function:: Ptr& Ptr::operator = (const Ptr& o) +.. ocv:function:: template Ptr& Ptr::operator = (const Ptr& o) - :param ptr: Object for assignment. + :param o: ``Ptr`` to share ownership with. -Decrements own reference counter (with ``release()``) and increments ptr's reference counter. + Assignment replaces the current ``Ptr`` instance with one that owns and stores same + pointers as ``o`` and then destroys the old instance. -Ptr::addref ------------ -Increments reference counter. - -.. ocv:function:: void Ptr::addref() Ptr::release ------------ -Decrements reference counter; when it becomes 0, ``delete_obj()`` is called. .. ocv:function:: void Ptr::release() -Ptr::delete_obj ---------------- -User-specified custom object deletion operation. By default, ``delete obj;`` is called. + If no other ``Ptr`` instance owns the owned pointer, deletes it with the associated deleter. + Then sets both the owned and the stored pointers to ``NULL``. -.. ocv:function:: void Ptr::delete_obj() + +Ptr::reset +---------- + +.. ocv:function:: template void Ptr::reset(Y* p) +.. ocv:function:: template void Ptr::reset(Y* p, D d) + + :param d: Deleter to use for the owned pointer. + :param p: Pointer to own. + + ``ptr.reset(...)`` is equivalent to ``ptr = Ptr(...)``. + +Ptr::swap +--------- + +.. ocv:function:: void Ptr::swap(Ptr& o) + + :param o: ``Ptr`` to swap with. + + Swaps the owned and stored pointers (and deleters, if any) of this and ``o``. + +Ptr::get +-------- + +.. ocv:function:: T* Ptr::get() const + + Returns the stored pointer. + +Ptr pointer emulation +--------------------- + +.. ocv:function:: T& Ptr::operator * () const +.. ocv:function:: T* Ptr::operator -> () const +.. ocv:function:: Ptr::operator T* () const + + These operators are what allows ``Ptr`` to pretend to be a pointer. + + If ``ptr`` is a ``Ptr``, then ``*ptr`` is equivalent to ``*ptr.get()`` + and ``ptr->foo`` is equivalent to ``ptr.get()->foo``. In addition, ``ptr`` + is implicitly convertible to ``T*``, and such conversion is equivalent to + ``ptr.get()``. As a corollary, ``if (ptr)`` is equivalent to ``if (ptr.get())``. + In other words, a ``Ptr`` behaves as if it was its own stored pointer. Ptr::empty ---------- -Returns true if obj == 0; -bool empty() const; +.. ocv:function:: bool Ptr::empty() const -Ptr::operator -> ----------------- -Provide access to the object fields and methods. + ``ptr.empty()`` is equivalent to ``!ptr.get()``. -.. ocv:function:: template _Tp* Ptr::operator -> () -.. ocv:function:: template const _Tp* Ptr::operator -> () const +Ptr casts +--------- +.. ocv:function:: template Ptr Ptr::staticCast() const +.. ocv:function:: template Ptr Ptr::constCast() const +.. ocv:function:: template Ptr Ptr::dynamicCast() const -Ptr::operator _Tp* ------------------- -Returns the underlying object pointer. Thanks to the methods, the ``Ptr<_Tp>`` can be used instead -of ``_Tp*``. + If ``ptr`` is a ``Ptr``, then ``ptr.fooCast()`` is equivalent to + ``Ptr(ptr, foo_cast(ptr.get()))``. That is, these functions create + a new ``Ptr`` with the same owned pointer and a cast stored pointer. -.. ocv:function:: template Ptr::operator _Tp* () -.. ocv:function:: template Ptr::operator const _Tp*() const +Ptr global swap +--------------- +.. ocv:function:: template void swap(Ptr& ptr1, Ptr& ptr2) + + Equivalent to ``ptr1.swap(ptr2)``. Provided to help write generic algorithms. + +Ptr comparisons +--------------- + +.. ocv:function:: template bool operator == (const Ptr& ptr1, const Ptr& ptr2) +.. ocv:function:: template bool operator != (const Ptr& ptr1, const Ptr& ptr2) + + Return whether ``ptr1.get()`` and ``ptr2.get()`` are equal and not equal, respectively. + +makePtr +------- + +.. ocv:function:: template Ptr makePtr() +.. ocv:function:: template Ptr makePtr(const A1& a1) +.. ocv:function:: template Ptr makePtr(const A1& a1, const A2& a2) +.. ocv:function:: template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3) + + (and so on...) + + ``makePtr(...)`` is equivalent to ``Ptr(new T(...))``. It is shorter than the latter, and + it's marginally safer than using a constructor or :ocv:func:`Ptr::reset`, since it ensures that + the owned pointer is new and thus not owned by any other ``Ptr`` instance. + + Unfortunately, perfect forwarding is impossible to implement in C++03, and so ``makePtr`` is limited + to constructors of ``T`` that have up to 10 arguments, none of which are non-const references. Mat --- @@ -2925,7 +3108,7 @@ Creates algorithm instance by name :param name: The algorithm name, one of the names returned by ``Algorithm::getList()``. -This static method creates a new instance of the specified algorithm. If there is no such algorithm, the method will silently return null pointer (that can be checked by ``Ptr::empty()`` method). Also, you should specify the particular ``Algorithm`` subclass as ``_Tp`` (or simply ``Algorithm`` if you do not know it at that point). :: +This static method creates a new instance of the specified algorithm. If there is no such algorithm, the method will silently return a null pointer. Also, you should specify the particular ``Algorithm`` subclass as ``_Tp`` (or simply ``Algorithm`` if you do not know it at that point). :: Ptr bgfg = Algorithm::create("BackgroundSubtractor.MOG2"); diff --git a/modules/core/doc/intro.rst b/modules/core/doc/intro.rst index 582f1d00dc..6d9fdfca5e 100644 --- a/modules/core/doc/intro.rst +++ b/modules/core/doc/intro.rst @@ -83,17 +83,22 @@ First of all, ``std::vector``, ``Mat``, and other data structures used by the fu // matrix will be deallocated, since it is not referenced by anyone C = C.clone(); -You see that the use of ``Mat`` and other basic structures is simple. But what about high-level classes or even user data types created without taking automatic memory management into account? For them, OpenCV offers the ``Ptr<>`` template class that is similar to ``std::shared_ptr`` from C++ TR1. So, instead of using plain pointers:: +You see that the use of ``Mat`` and other basic structures is simple. But what about high-level classes or even user +data types created without taking automatic memory management into account? For them, OpenCV offers the :ocv:class:`Ptr` +template class that is similar to ``std::shared_ptr`` from C++11. So, instead of using plain pointers:: T* ptr = new T(...); you can use:: - Ptr ptr = new T(...); + Ptr ptr(new T(...)); -That is, ``Ptr ptr`` encapsulates a pointer to a ``T`` instance and a reference counter associated with the pointer. See the -:ocv:class:`Ptr` -description for details. +or:: + + Ptr ptr = makePtr(...); + +``Ptr`` encapsulates a pointer to a ``T`` instance and a reference counter associated with the pointer. See the +:ocv:class:`Ptr` description for details. .. _AutomaticAllocation: diff --git a/modules/core/include/opencv2/core/core_c.h b/modules/core/include/opencv2/core/core_c.h index 74a1e403a2..ca8413ee23 100644 --- a/modules/core/include/opencv2/core/core_c.h +++ b/modules/core/include/opencv2/core/core_c.h @@ -1882,13 +1882,13 @@ CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); -//////// specializied implementations of Ptr::delete_obj() for classic OpenCV types //////// +////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMat* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(IplImage* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMatND* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvSparseMat* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMemStorage* obj) const; ////////////// convenient wrappers for operating old-style dynamic structures ////////////// diff --git a/modules/core/include/opencv2/core/cuda.hpp b/modules/core/include/opencv2/core/cuda.hpp index 49e22b0643..6bca5413f9 100644 --- a/modules/core/include/opencv2/core/cuda.hpp +++ b/modules/core/include/opencv2/core/cuda.hpp @@ -666,12 +666,6 @@ CV_EXPORTS void printShortCudaDeviceInfo(int device); }} // namespace cv { namespace cuda { -namespace cv { - -template <> CV_EXPORTS void Ptr::delete_obj(); -template <> CV_EXPORTS void Ptr::delete_obj(); - -} #include "opencv2/core/cuda.inl.hpp" diff --git a/modules/core/include/opencv2/core/cvstd.hpp b/modules/core/include/opencv2/core/cvstd.hpp index 5014dba0f7..afdeb2549a 100644 --- a/modules/core/include/opencv2/core/cvstd.hpp +++ b/modules/core/include/opencv2/core/cvstd.hpp @@ -158,69 +158,176 @@ public: size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } }; - - -//////////////////// generic_type ref-counting pointer class for C/C++ objects //////////////////////// - -/*! - Smart pointer to dynamically allocated objects. - - This is template pointer-wrapping class that stores the associated reference counter along with the - object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard, - but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library). - - Basically, you can use "Ptr ptr" (or faster "const Ptr& ptr" for read-only access) - everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class. - To make it all work, you need to specialize Ptr<>::delete_obj(), like: - - \code - template<> CV_EXPORTS void Ptr::delete_obj() { call_destructor_func(obj); } - \endcode - - \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(), - since the default implementation calls "delete obj;"} - - \note{Another good property of the class is that the operations on the reference counter are atomic, - i.e. it is safe to use the class in multi-threaded applications} -*/ -template class Ptr +namespace detail { -public: - //! empty constructor - Ptr(); - //! take ownership of the pointer. The associated reference counter is allocated and set to 1 - Ptr(_Tp* _obj); - //! calls release() - ~Ptr(); - //! copy constructor. Copies the members and calls addref() - Ptr(const Ptr& ptr); - template Ptr(const Ptr<_Tp2>& ptr); - //! copy operator. Calls ptr.addref() and release() before copying the members - Ptr& operator = (const Ptr& ptr); - //! increments the reference counter - void addref(); - //! decrements the reference counter. If it reaches 0, delete_obj() is called - void release(); - //! deletes the object. Override if needed - void delete_obj(); - //! returns true iff obj==NULL - bool empty() const; - //! cast pointer to another type - template Ptr<_Tp2> ptr(); - template const Ptr<_Tp2> ptr() const; +// Metafunction to avoid taking a reference to void. +template +struct RefOrVoid { typedef T& type; }; - //! helper operators making "Ptr ptr" use very similar to "T* ptr". - _Tp* operator -> (); - const _Tp* operator -> () const; +template<> +struct RefOrVoid{ typedef void type; }; - operator _Tp* (); - operator const _Tp*() const; +template<> +struct RefOrVoid{ typedef const void type; }; - _Tp* obj; //< the object pointer. - int* refcount; //< the associated reference counter +template<> +struct RefOrVoid{ typedef volatile void type; }; + +template<> +struct RefOrVoid{ typedef const volatile void type; }; + +// This class would be private to Ptr, if it didn't have to be a non-template. +struct PtrOwner; + +} + +template +struct DefaultDeleter +{ + void operator () (Y* p) const; }; +/* + A smart shared pointer class with reference counting. + + A Ptr stores a pointer and owns a (potentially different) pointer. + The stored pointer has type T and is the one returned by get() et al, + while the owned pointer can have any type and is the one deleted + when there are no more Ptrs that own it. You can't directly obtain the + owned pointer. + + The interface of this class is mostly a subset of that of C++11's + std::shared_ptr. +*/ +template +struct Ptr +{ + /* Generic programming support. */ + typedef T element_type; + + /* Ptr that owns NULL and stores NULL. */ + Ptr(); + + /* Ptr that owns p and stores p. The owned pointer will be deleted with + DefaultDeleter. Y must be a complete type and Y* must be + convertible to T*. */ + template + explicit Ptr(Y* p); + + /* Ptr that owns p and stores p. The owned pointer will be deleted by + calling d(p). Y* must be convertible to T*. */ + template + Ptr(Y* p, D d); + + /* Same as the constructor below; it exists to suppress the generation + of the implicit copy constructor. */ + Ptr(const Ptr& o); + + /* Ptr that owns the same pointer as o and stores the same pointer as o, + converted to T*. Naturally, Y* must be convertible to T*. */ + template + Ptr(const Ptr& o); + + /* Ptr that owns same pointer as o, and stores p. Useful for casts and + creating non-owning Ptrs. */ + template + Ptr(const Ptr& o, T* p); + + /* Equivalent to release(). */ + ~Ptr(); + + /* Same as assignment below; exists to suppress the generation of the + implicit assignment operator. */ + Ptr& operator = (const Ptr& o); + + template + Ptr& operator = (const Ptr& o); + + /* Resets both the owned and stored pointers to NULL. Deletes the owned + pointer with the associated deleter if it's not owned by any other + Ptr and is non-zero. It's called reset() in std::shared_ptr; here + it is release() for compatibility with old OpenCV versions. */ + void release(); + + /* Equivalent to assigning from Ptr(p). */ + template + void reset(Y* p); + + /* Equivalent to assigning from Ptr(p, d). */ + template + void reset(Y* p, D d); + + /* Swaps the stored and owned pointers of this and o. */ + void swap(Ptr& o); + + /* Returns the stored pointer. */ + T* get() const; + + /* Ordinary pointer emulation. */ + typename detail::RefOrVoid::type operator * () const; + T* operator -> () const; + + /* Equivalent to get(). */ + operator T* () const; + + /* Equivalent to !*this. */ + bool empty() const; + + /* Returns a Ptr that owns the same pointer as this, and stores the same + pointer as this, except converted via static_cast to Y*. */ + template + Ptr staticCast() const; + + /* Ditto for const_cast. */ + template + Ptr constCast() const; + + /* Ditto for dynamic_cast. */ + template + Ptr dynamicCast() const; + +private: + detail::PtrOwner* owner; + T* stored; + + template + friend struct Ptr; // have to do this for the cross-type copy constructor +}; + +/* Overload of the generic swap. */ +template +void swap(Ptr& ptr1, Ptr& ptr2); + +/* Obvious comparisons. */ +template +bool operator == (const Ptr& ptr1, const Ptr& ptr2); +template +bool operator != (const Ptr& ptr1, const Ptr& ptr2); + +/* Convenience creation functions. In the far future, there may be variadic templates here. */ +template +Ptr makePtr(); +template +Ptr makePtr(const A1& a1); +template +Ptr makePtr(const A1& a1, const A2& a2); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9); +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10); //////////////////////////////// string class //////////////////////////////// @@ -324,176 +431,6 @@ private: }; - -/////////////////////////// cv::Ptr implementation /////////////////////////// - -template inline -Ptr<_Tp>::Ptr() - : obj(0), refcount(0) {} - -template inline -Ptr<_Tp>::Ptr(_Tp* _obj) - : obj(_obj) -{ - if(obj) - { - refcount = (int*)fastMalloc(sizeof(*refcount)); - *refcount = 1; - } - else - refcount = 0; -} - -template template -Ptr<_Tp>::Ptr(const Ptr<_Tp2>& p) - : obj(0), refcount(0) -{ - if (p.empty()) - return; - - _Tp* p_casted = dynamic_cast<_Tp*>(p.obj); - if (!p_casted) - return; - - obj = p_casted; - refcount = p.refcount; - addref(); -} - -template inline -Ptr<_Tp>::~Ptr() -{ - release(); -} - -template inline -void Ptr<_Tp>::addref() -{ - if( refcount ) - CV_XADD(refcount, 1); -} - -template inline -void Ptr<_Tp>::release() -{ - if( refcount && CV_XADD(refcount, -1) == 1 ) - { - delete_obj(); - fastFree(refcount); - } - refcount = 0; - obj = 0; -} - -template inline -void Ptr<_Tp>::delete_obj() -{ - if( obj ) - delete obj; -} - -template inline -Ptr<_Tp>::Ptr(const Ptr<_Tp>& _ptr) -{ - obj = _ptr.obj; - refcount = _ptr.refcount; - addref(); -} - -template inline -Ptr<_Tp>& Ptr<_Tp>::operator = (const Ptr<_Tp>& _ptr) -{ - int* _refcount = _ptr.refcount; - if( _refcount ) - CV_XADD(_refcount, 1); - release(); - obj = _ptr.obj; - refcount = _refcount; - return *this; -} - -template inline -_Tp* Ptr<_Tp>::operator -> () -{ - return obj; -} - -template inline -const _Tp* Ptr<_Tp>::operator -> () const -{ - return obj; -} - -template inline -Ptr<_Tp>::operator _Tp* () -{ - return obj; -} - -template inline -Ptr<_Tp>::operator const _Tp*() const -{ - return obj; -} - -template inline -bool Ptr<_Tp>::empty() const -{ - return obj == 0; -} - -template template inline -Ptr<_Tp2> Ptr<_Tp>::ptr() -{ - Ptr<_Tp2> p; - if( !obj ) - return p; - - _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); - if (!obj_casted) - return p; - - if( refcount ) - CV_XADD(refcount, 1); - - p.obj = obj_casted; - p.refcount = refcount; - return p; -} - -template template inline -const Ptr<_Tp2> Ptr<_Tp>::ptr() const -{ - Ptr<_Tp2> p; - if( !obj ) - return p; - - _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); - if (!obj_casted) - return p; - - if( refcount ) - CV_XADD(refcount, 1); - - p.obj = obj_casted; - p.refcount = refcount; - return p; -} - -template static inline -bool operator == (const Ptr<_Tp>& a, const Ptr<_Tp2>& b) -{ - return a.refcount == b.refcount; -} - -template static inline -bool operator != (const Ptr<_Tp>& a, const Ptr<_Tp2>& b) -{ - return a.refcount != b.refcount; -} - - - ////////////////////////// cv::String implementation ///////////////////////// inline @@ -940,4 +877,6 @@ namespace cv } } +#include "opencv2/core/ptr.inl.hpp" + #endif //__OPENCV_CORE_CVSTD_HPP__ diff --git a/modules/core/include/opencv2/core/opengl.hpp b/modules/core/include/opencv2/core/opengl.hpp index 751b2dfb23..19e5a629e5 100644 --- a/modules/core/include/opencv2/core/opengl.hpp +++ b/modules/core/include/opencv2/core/opengl.hpp @@ -283,12 +283,6 @@ CV_EXPORTS void setGlDevice(int device = 0); }} -namespace cv { - -template <> CV_EXPORTS void Ptr::delete_obj(); -template <> CV_EXPORTS void Ptr::delete_obj(); - -} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// diff --git a/modules/core/include/opencv2/core/operations.hpp b/modules/core/include/opencv2/core/operations.hpp index 7d39154a16..f8aeddfb11 100644 --- a/modules/core/include/opencv2/core/operations.hpp +++ b/modules/core/include/opencv2/core/operations.hpp @@ -445,14 +445,14 @@ int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) template inline Ptr<_Tp> Algorithm::create(const String& name) { - return _create(name).ptr<_Tp>(); + return _create(name).dynamicCast<_Tp>(); } template inline void Algorithm::set(const char* _name, const Ptr<_Tp>& value) { - Ptr algo_ptr = value. template ptr(); - if (algo_ptr.empty()) { + Ptr algo_ptr = value. template dynamicCast(); + if (!algo_ptr) { CV_Error( Error::StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); } info()->set(this, _name, ParamType::type, &algo_ptr); @@ -468,7 +468,7 @@ template inline void Algorithm::setAlgorithm(const char* _name, const Ptr<_Tp>& value) { Ptr algo_ptr = value. template ptr(); - if (algo_ptr.empty()) { + if (!algo_ptr) { CV_Error( Error::StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); } info()->set(this, _name, ParamType::type, &algo_ptr); diff --git a/modules/core/include/opencv2/core/persistence.hpp b/modules/core/include/opencv2/core/persistence.hpp index 1b2bbf688c..f5687614bb 100644 --- a/modules/core/include/opencv2/core/persistence.hpp +++ b/modules/core/include/opencv2/core/persistence.hpp @@ -186,7 +186,7 @@ public: //! the full constructor that opens file storage for reading or writing CV_WRAP FileStorage(const String& source, int flags, const String& encoding=String()); //! the constructor that takes pointer to the C FileStorage structure - FileStorage(CvFileStorage* fs); + FileStorage(CvFileStorage* fs, bool owning=true); //! the destructor. calls release() virtual ~FileStorage(); @@ -209,9 +209,9 @@ public: CV_WRAP FileNode operator[](const char* nodename) const; //! returns pointer to the underlying C FileStorage structure - CvFileStorage* operator *() { return fs; } + CvFileStorage* operator *() { return fs.get(); } //! returns pointer to the underlying C FileStorage structure - const CvFileStorage* operator *() const { return fs; } + const CvFileStorage* operator *() const { return fs.get(); } //! writes one or more numbers of the specified format to the currently written structure void writeRaw( const String& fmt, const uchar* vec, size_t len ); //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite() @@ -226,7 +226,7 @@ public: int state; //!< the writer state }; -template<> CV_EXPORTS void Ptr::delete_obj(); +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvFileStorage* obj) const; /*! File Storage Node class diff --git a/modules/core/include/opencv2/core/private.hpp b/modules/core/include/opencv2/core/private.hpp index c81efafb1f..a1cc0e5c89 100644 --- a/modules/core/include/opencv2/core/private.hpp +++ b/modules/core/include/opencv2/core/private.hpp @@ -128,12 +128,17 @@ namespace cv } //namespace cv #define CV_INIT_ALGORITHM(classname, algname, memberinit) \ - static ::cv::Algorithm* create##classname##_hidden() \ + static inline ::cv::Algorithm* create##classname##_hidden() \ { \ return new classname; \ } \ \ - static ::cv::AlgorithmInfo& classname##_info() \ + static inline ::cv::Ptr< ::cv::Algorithm> create##classname##_ptr_hidden() \ + { \ + return ::cv::makePtr(); \ + } \ + \ + static inline ::cv::AlgorithmInfo& classname##_info() \ { \ static ::cv::AlgorithmInfo classname##_info_var(algname, create##classname##_hidden); \ return classname##_info_var; \ diff --git a/modules/core/include/opencv2/core/ptr.inl.hpp b/modules/core/include/opencv2/core/ptr.inl.hpp new file mode 100644 index 0000000000..989724281f --- /dev/null +++ b/modules/core/include/opencv2/core/ptr.inl.hpp @@ -0,0 +1,338 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, NVIDIA Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the copyright holders or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef __OPENCV_CORE_PTR_INL_HPP__ +#define __OPENCV_CORE_PTR_INL_HPP__ + +#include + +namespace cv { + +template +void DefaultDeleter::operator () (Y* p) const +{ + delete p; +} + +namespace detail +{ + +struct PtrOwner +{ + PtrOwner() : refCount(1) + {} + + void incRef() + { + CV_XADD(&refCount, 1); + } + + void decRef() + { + if (CV_XADD(&refCount, -1) == 1) deleteSelf(); + } + +protected: + /* This doesn't really need to be virtual, since PtrOwner is never deleted + directly, but it doesn't hurt and it helps avoid warnings. */ + virtual ~PtrOwner() + {} + + virtual void deleteSelf() = 0; + +private: + unsigned int refCount; + + // noncopyable + PtrOwner(const PtrOwner&); + PtrOwner& operator = (const PtrOwner&); +}; + +template +struct PtrOwnerImpl : PtrOwner +{ + PtrOwnerImpl(Y* p, D d) : owned(p), deleter(d) + {} + + void deleteSelf() + { + deleter(owned); + delete this; + } + +private: + Y* owned; + D deleter; +}; + + +} + +template +Ptr::Ptr() : owner(NULL), stored(NULL) +{} + +template +template +Ptr::Ptr(Y* p) + : owner(p + ? new detail::PtrOwnerImpl >(p, DefaultDeleter()) + : NULL), + stored(p) +{} + +template +template +Ptr::Ptr(Y* p, D d) + : owner(p + ? new detail::PtrOwnerImpl(p, d) + : NULL), + stored(p) +{} + +template +Ptr::Ptr(const Ptr& o) : owner(o.owner), stored(o.stored) +{ + if (owner) owner->incRef(); +} + +template +template +Ptr::Ptr(const Ptr& o) : owner(o.owner), stored(o.stored) +{ + if (owner) owner->incRef(); +} + +template +template +Ptr::Ptr(const Ptr& o, T* p) : owner(o.owner), stored(p) +{ + if (owner) owner->incRef(); +} + +template +Ptr::~Ptr() +{ + release(); +} + +template +Ptr& Ptr::operator = (const Ptr& o) +{ + Ptr(o).swap(*this); + return *this; +} + +template +template +Ptr& Ptr::operator = (const Ptr& o) +{ + Ptr(o).swap(*this); + return *this; +} + +template +void Ptr::release() +{ + if (owner) owner->decRef(); + owner = NULL; + stored = NULL; +} + +template +template +void Ptr::reset(Y* p) +{ + Ptr(p).swap(*this); +} + +template +template +void Ptr::reset(Y* p, D d) +{ + Ptr(p, d).swap(*this); +} + +template +void Ptr::swap(Ptr& o) +{ + std::swap(owner, o.owner); + std::swap(stored, o.stored); +} + +template +T* Ptr::get() const +{ + return stored; +} + +template +typename detail::RefOrVoid::type Ptr::operator * () const +{ + return *stored; +} + +template +T* Ptr::operator -> () const +{ + return stored; +} + +template +Ptr::operator T* () const +{ + return stored; +} + + +template +bool Ptr::empty() const +{ + return !stored; +} + +template +template +Ptr Ptr::staticCast() const +{ + return Ptr(*this, static_cast(stored)); +} + +template +template +Ptr Ptr::constCast() const +{ + return Ptr(*this, const_cast(stored)); +} + +template +template +Ptr Ptr::dynamicCast() const +{ + return Ptr(*this, dynamic_cast(stored)); +} + +template +void swap(Ptr& ptr1, Ptr& ptr2){ + ptr1.swap(ptr2); +} + +template +bool operator == (const Ptr& ptr1, const Ptr& ptr2) +{ + return ptr1.get() == ptr2.get(); +} + +template +bool operator != (const Ptr& ptr1, const Ptr& ptr2) +{ + return ptr1.get() != ptr2.get(); +} + +template +Ptr makePtr() +{ + return Ptr(new T()); +} + +template +Ptr makePtr(const A1& a1) +{ + return Ptr(new T(a1)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2) +{ + return Ptr(new T(a1, a2)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3) +{ + return Ptr(new T(a1, a2, a3)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4) +{ + return Ptr(new T(a1, a2, a3, a4)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) +{ + return Ptr(new T(a1, a2, a3, a4, a5)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) +{ + return Ptr(new T(a1, a2, a3, a4, a5, a6)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) +{ + return Ptr(new T(a1, a2, a3, a4, a5, a6, a7)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8) +{ + return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9) +{ + return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8, a9)); +} + +template +Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10) +{ + return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); +} + +} // namespace cv + +#endif // __OPENCV_CORE_PTR_INL_HPP__ diff --git a/modules/core/include/opencv2/core/types.hpp b/modules/core/include/opencv2/core/types.hpp index 3ca86add05..9252cad14a 100644 --- a/modules/core/include/opencv2/core/types.hpp +++ b/modules/core/include/opencv2/core/types.hpp @@ -551,18 +551,18 @@ public: size_t hash() const; //! converts vector of keypoints to vector of points - static void convert(const std::vector& keypoints, - CV_OUT std::vector& points2f, - const std::vector& keypointIndexes=std::vector()); + CV_WRAP static void convert(const std::vector& keypoints, + CV_OUT std::vector& points2f, + const std::vector& keypointIndexes=std::vector()); //! converts vector of points to the vector of keypoints, where each keypoint is assigned the same size and the same orientation - static void convert(const std::vector& points2f, - CV_OUT std::vector& keypoints, - float size=1, float response=1, int octave=0, int class_id=-1); + CV_WRAP static void convert(const std::vector& points2f, + CV_OUT std::vector& keypoints, + float size=1, float response=1, int octave=0, int class_id=-1); //! computes overlap for pair of keypoints; //! overlap is a ratio between area of keypoint regions intersection and //! area of keypoint regions union (now keypoint region is circle) - static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); + CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); CV_PROP_RW Point2f pt; //!< coordinates of the keypoints CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood diff --git a/modules/core/src/algorithm.cpp b/modules/core/src/algorithm.cpp index d0c6f5c924..ff67a5df1e 100644 --- a/modules/core/src/algorithm.cpp +++ b/modules/core/src/algorithm.cpp @@ -163,7 +163,7 @@ Ptr Algorithm::_create(const String& name) Algorithm::Constructor c = 0; if( !alglist().find(name, c) ) return Ptr(); - return c(); + return Ptr(c()); } Algorithm::Algorithm() @@ -490,7 +490,7 @@ void AlgorithmInfo::read(Algorithm* algo, const FileNode& fn) const else if( p.type == Param::ALGORITHM ) { Ptr nestedAlgo = Algorithm::_create((String)n["name"]); - CV_Assert( !nestedAlgo.empty() ); + CV_Assert( nestedAlgo ); nestedAlgo->read(n); info->set(algo, pname.c_str(), p.type, &nestedAlgo, true); } diff --git a/modules/core/src/array.cpp b/modules/core/src/array.cpp index 60ac848651..2ad7b1216c 100644 --- a/modules/core/src/array.cpp +++ b/modules/core/src/array.cpp @@ -3190,22 +3190,22 @@ cvCheckTermCriteria( CvTermCriteria criteria, double default_eps, namespace cv { -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvMat* obj) const { cvReleaseMat(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(IplImage* obj) const { cvReleaseImage(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvMatND* obj) const { cvReleaseMatND(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvSparseMat* obj) const { cvReleaseSparseMat(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvMemStorage* obj) const { cvReleaseMemStorage(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvFileStorage* obj) const { cvReleaseFileStorage(&obj); } } diff --git a/modules/core/src/cuda_stream.cpp b/modules/core/src/cuda_stream.cpp index 27fd6628cc..3fdc83867b 100644 --- a/modules/core/src/cuda_stream.cpp +++ b/modules/core/src/cuda_stream.cpp @@ -100,7 +100,7 @@ cv::cuda::Stream::Stream() #ifndef HAVE_CUDA throw_no_cuda(); #else - impl_ = new Impl; + impl_ = makePtr(); #endif } @@ -182,7 +182,7 @@ void cv::cuda::Stream::enqueueHostCallback(StreamCallback callback, void* userDa Stream& cv::cuda::Stream::Null() { - static Stream s(new Impl(0)); + static Stream s(Ptr(new Impl(0))); return s; } @@ -195,10 +195,6 @@ cv::cuda::Stream::operator bool_type() const #endif } -template <> void cv::Ptr::delete_obj() -{ - if (obj) delete obj; -} //////////////////////////////////////////////////////////////// // Stream @@ -249,7 +245,7 @@ cv::cuda::Event::Event(CreateFlags flags) (void) flags; throw_no_cuda(); #else - impl_ = new Impl(flags); + impl_ = makePtr(flags); #endif } @@ -301,8 +297,3 @@ float cv::cuda::Event::elapsedTime(const Event& start, const Event& end) return ms; #endif } - -template <> void cv::Ptr::delete_obj() -{ - if (obj) delete obj; -} diff --git a/modules/core/src/opengl.cpp b/modules/core/src/opengl.cpp index 37a78a8705..24098bbec4 100644 --- a/modules/core/src/opengl.cpp +++ b/modules/core/src/opengl.cpp @@ -836,10 +836,6 @@ unsigned int cv::ogl::Buffer::bufId() const #endif } -template <> void cv::Ptr::delete_obj() -{ - if (obj) delete obj; -} ////////////////////////////////////////////////////////////////////////////////////////// // ogl::Texture @@ -1243,10 +1239,6 @@ unsigned int cv::ogl::Texture2D::texId() const #endif } -template <> void cv::Ptr::delete_obj() -{ - if (obj) delete obj; -} //////////////////////////////////////////////////////////////////////// // ogl::Arrays diff --git a/modules/core/src/out.cpp b/modules/core/src/out.cpp index cc2294ded6..3ed454ebfa 100644 --- a/modules/core/src/out.cpp +++ b/modules/core/src/out.cpp @@ -256,7 +256,7 @@ namespace cv::Ptr format(const cv::Mat& mtx) const { char braces[5] = {'\0', '\0', ';', '\0', '\0'}; - return new FormattedImpl("[", "]", mtx, braces, + return cv::makePtr("[", "]", mtx, &*braces, mtx.cols == 1 || !multiline, mtx.depth() == CV_64F ? prec64f : prec32f ); } }; @@ -270,7 +270,7 @@ namespace char braces[5] = {'[', ']', '\0', '[', ']'}; if (mtx.cols == 1) braces[0] = braces[1] = '\0'; - return new FormattedImpl("[", "]", mtx, braces, + return cv::makePtr("[", "]", mtx, &*braces, mtx.cols*mtx.channels() == 1 || !multiline, mtx.depth() == CV_64F ? prec64f : prec32f ); } }; @@ -288,7 +288,8 @@ namespace char braces[5] = {'[', ']', '\0', '[', ']'}; if (mtx.cols == 1) braces[0] = braces[1] = '\0'; - return new FormattedImpl("array([", cv::format("], type='%s')", numpyTypes[mtx.depth()]), mtx, braces, + return cv::makePtr("array([", + cv::format("], type='%s')", numpyTypes[mtx.depth()]), mtx, &*braces, mtx.cols*mtx.channels() == 1 || !multiline, mtx.depth() == CV_64F ? prec64f : prec32f ); } }; @@ -300,7 +301,8 @@ namespace cv::Ptr format(const cv::Mat& mtx) const { char braces[5] = {'\0', '\0', '\0', '\0', '\0'}; - return new FormattedImpl(cv::String(), mtx.rows > 1 ? cv::String("\n") : cv::String(), mtx, braces, + return cv::makePtr(cv::String(), + mtx.rows > 1 ? cv::String("\n") : cv::String(), mtx, &*braces, mtx.cols*mtx.channels() == 1 || !multiline, mtx.depth() == CV_64F ? prec64f : prec32f ); } }; @@ -312,7 +314,7 @@ namespace cv::Ptr format(const cv::Mat& mtx) const { char braces[5] = {'\0', '\0', ',', '\0', '\0'}; - return new FormattedImpl("{", "}", mtx, braces, + return cv::makePtr("{", "}", mtx, &*braces, mtx.cols == 1 || !multiline, mtx.depth() == CV_64F ? prec64f : prec32f ); } }; @@ -330,16 +332,16 @@ namespace cv switch(fmt) { case FMT_MATLAB: - return new MatlabFormatter(); + return makePtr(); case FMT_CSV: - return new CSVFormatter(); + return makePtr(); case FMT_PYTHON: - return new PythonFormatter(); + return makePtr(); case FMT_NUMPY: - return new NumpyFormatter(); + return makePtr(); case FMT_C: - return new CFormatter(); + return makePtr(); } - return new MatlabFormatter(); + return makePtr(); } } // cv diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 3a13e6552b..39ce633139 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -5129,9 +5129,11 @@ FileStorage::FileStorage(const String& filename, int flags, const String& encodi open( filename, flags, encoding ); } -FileStorage::FileStorage(CvFileStorage* _fs) +FileStorage::FileStorage(CvFileStorage* _fs, bool owning) { - fs = Ptr(_fs); + if (owning) fs.reset(_fs); + else fs = Ptr(Ptr(), _fs); + state = _fs ? NAME_EXPECTED + INSIDE_MAP : UNDEFINED; } @@ -5147,8 +5149,8 @@ FileStorage::~FileStorage() bool FileStorage::open(const String& filename, int flags, const String& encoding) { release(); - fs = Ptr(cvOpenFileStorage( filename.c_str(), 0, flags, - !encoding.empty() ? encoding.c_str() : 0)); + fs.reset(cvOpenFileStorage( filename.c_str(), 0, flags, + !encoding.empty() ? encoding.c_str() : 0)); bool ok = isOpened(); state = ok ? NAME_EXPECTED + INSIDE_MAP : UNDEFINED; return ok; @@ -5156,7 +5158,7 @@ bool FileStorage::open(const String& filename, int flags, const String& encoding bool FileStorage::isOpened() const { - return !fs.empty() && fs.obj->is_opened; + return fs && fs->is_opened; } void FileStorage::release() @@ -5169,8 +5171,8 @@ void FileStorage::release() String FileStorage::releaseAndGetString() { String buf; - if( fs.obj && fs.obj->outbuf ) - icvClose(fs.obj, &buf); + if( fs && fs->outbuf ) + icvClose(fs, &buf); release(); return buf; @@ -5479,7 +5481,7 @@ void write( FileStorage& fs, const String& name, const Mat& value ) // TODO: the 4 functions below need to be implemented more efficiently void write( FileStorage& fs, const String& name, const SparseMat& value ) { - Ptr mat = cvCreateSparseMat(value); + Ptr mat(cvCreateSparseMat(value)); cvWrite( *fs, name.size() ? name.c_str() : 0, mat ); } @@ -5529,8 +5531,8 @@ void read( const FileNode& node, SparseMat& mat, const SparseMat& default_mat ) default_mat.copyTo(mat); return; } - Ptr m = (CvSparseMat*)cvRead((CvFileStorage*)node.fs, (CvFileNode*)*node); - CV_Assert(CV_IS_SPARSE_MAT(m.obj)); + Ptr m((CvSparseMat*)cvRead((CvFileStorage*)node.fs, (CvFileNode*)*node)); + CV_Assert(CV_IS_SPARSE_MAT(m)); m->copyToSparseMat(mat); } diff --git a/modules/core/test/test_ds.cpp b/modules/core/test/test_ds.cpp index cd76ca2fe9..c71deed06f 100644 --- a/modules/core/test/test_ds.cpp +++ b/modules/core/test/test_ds.cpp @@ -358,8 +358,6 @@ Core_DynStructBaseTest::Core_DynStructBaseTest() iterations = max_struct_size*2; gen = struct_idx = iter = -1; test_progress = -1; - - storage = 0; } @@ -999,7 +997,7 @@ void Core_SeqBaseTest::run( int ) { t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); + storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) )); } iter = struct_idx = -1; @@ -1083,11 +1081,11 @@ void Core_SeqSortInvTest::run( int ) { struct_idx = iter = -1; - if( storage.empty() ) + if( !storage ) { t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); + storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) )); } for( iter = 0; iter < iterations/10; iter++ ) @@ -1384,7 +1382,7 @@ void Core_SetTest::run( int ) { struct_idx = iter = -1; t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); + storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) )); for( int i = 0; i < struct_count; i++ ) { @@ -1398,7 +1396,7 @@ void Core_SetTest::run( int ) cvTsReleaseSimpleSet( (CvTsSimpleSet**)&simple_struct[i] ); simple_struct[i] = cvTsCreateSimpleSet( max_struct_size, pure_elem_size ); - cxcore_struct[i] = cvCreateSet( 0, sizeof(CvSet), elem_size, storage ); + cxcore_struct[i] = cvCreateSet( 0, sizeof(CvSet), elem_size, storage ); } if( test_set_ops( iterations*100 ) < 0 ) @@ -1811,7 +1809,7 @@ void Core_GraphTest::run( int ) int block_size = cvRound( exp(t * CV_LOG2) ); block_size = MAX(block_size, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - storage = cvCreateMemStorage(block_size); + storage.reset(cvCreateMemStorage(block_size)); for( i = 0; i < struct_count; i++ ) { @@ -1929,7 +1927,7 @@ void Core_GraphScanTest::run( int ) storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphEdge) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphVtx) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - storage = cvCreateMemStorage(storage_blocksize); + storage.reset(cvCreateMemStorage(storage_blocksize)); if( gen == 0 ) { diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 8644d8eeac..ba66567615 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -270,16 +270,16 @@ protected: cvRelease((void**)&m_nd); - Ptr m_s = (CvSparseMat*)fs["test_sparse_mat"].readObj(); - Ptr _test_sparse_ = cvCreateSparseMat(test_sparse_mat); - Ptr _test_sparse = (CvSparseMat*)cvClone(_test_sparse_); + Ptr m_s((CvSparseMat*)fs["test_sparse_mat"].readObj()); + Ptr _test_sparse_(cvCreateSparseMat(test_sparse_mat)); + Ptr _test_sparse((CvSparseMat*)cvClone(_test_sparse_)); SparseMat m_s2; fs["test_sparse_mat"] >> m_s2; - Ptr _m_s2 = cvCreateSparseMat(m_s2); + Ptr _m_s2(cvCreateSparseMat(m_s2)); if( !m_s || !CV_IS_SPARSE_MAT(m_s) || - !cvTsCheckSparse(m_s, _test_sparse,0) || - !cvTsCheckSparse(_m_s2, _test_sparse,0)) + !cvTsCheckSparse(m_s, _test_sparse, 0) || + !cvTsCheckSparse(_m_s2, _test_sparse, 0)) { ts->printf( cvtest::TS::LOG, "the read sparse matrix is not correct\n" ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); diff --git a/modules/core/test/test_mat.cpp b/modules/core/test/test_mat.cpp index 6e3ec03dc6..3c8ae8bf9f 100644 --- a/modules/core/test/test_mat.cpp +++ b/modules/core/test/test_mat.cpp @@ -669,7 +669,7 @@ void Core_ArrayOpTest::run( int /* start_from */) cvSetReal3D(&matA, idx1[0], idx1[1], idx1[2], -val0); cvSetND(&matB, idx0, val1); cvSet3D(&matB, idx1[0], idx1[1], idx1[2], -val1); - Ptr matC = cvCloneMatND(&matB); + Ptr matC(cvCloneMatND(&matB)); if( A.at(idx0[0], idx0[1], idx0[2]) != val0 || A.at(idx1[0], idx1[1], idx1[2]) != -val0 || @@ -762,7 +762,7 @@ void Core_ArrayOpTest::run( int /* start_from */) } } - Ptr M2 = cvCreateSparseMat(M); + Ptr M2(cvCreateSparseMat(M)); MatND Md; M.copyTo(Md); SparseMat M3; SparseMat(Md).convertTo(M3, Md.type(), 2); diff --git a/modules/core/test/test_ptr.cpp b/modules/core/test/test_ptr.cpp new file mode 100644 index 0000000000..c6f793ab16 --- /dev/null +++ b/modules/core/test/test_ptr.cpp @@ -0,0 +1,389 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, NVIDIA Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the copyright holders or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include "test_precomp.hpp" + +using namespace cv; + +namespace { + +struct Reporter { + Reporter(bool* deleted) : deleted_(deleted) + { *deleted_ = false; } + + // the destructor is virtual, so that we can test dynamic_cast later + virtual ~Reporter() + { *deleted_ = true; } + +private: + bool* deleted_; + + Reporter(const Reporter&); + Reporter& operator = (const Reporter&); +}; + +struct ReportingDeleter { + ReportingDeleter(bool* deleted) : deleted_(deleted) + { *deleted_ = false; } + + void operator()(void*) + { *deleted_ = true; } + +private: + bool* deleted_; +}; + +int dummyObject; + +} + +TEST(Core_Ptr, default_ctor) +{ + Ptr p; + EXPECT_EQ(NULL, p.get()); +} + +TEST(Core_Ptr, owning_ctor) +{ + bool deleted = false; + + { + Reporter* r = new Reporter(&deleted); + Ptr p(r); + EXPECT_EQ(r, p.get()); + } + + EXPECT_TRUE(deleted); + + { + Ptr p(&dummyObject, ReportingDeleter(&deleted)); + EXPECT_EQ(&dummyObject, p.get()); + } + + EXPECT_TRUE(deleted); + + { + Ptr p((void*)0, ReportingDeleter(&deleted)); + EXPECT_EQ(NULL, p.get()); + } + + EXPECT_FALSE(deleted); +} + +TEST(Core_Ptr, sharing_ctor) +{ + bool deleted = false; + + { + Ptr p1(new Reporter(&deleted)); + Ptr p2(p1); + EXPECT_EQ(p1.get(), p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); + + { + Ptr p1(new Reporter(&deleted)); + Ptr p2(p1); + EXPECT_EQ(p1.get(), p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); + + { + Ptr p1(new Reporter(&deleted)); + Ptr p2(p1, &dummyObject); + EXPECT_EQ(&dummyObject, p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); +} + +TEST(Core_Ptr, assignment) +{ + bool deleted1 = false, deleted2 = false; + + { + Ptr p1(new Reporter(&deleted1)); + p1 = p1; + EXPECT_FALSE(deleted1); + } + + EXPECT_TRUE(deleted1); + + { + Ptr p1(new Reporter(&deleted1)); + Ptr p2(new Reporter(&deleted2)); + p2 = p1; + EXPECT_TRUE(deleted2); + EXPECT_EQ(p1.get(), p2.get()); + p1.release(); + EXPECT_FALSE(deleted1); + } + + EXPECT_TRUE(deleted1); + + { + Ptr p1(new Reporter(&deleted1)); + Ptr p2(new Reporter(&deleted2)); + p2 = p1; + EXPECT_TRUE(deleted2); + EXPECT_EQ(p1.get(), p2.get()); + p1.release(); + EXPECT_FALSE(deleted1); + } + + EXPECT_TRUE(deleted1); +} + +TEST(Core_Ptr, release) +{ + bool deleted = false; + + Ptr p1(new Reporter(&deleted)); + p1.release(); + EXPECT_TRUE(deleted); + EXPECT_EQ(NULL, p1.get()); +} + +TEST(Core_Ptr, reset) +{ + bool deleted_old = false, deleted_new = false; + + { + Ptr p(new Reporter(&deleted_old)); + Reporter* r = new Reporter(&deleted_new); + p.reset(r); + EXPECT_TRUE(deleted_old); + EXPECT_EQ(r, p.get()); + } + + EXPECT_TRUE(deleted_new); + + { + Ptr p(new Reporter(&deleted_old)); + p.reset(&dummyObject, ReportingDeleter(&deleted_new)); + EXPECT_TRUE(deleted_old); + EXPECT_EQ(&dummyObject, p.get()); + } + + EXPECT_TRUE(deleted_new); +} + +TEST(Core_Ptr, swap) +{ + bool deleted1 = false, deleted2 = false; + + { + Reporter* r1 = new Reporter(&deleted1); + Reporter* r2 = new Reporter(&deleted2); + Ptr p1(r1), p2(r2); + p1.swap(p2); + EXPECT_EQ(r1, p2.get()); + EXPECT_EQ(r2, p1.get()); + EXPECT_FALSE(deleted1); + EXPECT_FALSE(deleted2); + p1.release(); + EXPECT_TRUE(deleted2); + } + + EXPECT_TRUE(deleted1); + + { + Reporter* r1 = new Reporter(&deleted1); + Reporter* r2 = new Reporter(&deleted2); + Ptr p1(r1), p2(r2); + swap(p1, p2); + EXPECT_EQ(r1, p2.get()); + EXPECT_EQ(r2, p1.get()); + EXPECT_FALSE(deleted1); + EXPECT_FALSE(deleted2); + p1.release(); + EXPECT_TRUE(deleted2); + } + + EXPECT_TRUE(deleted1); +} + +TEST(Core_Ptr, accessors) +{ + { + Ptr p; + EXPECT_EQ(NULL, static_cast(p)); + EXPECT_TRUE(p.empty()); + } + + { + Size* s = new Size(); + Ptr p(s); + EXPECT_EQ(s, static_cast(p)); + EXPECT_EQ(s, &*p); + EXPECT_EQ(&s->width, &p->width); + EXPECT_FALSE(p.empty()); + } +} + +namespace { + +struct SubReporterBase { + virtual ~SubReporterBase() {} + int padding; +}; + +/* multiple inheritance, so that casts do something interesting */ +struct SubReporter : SubReporterBase, Reporter +{ + SubReporter(bool* deleted) : Reporter(deleted) + {} +}; + +} + +TEST(Core_Ptr, casts) +{ + bool deleted = false; + + { + Ptr p1(new Reporter(&deleted)); + Ptr p2 = p1.constCast(); + EXPECT_EQ(p1.get(), p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); + + { + SubReporter* sr = new SubReporter(&deleted); + Ptr p1(sr); + // This next check isn't really for Ptr itself; it checks that Reporter + // is at a non-zero offset within SubReporter, so that the next + // check will give us more confidence that the cast actually did something. + EXPECT_NE(static_cast(sr), static_cast(p1.get())); + Ptr p2 = p1.staticCast(); + EXPECT_EQ(sr, p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); + + { + SubReporter* sr = new SubReporter(&deleted); + Ptr p1(sr); + EXPECT_NE(static_cast(sr), static_cast(p1.get())); + Ptr p2 = p1.dynamicCast(); + EXPECT_EQ(sr, p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); + + { + Ptr p1(new Reporter(&deleted)); + Ptr p2 = p1.dynamicCast(); + EXPECT_EQ(NULL, p2.get()); + p1.release(); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); +} + +TEST(Core_Ptr, comparisons) +{ + Ptr p1, p2(new int), p3(new int); + Ptr p4(p2, p3.get()); + + // Not using EXPECT_EQ here, since none of them are really "expected" or "actual". + EXPECT_TRUE(p1 == p1); + EXPECT_TRUE(p2 == p2); + EXPECT_TRUE(p2 != p3); + EXPECT_TRUE(p2 != p4); + EXPECT_TRUE(p3 == p4); +} + +TEST(Core_Ptr, make) +{ + bool deleted = true; + + { + Ptr p = makePtr(&deleted); + EXPECT_FALSE(deleted); + } + + EXPECT_TRUE(deleted); +} + +namespace { + +struct SpeciallyDeletable +{ + SpeciallyDeletable() : deleted(false) + {} + bool deleted; +}; + +} + +namespace cv { + +template<> +void DefaultDeleter::operator()(SpeciallyDeletable * obj) const +{ obj->deleted = true; } + +} + +TEST(Core_Ptr, specialized_deleter) +{ + SpeciallyDeletable sd; + + { Ptr p(&sd); } + + ASSERT_TRUE(sd.deleted); +} diff --git a/modules/cuda/src/cascadeclassifier.cpp b/modules/cuda/src/cascadeclassifier.cpp index 9449b0a27d..c4e9870151 100644 --- a/modules/cuda/src/cascadeclassifier.cpp +++ b/modules/cuda/src/cascadeclassifier.cpp @@ -207,8 +207,8 @@ private: ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), NCV_CUDA_ERROR); // Load the classifier from file (assuming its size is about 1 mb) using a simple allocator - gpuCascadeAllocator = new NCVMemNativeAllocator(NCVMemoryTypeDevice, static_cast(devProp.textureAlignment)); - cpuCascadeAllocator = new NCVMemNativeAllocator(NCVMemoryTypeHostPinned, static_cast(devProp.textureAlignment)); + gpuCascadeAllocator = makePtr(NCVMemoryTypeDevice, static_cast(devProp.textureAlignment)); + cpuCascadeAllocator = makePtr(NCVMemoryTypeHostPinned, static_cast(devProp.textureAlignment)); ncvAssertPrintReturn(gpuCascadeAllocator->isInitialized(), "Error creating cascade GPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(cpuCascadeAllocator->isInitialized(), "Error creating cascade CPU allocator", NCV_CUDA_ERROR); @@ -217,9 +217,9 @@ private: ncvStat = ncvHaarGetClassifierSize(classifierFile, haarNumStages, haarNumNodes, haarNumFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", NCV_FILE_ERROR); - h_haarStages = new NCVVectorAlloc(*cpuCascadeAllocator, haarNumStages); - h_haarNodes = new NCVVectorAlloc(*cpuCascadeAllocator, haarNumNodes); - h_haarFeatures = new NCVVectorAlloc(*cpuCascadeAllocator, haarNumFeatures); + h_haarStages.reset (new NCVVectorAlloc(*cpuCascadeAllocator, haarNumStages)); + h_haarNodes.reset (new NCVVectorAlloc(*cpuCascadeAllocator, haarNumNodes)); + h_haarFeatures.reset(new NCVVectorAlloc(*cpuCascadeAllocator, haarNumFeatures)); ncvAssertPrintReturn(h_haarStages->isMemAllocated(), "Error in cascade CPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(h_haarNodes->isMemAllocated(), "Error in cascade CPU allocator", NCV_CUDA_ERROR); @@ -228,9 +228,9 @@ private: ncvStat = ncvHaarLoadFromFile_host(classifierFile, haar, *h_haarStages, *h_haarNodes, *h_haarFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", NCV_FILE_ERROR); - d_haarStages = new NCVVectorAlloc(*gpuCascadeAllocator, haarNumStages); - d_haarNodes = new NCVVectorAlloc(*gpuCascadeAllocator, haarNumNodes); - d_haarFeatures = new NCVVectorAlloc(*gpuCascadeAllocator, haarNumFeatures); + d_haarStages.reset (new NCVVectorAlloc(*gpuCascadeAllocator, haarNumStages)); + d_haarNodes.reset (new NCVVectorAlloc(*gpuCascadeAllocator, haarNumNodes)); + d_haarFeatures.reset(new NCVVectorAlloc(*gpuCascadeAllocator, haarNumFeatures)); ncvAssertPrintReturn(d_haarStages->isMemAllocated(), "Error in cascade GPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(d_haarNodes->isMemAllocated(), "Error in cascade GPU allocator", NCV_CUDA_ERROR); @@ -279,8 +279,8 @@ private: ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); - gpuAllocator = new NCVMemStackAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), static_cast(devProp.textureAlignment)); - cpuAllocator = new NCVMemStackAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), static_cast(devProp.textureAlignment)); + gpuAllocator = makePtr(NCVMemoryTypeDevice, gpuCounter.maxSize(), static_cast(devProp.textureAlignment)); + cpuAllocator = makePtr(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), static_cast(devProp.textureAlignment)); ncvAssertPrintReturn(gpuAllocator->isInitialized(), "Error creating GPU memory allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(cpuAllocator->isInitialized(), "Error creating CPU memory allocator", NCV_CUDA_ERROR); diff --git a/modules/cudaarithm/src/arithm.cpp b/modules/cudaarithm/src/arithm.cpp index d08e993bb2..6f7417ae35 100644 --- a/modules/cudaarithm/src/arithm.cpp +++ b/modules/cudaarithm/src/arithm.cpp @@ -629,7 +629,7 @@ Ptr cv::cuda::createConvolution(Size user_block_size) CV_Error(Error::StsNotImplemented, "The library was build without CUFFT"); return Ptr(); #else - return new ConvolutionImpl(user_block_size); + return makePtr(user_block_size); #endif } diff --git a/modules/cudaarithm/src/core.cpp b/modules/cudaarithm/src/core.cpp index b6189fd0ef..e6c14db09f 100644 --- a/modules/cudaarithm/src/core.cpp +++ b/modules/cudaarithm/src/core.cpp @@ -497,7 +497,7 @@ namespace Ptr cv::cuda::createLookUpTable(InputArray lut) { - return new LookUpTableImpl(lut); + return makePtr(lut); } //////////////////////////////////////////////////////////////////////// diff --git a/modules/cudabgsegm/perf/perf_bgsegm.cpp b/modules/cudabgsegm/perf/perf_bgsegm.cpp index 93de1c8f11..ef2bea864a 100644 --- a/modules/cudabgsegm/perf/perf_bgsegm.cpp +++ b/modules/cudabgsegm/perf/perf_bgsegm.cpp @@ -76,7 +76,7 @@ using namespace perf; namespace cv { - template<> void Ptr::delete_obj() + template<> void DefaultDeleter::operator ()(CvBGStatModel* obj) const { cvReleaseBGStatModel(&obj); } diff --git a/modules/cudabgsegm/src/fgd.cpp b/modules/cudabgsegm/src/fgd.cpp index 46abf6188e..68f03a3e16 100644 --- a/modules/cudabgsegm/src/fgd.cpp +++ b/modules/cudabgsegm/src/fgd.cpp @@ -725,7 +725,7 @@ namespace Ptr cv::cuda::createBackgroundSubtractorFGD(const FGDParams& params) { - return new FGDImpl(params); + return makePtr(params); } #endif // HAVE_CUDA diff --git a/modules/cudabgsegm/src/gmg.cpp b/modules/cudabgsegm/src/gmg.cpp index 096c958a61..9158d8fa61 100644 --- a/modules/cudabgsegm/src/gmg.cpp +++ b/modules/cudabgsegm/src/gmg.cpp @@ -271,7 +271,7 @@ namespace Ptr cv::cuda::createBackgroundSubtractorGMG(int initializationFrames, double decisionThreshold) { - return new GMGImpl(initializationFrames, decisionThreshold); + return makePtr(initializationFrames, decisionThreshold); } #endif diff --git a/modules/cudabgsegm/src/mog.cpp b/modules/cudabgsegm/src/mog.cpp index 4abfed9768..c3712bca35 100644 --- a/modules/cudabgsegm/src/mog.cpp +++ b/modules/cudabgsegm/src/mog.cpp @@ -203,7 +203,7 @@ namespace Ptr cv::cuda::createBackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma) { - return new MOGImpl(history, nmixtures, backgroundRatio, noiseSigma); + return makePtr(history, nmixtures, backgroundRatio, noiseSigma); } #endif diff --git a/modules/cudabgsegm/src/mog2.cpp b/modules/cudabgsegm/src/mog2.cpp index c5ba5577ae..f1a4008a72 100644 --- a/modules/cudabgsegm/src/mog2.cpp +++ b/modules/cudabgsegm/src/mog2.cpp @@ -247,7 +247,7 @@ namespace Ptr cv::cuda::createBackgroundSubtractorMOG2(int history, double varThreshold, bool detectShadows) { - return new MOG2Impl(history, varThreshold, detectShadows); + return makePtr(history, varThreshold, detectShadows); } #endif diff --git a/modules/cudabgsegm/test/test_bgsegm.cpp b/modules/cudabgsegm/test/test_bgsegm.cpp index 6da0bba08e..3597e2c10c 100644 --- a/modules/cudabgsegm/test/test_bgsegm.cpp +++ b/modules/cudabgsegm/test/test_bgsegm.cpp @@ -70,7 +70,7 @@ using namespace cvtest; namespace cv { - template<> void Ptr::delete_obj() + template<> void DefaultDeleter::operator ()(CvBGStatModel* obj) const { cvReleaseBGStatModel(&obj); } diff --git a/modules/cudacodec/src/thread.cpp b/modules/cudacodec/src/thread.cpp index 24e8abd0dd..ef97032706 100644 --- a/modules/cudacodec/src/thread.cpp +++ b/modules/cudacodec/src/thread.cpp @@ -167,9 +167,4 @@ void cv::cudacodec::detail::Thread::sleep(int ms) #endif } -template <> void cv::Ptr::delete_obj() -{ - if (obj) delete obj; -} - #endif // HAVE_NVCUVID diff --git a/modules/cudacodec/src/thread.hpp b/modules/cudacodec/src/thread.hpp index 67e25dc0cd..25c2b2251b 100644 --- a/modules/cudacodec/src/thread.hpp +++ b/modules/cudacodec/src/thread.hpp @@ -67,8 +67,4 @@ private: }}} -namespace cv { - template <> void Ptr::delete_obj(); -} - #endif // __THREAD_WRAPPERS_HPP__ diff --git a/modules/cudafilters/src/filtering.cpp b/modules/cudafilters/src/filtering.cpp index cabc0013a3..2ab35ccee5 100644 --- a/modules/cudafilters/src/filtering.cpp +++ b/modules/cudafilters/src/filtering.cpp @@ -169,7 +169,7 @@ Ptr cv::cuda::createBoxFilter(int srcType, int dstType, Size ksize, Poin dstType = CV_MAKE_TYPE(CV_MAT_DEPTH(dstType), CV_MAT_CN(srcType)); - return new NPPBoxFilter(srcType, dstType, ksize, anchor, borderMode, borderVal); + return makePtr(srcType, dstType, ksize, anchor, borderMode, borderVal); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -277,7 +277,7 @@ Ptr cv::cuda::createLinearFilter(int srcType, int dstType, InputArray ke dstType = CV_MAKE_TYPE(CV_MAT_DEPTH(dstType), CV_MAT_CN(srcType)); - return new LinearFilter(srcType, dstType, kernel, anchor, borderMode, borderVal); + return makePtr(srcType, dstType, kernel, anchor, borderMode, borderVal); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -428,7 +428,7 @@ Ptr cv::cuda::createSeparableLinearFilter(int srcType, int dstType, Inpu if (columnBorderMode < 0) columnBorderMode = rowBorderMode; - return new SeparableLinearFilter(srcType, dstType, rowKernel, columnKernel, anchor, rowBorderMode, columnBorderMode); + return makePtr(srcType, dstType, rowKernel, columnKernel, anchor, rowBorderMode, columnBorderMode); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -748,27 +748,27 @@ Ptr cv::cuda::createMorphologyFilter(int op, int srcType, InputArray ker { case MORPH_ERODE: case MORPH_DILATE: - return new MorphologyFilter(op, srcType, kernel, anchor, iterations); + return makePtr(op, srcType, kernel, anchor, iterations); break; case MORPH_OPEN: - return new MorphologyOpenFilter(srcType, kernel, anchor, iterations); + return makePtr(srcType, kernel, anchor, iterations); break; case MORPH_CLOSE: - return new MorphologyCloseFilter(srcType, kernel, anchor, iterations); + return makePtr(srcType, kernel, anchor, iterations); break; case MORPH_GRADIENT: - return new MorphologyGradientFilter(srcType, kernel, anchor, iterations); + return makePtr(srcType, kernel, anchor, iterations); break; case MORPH_TOPHAT: - return new MorphologyTophatFilter(srcType, kernel, anchor, iterations); + return makePtr(srcType, kernel, anchor, iterations); break; case MORPH_BLACKHAT: - return new MorphologyBlackhatFilter(srcType, kernel, anchor, iterations); + return makePtr(srcType, kernel, anchor, iterations); break; default: @@ -782,7 +782,7 @@ Ptr cv::cuda::createMorphologyFilter(int op, int srcType, InputArray ker namespace { - enum + enum RankType { RANK_MAX, RANK_MIN @@ -862,12 +862,12 @@ namespace Ptr cv::cuda::createBoxMaxFilter(int srcType, Size ksize, Point anchor, int borderMode, Scalar borderVal) { - return new NPPRankFilter(RANK_MAX, srcType, ksize, anchor, borderMode, borderVal); + return makePtr(RANK_MAX, srcType, ksize, anchor, borderMode, borderVal); } Ptr cv::cuda::createBoxMinFilter(int srcType, Size ksize, Point anchor, int borderMode, Scalar borderVal) { - return new NPPRankFilter(RANK_MIN, srcType, ksize, anchor, borderMode, borderVal); + return makePtr(RANK_MIN, srcType, ksize, anchor, borderMode, borderVal); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -931,7 +931,7 @@ namespace Ptr cv::cuda::createRowSumFilter(int srcType, int dstType, int ksize, int anchor, int borderMode, Scalar borderVal) { - return new NppRowSumFilter(srcType, dstType, ksize, anchor, borderMode, borderVal); + return makePtr(srcType, dstType, ksize, anchor, borderMode, borderVal); } namespace @@ -992,7 +992,7 @@ namespace Ptr cv::cuda::createColumnSumFilter(int srcType, int dstType, int ksize, int anchor, int borderMode, Scalar borderVal) { - return new NppColumnSumFilter(srcType, dstType, ksize, anchor, borderMode, borderVal); + return makePtr(srcType, dstType, ksize, anchor, borderMode, borderVal); } #endif diff --git a/modules/cudaimgproc/src/canny.cpp b/modules/cudaimgproc/src/canny.cpp index e24407358d..b22094d603 100644 --- a/modules/cudaimgproc/src/canny.cpp +++ b/modules/cudaimgproc/src/canny.cpp @@ -228,7 +228,7 @@ namespace Ptr cv::cuda::createCannyEdgeDetector(double low_thresh, double high_thresh, int apperture_size, bool L2gradient) { - return new CannyImpl(low_thresh, high_thresh, apperture_size, L2gradient); + return makePtr(low_thresh, high_thresh, apperture_size, L2gradient); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/corners.cpp b/modules/cudaimgproc/src/corners.cpp index 42cfa705cf..aa8867f0ef 100644 --- a/modules/cudaimgproc/src/corners.cpp +++ b/modules/cudaimgproc/src/corners.cpp @@ -178,12 +178,12 @@ namespace Ptr cv::cuda::createHarrisCorner(int srcType, int blockSize, int ksize, double k, int borderType) { - return new Harris(srcType, blockSize, ksize, k, borderType); + return makePtr(srcType, blockSize, ksize, k, borderType); } Ptr cv::cuda::createMinEigenValCorner(int srcType, int blockSize, int ksize, int borderType) { - return new MinEigenVal(srcType, blockSize, ksize, borderType); + return makePtr(srcType, blockSize, ksize, borderType); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/generalized_hough.cpp b/modules/cudaimgproc/src/generalized_hough.cpp index f6c7d7f202..d68b76e625 100644 --- a/modules/cudaimgproc/src/generalized_hough.cpp +++ b/modules/cudaimgproc/src/generalized_hough.cpp @@ -554,7 +554,7 @@ namespace Ptr cv::cuda::createGeneralizedHoughBallard() { - return new GeneralizedHoughBallardImpl; + return makePtr(); } // GeneralizedHoughGuil @@ -900,7 +900,7 @@ namespace Ptr cv::cuda::createGeneralizedHoughGuil() { - return new GeneralizedHoughGuilImpl; + return makePtr(); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/gftt.cpp b/modules/cudaimgproc/src/gftt.cpp index 094e67a674..243665083a 100644 --- a/modules/cudaimgproc/src/gftt.cpp +++ b/modules/cudaimgproc/src/gftt.cpp @@ -209,7 +209,8 @@ namespace Ptr cv::cuda::createGoodFeaturesToTrackDetector(int srcType, int maxCorners, double qualityLevel, double minDistance, int blockSize, bool useHarrisDetector, double harrisK) { - return new GoodFeaturesToTrackDetector(srcType, maxCorners, qualityLevel, minDistance, blockSize, useHarrisDetector, harrisK); + return Ptr( + new GoodFeaturesToTrackDetector(srcType, maxCorners, qualityLevel, minDistance, blockSize, useHarrisDetector, harrisK)); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/histogram.cpp b/modules/cudaimgproc/src/histogram.cpp index 471578ddac..37edd6e0d1 100644 --- a/modules/cudaimgproc/src/histogram.cpp +++ b/modules/cudaimgproc/src/histogram.cpp @@ -257,7 +257,7 @@ namespace cv::Ptr cv::cuda::createCLAHE(double clipLimit, cv::Size tileGridSize) { - return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height); + return makePtr(clipLimit, tileGridSize.width, tileGridSize.height); } //////////////////////////////////////////////////////////////////////// diff --git a/modules/cudaimgproc/src/hough_circles.cpp b/modules/cudaimgproc/src/hough_circles.cpp index b31288953f..0cf94a63d1 100644 --- a/modules/cudaimgproc/src/hough_circles.cpp +++ b/modules/cudaimgproc/src/hough_circles.cpp @@ -291,7 +291,7 @@ namespace Ptr cv::cuda::createHoughCirclesDetector(float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles) { - return new HoughCirclesDetectorImpl(dp, minDist, cannyThreshold, votesThreshold, minRadius, maxRadius, maxCircles); + return makePtr(dp, minDist, cannyThreshold, votesThreshold, minRadius, maxRadius, maxCircles); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/hough_lines.cpp b/modules/cudaimgproc/src/hough_lines.cpp index 6bfa65a185..b9f159a9cb 100644 --- a/modules/cudaimgproc/src/hough_lines.cpp +++ b/modules/cudaimgproc/src/hough_lines.cpp @@ -196,7 +196,7 @@ namespace Ptr cv::cuda::createHoughLinesDetector(float rho, float theta, int threshold, bool doSort, int maxLines) { - return new HoughLinesDetectorImpl(rho, theta, threshold, doSort, maxLines); + return makePtr(rho, theta, threshold, doSort, maxLines); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/hough_segments.cpp b/modules/cudaimgproc/src/hough_segments.cpp index dc3141130a..2434f6d26d 100644 --- a/modules/cudaimgproc/src/hough_segments.cpp +++ b/modules/cudaimgproc/src/hough_segments.cpp @@ -177,7 +177,7 @@ namespace Ptr cv::cuda::createHoughSegmentDetector(float rho, float theta, int minLineLength, int maxLineGap, int maxLines) { - return new HoughSegmentDetectorImpl(rho, theta, minLineLength, maxLineGap, maxLines); + return makePtr(rho, theta, minLineLength, maxLineGap, maxLines); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudaimgproc/src/match_template.cpp b/modules/cudaimgproc/src/match_template.cpp index d4406c8b13..19d091588b 100644 --- a/modules/cudaimgproc/src/match_template.cpp +++ b/modules/cudaimgproc/src/match_template.cpp @@ -607,10 +607,10 @@ Ptr cv::cuda::createTemplateMatching(int srcType, int me switch (method) { case TM_SQDIFF: - return new Match_SQDIFF_32F; + return makePtr(); case TM_CCORR: - return new Match_CCORR_32F(user_block_size); + return makePtr(user_block_size); default: CV_Error( Error::StsBadFlag, "Unsopported method" ); @@ -622,22 +622,22 @@ Ptr cv::cuda::createTemplateMatching(int srcType, int me switch (method) { case TM_SQDIFF: - return new Match_SQDIFF_8U(user_block_size); + return makePtr(user_block_size); case TM_SQDIFF_NORMED: - return new Match_SQDIFF_NORMED_8U(user_block_size); + return makePtr(user_block_size); case TM_CCORR: - return new Match_CCORR_8U(user_block_size); + return makePtr(user_block_size); case TM_CCORR_NORMED: - return new Match_CCORR_NORMED_8U(user_block_size); + return makePtr(user_block_size); case TM_CCOEFF: - return new Match_CCOEFF_8U(user_block_size); + return makePtr(user_block_size); case TM_CCOEFF_NORMED: - return new Match_CCOEFF_NORMED_8U(user_block_size); + return makePtr(user_block_size); default: CV_Error( Error::StsBadFlag, "Unsopported method" ); diff --git a/modules/cudalegacy/src/cuda/NCVHaarObjectDetection.cu b/modules/cudalegacy/src/cuda/NCVHaarObjectDetection.cu index fb276258f6..e6e5e52793 100644 --- a/modules/cudalegacy/src/cuda/NCVHaarObjectDetection.cu +++ b/modules/cudalegacy/src/cuda/NCVHaarObjectDetection.cu @@ -2138,8 +2138,8 @@ static NCVStatus loadFromXML(const cv::String &filename, haarClassifierNodes.resize(0); haarFeatures.resize(0); - cv::Ptr oldCascade = (CvHaarClassifierCascade*)cvLoad(filename.c_str(), 0, 0, 0); - if (oldCascade.empty()) + cv::Ptr oldCascade((CvHaarClassifierCascade*)cvLoad(filename.c_str(), 0, 0, 0)); + if (!oldCascade) { return NCV_HAAR_XML_LOADING_EXCEPTION; } diff --git a/modules/cudastereo/src/disparity_bilateral_filter.cpp b/modules/cudastereo/src/disparity_bilateral_filter.cpp index 7b55dcfc7b..75cbce48a9 100644 --- a/modules/cudastereo/src/disparity_bilateral_filter.cpp +++ b/modules/cudastereo/src/disparity_bilateral_filter.cpp @@ -200,7 +200,7 @@ namespace Ptr cv::cuda::createDisparityBilateralFilter(int ndisp, int radius, int iters) { - return new DispBilateralFilterImpl(ndisp, radius, iters); + return makePtr(ndisp, radius, iters); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudastereo/src/stereobm.cpp b/modules/cudastereo/src/stereobm.cpp index deacc0eedf..1cfc0a644f 100644 --- a/modules/cudastereo/src/stereobm.cpp +++ b/modules/cudastereo/src/stereobm.cpp @@ -179,7 +179,7 @@ namespace Ptr cv::cuda::createStereoBM(int numDisparities, int blockSize) { - return new StereoBMImpl(numDisparities, blockSize); + return makePtr(numDisparities, blockSize); } #endif /* !defined (HAVE_CUDA) */ diff --git a/modules/cudastereo/src/stereobp.cpp b/modules/cudastereo/src/stereobp.cpp index 95be219f9c..953674b904 100644 --- a/modules/cudastereo/src/stereobp.cpp +++ b/modules/cudastereo/src/stereobp.cpp @@ -361,7 +361,7 @@ namespace Ptr cv::cuda::createStereoBeliefPropagation(int ndisp, int iters, int levels, int msg_type) { - return new StereoBPImpl(ndisp, iters, levels, msg_type); + return makePtr(ndisp, iters, levels, msg_type); } void cv::cuda::StereoBeliefPropagation::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels) diff --git a/modules/cudastereo/src/stereocsbp.cpp b/modules/cudastereo/src/stereocsbp.cpp index 046bbfe95e..474562baf2 100644 --- a/modules/cudastereo/src/stereocsbp.cpp +++ b/modules/cudastereo/src/stereocsbp.cpp @@ -366,7 +366,7 @@ namespace Ptr cv::cuda::createStereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane, int msg_type) { - return new StereoCSBPImpl(ndisp, iters, levels, nr_plane, msg_type); + return makePtr(ndisp, iters, levels, nr_plane, msg_type); } void cv::cuda::StereoConstantSpaceBP::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane) diff --git a/modules/cudawarping/src/pyramids.cpp b/modules/cudawarping/src/pyramids.cpp index 5f37c392b7..edb1500adb 100644 --- a/modules/cudawarping/src/pyramids.cpp +++ b/modules/cudawarping/src/pyramids.cpp @@ -237,7 +237,7 @@ Ptr cv::cuda::createImagePyramid(InputArray img, int nLayers, Stre throw_no_cuda(); return Ptr(); #else - return new ImagePyramidImpl(img, nLayers, stream); + return Ptr(new ImagePyramidImpl(img, nLayers, stream)); #endif } diff --git a/modules/features2d/include/opencv2/features2d.hpp b/modules/features2d/include/opencv2/features2d.hpp index 4e3f3b80a6..af687e3085 100644 --- a/modules/features2d/include/opencv2/features2d.hpp +++ b/modules/features2d/include/opencv2/features2d.hpp @@ -646,7 +646,7 @@ public: * gridRows Grid rows count. * gridCols Grid column count. */ - CV_WRAP GridAdaptedFeatureDetector( const Ptr& detector=0, + CV_WRAP GridAdaptedFeatureDetector( const Ptr& detector=Ptr(), int maxTotalKeypoints=1000, int gridRows=4, int gridCols=4 ); @@ -1143,8 +1143,8 @@ protected: class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher { public: - CV_WRAP FlannBasedMatcher( const Ptr& indexParams=new flann::KDTreeIndexParams(), - const Ptr& searchParams=new flann::SearchParams() ); + CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), + const Ptr& searchParams=makePtr() ); virtual void add( const std::vector& descriptors ); virtual void clear(); diff --git a/modules/features2d/src/brisk.cpp b/modules/features2d/src/brisk.cpp index 9e017d5253..76bded666b 100644 --- a/modules/features2d/src/brisk.cpp +++ b/modules/features2d/src/brisk.cpp @@ -2003,7 +2003,7 @@ BriskLayer::BriskLayer(const cv::Mat& img_in, float scale_in, float offset_in) scale_ = scale_in; offset_ = offset_in; // create an agast detector - fast_9_16_ = new FastFeatureDetector(1, true, FastFeatureDetector::TYPE_9_16); + fast_9_16_ = makePtr(1, true, FastFeatureDetector::TYPE_9_16); makeOffsets(pixel_5_8_, (int)img_.step, 8); makeOffsets(pixel_9_16_, (int)img_.step, 16); } @@ -2025,7 +2025,7 @@ BriskLayer::BriskLayer(const BriskLayer& layer, int mode) offset_ = 0.5f * scale_ - 0.5f; } scores_ = cv::Mat::zeros(img_.rows, img_.cols, CV_8U); - fast_9_16_ = new FastFeatureDetector(1, false, FastFeatureDetector::TYPE_9_16); + fast_9_16_ = makePtr(1, false, FastFeatureDetector::TYPE_9_16); makeOffsets(pixel_5_8_, (int)img_.step, 8); makeOffsets(pixel_9_16_, (int)img_.step, 16); } diff --git a/modules/features2d/src/descriptors.cpp b/modules/features2d/src/descriptors.cpp index 4f434032ec..b79768ae15 100644 --- a/modules/features2d/src/descriptors.cpp +++ b/modules/features2d/src/descriptors.cpp @@ -99,7 +99,7 @@ Ptr DescriptorExtractor::create(const String& descriptorExt { size_t pos = String("Opponent").size(); String type = descriptorExtractorType.substr(pos); - return new OpponentColorDescriptorExtractor(DescriptorExtractor::create(type)); + return makePtr(DescriptorExtractor::create(type)); } return Algorithm::create("Feature2D." + descriptorExtractorType); @@ -119,7 +119,7 @@ CV_WRAP void Feature2D::compute( const Mat& image, CV_OUT CV_IN_OUT std::vector< OpponentColorDescriptorExtractor::OpponentColorDescriptorExtractor( const Ptr& _descriptorExtractor ) : descriptorExtractor(_descriptorExtractor) { - CV_Assert( !descriptorExtractor.empty() ); + CV_Assert( descriptorExtractor ); } static void convertBGRImageToOpponentColorSpace( const Mat& bgrImage, std::vector& opponentChannels ) @@ -249,7 +249,7 @@ int OpponentColorDescriptorExtractor::descriptorType() const bool OpponentColorDescriptorExtractor::empty() const { - return descriptorExtractor.empty() || (DescriptorExtractor*)(descriptorExtractor)->empty(); + return !descriptorExtractor || descriptorExtractor->empty(); } } diff --git a/modules/features2d/src/detectors.cpp b/modules/features2d/src/detectors.cpp index c20d573552..63a882dd3f 100644 --- a/modules/features2d/src/detectors.cpp +++ b/modules/features2d/src/detectors.cpp @@ -90,19 +90,19 @@ Ptr FeatureDetector::create( const String& detectorType ) { if( detectorType.find("Grid") == 0 ) { - return new GridAdaptedFeatureDetector(FeatureDetector::create( + return makePtr(FeatureDetector::create( detectorType.substr(strlen("Grid")))); } if( detectorType.find("Pyramid") == 0 ) { - return new PyramidAdaptedFeatureDetector(FeatureDetector::create( + return makePtr(FeatureDetector::create( detectorType.substr(strlen("Pyramid")))); } if( detectorType.find("Dynamic") == 0 ) { - return new DynamicAdaptedFeatureDetector(AdjusterAdapter::create( + return makePtr(AdjusterAdapter::create( detectorType.substr(strlen("Dynamic")))); } @@ -190,7 +190,7 @@ GridAdaptedFeatureDetector::GridAdaptedFeatureDetector( const Ptrempty(); + return !detector || detector->empty(); } struct ResponseComparator @@ -295,7 +295,7 @@ PyramidAdaptedFeatureDetector::PyramidAdaptedFeatureDetector( const Ptrempty(); + return !detector || detector->empty(); } void PyramidAdaptedFeatureDetector::detectImpl( const Mat& image, std::vector& keypoints, const Mat& mask ) const diff --git a/modules/features2d/src/dynamic.cpp b/modules/features2d/src/dynamic.cpp index d08434da46..6bd6ab4de8 100644 --- a/modules/features2d/src/dynamic.cpp +++ b/modules/features2d/src/dynamic.cpp @@ -51,7 +51,7 @@ DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector(const Ptrempty(); + return !adjuster_ || adjuster_->empty(); } void DynamicAdaptedFeatureDetector::detectImpl(const Mat& image, std::vector& keypoints, const Mat& mask) const @@ -124,7 +124,7 @@ bool FastAdjuster::good() const Ptr FastAdjuster::clone() const { - Ptr cloned_obj = new FastAdjuster( init_thresh_, nonmax_, min_thresh_, max_thresh_ ); + Ptr cloned_obj(new FastAdjuster( init_thresh_, nonmax_, min_thresh_, max_thresh_ )); return cloned_obj; } @@ -158,7 +158,7 @@ bool StarAdjuster::good() const Ptr StarAdjuster::clone() const { - Ptr cloned_obj = new StarAdjuster( init_thresh_, min_thresh_, max_thresh_ ); + Ptr cloned_obj(new StarAdjuster( init_thresh_, min_thresh_, max_thresh_ )); return cloned_obj; } @@ -195,7 +195,7 @@ bool SurfAdjuster::good() const Ptr SurfAdjuster::clone() const { - Ptr cloned_obj = new SurfAdjuster( init_thresh_, min_thresh_, max_thresh_ ); + Ptr cloned_obj(new SurfAdjuster( init_thresh_, min_thresh_, max_thresh_ )); return cloned_obj; } @@ -205,15 +205,15 @@ Ptr AdjusterAdapter::create( const String& detectorType ) if( !detectorType.compare( "FAST" ) ) { - adapter = new FastAdjuster(); + adapter = makePtr(); } else if( !detectorType.compare( "STAR" ) ) { - adapter = new StarAdjuster(); + adapter = makePtr(); } else if( !detectorType.compare( "SURF" ) ) { - adapter = new SurfAdjuster(); + adapter = makePtr(); } return adapter; diff --git a/modules/features2d/src/evaluation.cpp b/modules/features2d/src/evaluation.cpp index 369ba44c91..5bde951d60 100644 --- a/modules/features2d/src/evaluation.cpp +++ b/modules/features2d/src/evaluation.cpp @@ -461,7 +461,7 @@ void cv::evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H keypoints1 = _keypoints1 != 0 ? _keypoints1 : &buf1; keypoints2 = _keypoints2 != 0 ? _keypoints2 : &buf2; - if( (keypoints1->empty() || keypoints2->empty()) && fdetector.empty() ) + if( (keypoints1->empty() || keypoints2->empty()) && !fdetector ) CV_Error( Error::StsBadArg, "fdetector must not be empty when keypoints1 or keypoints2 is empty" ); if( keypoints1->empty() ) @@ -575,7 +575,7 @@ void cv::evaluateGenericDescriptorMatcher( const Mat& img1, const Mat& img2, con if( keypoints1.empty() ) CV_Error( Error::StsBadArg, "keypoints1 must not be empty" ); - if( matches1to2->empty() && dmatcher.empty() ) + if( matches1to2->empty() && !dmatcher ) CV_Error( Error::StsBadArg, "dmatch must not be empty when matches1to2 is empty" ); bool computeKeypoints2ByPrj = keypoints2.empty(); diff --git a/modules/features2d/src/matchers.cpp b/modules/features2d/src/matchers.cpp index 54da1833e4..087c6a78bd 100644 --- a/modules/features2d/src/matchers.cpp +++ b/modules/features2d/src/matchers.cpp @@ -326,7 +326,7 @@ BFMatcher::BFMatcher( int _normType, bool _crossCheck ) Ptr BFMatcher::clone( bool emptyTrainData ) const { - BFMatcher* matcher = new BFMatcher(normType, crossCheck); + Ptr matcher = makePtr(normType, crossCheck); if( !emptyTrainData ) { matcher->trainDescCollection.resize(trainDescCollection.size()); @@ -458,31 +458,31 @@ void BFMatcher::radiusMatchImpl( const Mat& queryDescriptors, std::vector DescriptorMatcher::create( const String& descriptorMatcherType ) { - DescriptorMatcher* dm = 0; + Ptr dm; if( !descriptorMatcherType.compare( "FlannBased" ) ) { - dm = new FlannBasedMatcher(); + dm = makePtr(); } else if( !descriptorMatcherType.compare( "BruteForce" ) ) // L2 { - dm = new BFMatcher(NORM_L2); + dm = makePtr(int(NORM_L2)); // anonymous enums can't be template parameters } else if( !descriptorMatcherType.compare( "BruteForce-SL2" ) ) // Squared L2 { - dm = new BFMatcher(NORM_L2SQR); + dm = makePtr(int(NORM_L2SQR)); } else if( !descriptorMatcherType.compare( "BruteForce-L1" ) ) { - dm = new BFMatcher(NORM_L1); + dm = makePtr(int(NORM_L1)); } else if( !descriptorMatcherType.compare("BruteForce-Hamming") || !descriptorMatcherType.compare("BruteForce-HammingLUT") ) { - dm = new BFMatcher(NORM_HAMMING); + dm = makePtr(int(NORM_HAMMING)); } else if( !descriptorMatcherType.compare("BruteForce-Hamming(2)") ) { - dm = new BFMatcher(NORM_HAMMING2); + dm = makePtr(int(NORM_HAMMING2)); } else CV_Error( Error::StsBadArg, "Unknown matcher name" ); @@ -497,8 +497,8 @@ Ptr DescriptorMatcher::create( const String& descriptorMatche FlannBasedMatcher::FlannBasedMatcher( const Ptr& _indexParams, const Ptr& _searchParams ) : indexParams(_indexParams), searchParams(_searchParams), addedDescCount(0) { - CV_Assert( !_indexParams.empty() ); - CV_Assert( !_searchParams.empty() ); + CV_Assert( _indexParams ); + CV_Assert( _searchParams ); } void FlannBasedMatcher::add( const std::vector& descriptors ) @@ -522,17 +522,17 @@ void FlannBasedMatcher::clear() void FlannBasedMatcher::train() { - if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount ) + if( !flannIndex || mergedDescriptors.size() < addedDescCount ) { mergedDescriptors.set( trainDescCollection ); - flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams ); + flannIndex = makePtr( mergedDescriptors.getDescriptors(), *indexParams ); } } void FlannBasedMatcher::read( const FileNode& fn) { - if (indexParams.empty()) - indexParams = new flann::IndexParams(); + if (!indexParams) + indexParams = makePtr(); FileNode ip = fn["indexParams"]; CV_Assert(ip.type() == FileNode::SEQ); @@ -570,8 +570,8 @@ void FlannBasedMatcher::read( const FileNode& fn) }; } - if (searchParams.empty()) - searchParams = new flann::SearchParams(); + if (!searchParams) + searchParams = makePtr(); FileNode sp = fn["searchParams"]; CV_Assert(sp.type() == FileNode::SEQ); @@ -725,7 +725,7 @@ bool FlannBasedMatcher::isMaskSupported() const Ptr FlannBasedMatcher::clone( bool emptyTrainData ) const { - FlannBasedMatcher* matcher = new FlannBasedMatcher(indexParams, searchParams); + Ptr matcher = makePtr(indexParams, searchParams); if( !emptyTrainData ) { CV_Error( Error::StsNotImplemented, "deep clone functionality is not implemented, because " @@ -1066,7 +1066,7 @@ Ptr GenericDescriptorMatcher::create( const String& ge Ptr descriptorMatcher = Algorithm::create("DescriptorMatcher." + genericDescritptorMatcherType); - if( !paramsFilename.empty() && !descriptorMatcher.empty() ) + if( !paramsFilename.empty() && descriptorMatcher ) { FileStorage fs = FileStorage( paramsFilename, FileStorage::READ ); if( fs.isOpened() ) @@ -1086,7 +1086,7 @@ VectorDescriptorMatcher::VectorDescriptorMatcher( const Ptr const Ptr& _matcher ) : extractor( _extractor ), matcher( _matcher ) { - CV_Assert( !extractor.empty() && !matcher.empty() ); + CV_Assert( extractor && matcher ); } VectorDescriptorMatcher::~VectorDescriptorMatcher() @@ -1152,14 +1152,14 @@ void VectorDescriptorMatcher::write (FileStorage& fs) const bool VectorDescriptorMatcher::empty() const { - return extractor.empty() || extractor->empty() || - matcher.empty() || matcher->empty(); + return !extractor || extractor->empty() || + !matcher || matcher->empty(); } Ptr VectorDescriptorMatcher::clone( bool emptyTrainData ) const { // TODO clone extractor - return new VectorDescriptorMatcher( extractor, matcher->clone(emptyTrainData) ); + return makePtr( extractor, matcher->clone(emptyTrainData) ); } } diff --git a/modules/features2d/test/test_descriptors_regression.cpp b/modules/features2d/test/test_descriptors_regression.cpp index 548e818840..08eb59eae2 100644 --- a/modules/features2d/test/test_descriptors_regression.cpp +++ b/modules/features2d/test/test_descriptors_regression.cpp @@ -141,7 +141,7 @@ protected: void emptyDataTest() { - assert( !dextractor.empty() ); + assert( dextractor ); // One image. Mat image; @@ -186,7 +186,7 @@ protected: void regressionTest() { - assert( !dextractor.empty() ); + assert( dextractor ); // Read the test image. string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME; @@ -267,7 +267,7 @@ protected: void run(int) { createDescriptorExtractor(); - if( dextractor.empty() ) + if( !dextractor ) { ts->printf(cvtest::TS::LOG, "Descriptor extractor is empty.\n"); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); diff --git a/modules/features2d/test/test_detectors_regression.cpp b/modules/features2d/test/test_detectors_regression.cpp index 9a88c42f7b..8f34913a9a 100644 --- a/modules/features2d/test/test_detectors_regression.cpp +++ b/modules/features2d/test/test_detectors_regression.cpp @@ -230,7 +230,7 @@ void CV_FeatureDetectorTest::regressionTest() void CV_FeatureDetectorTest::run( int /*start_from*/ ) { - if( fdetector.empty() ) + if( !fdetector ) { ts->printf( cvtest::TS::LOG, "Feature detector is empty.\n" ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); diff --git a/modules/features2d/test/test_keypoints.cpp b/modules/features2d/test/test_keypoints.cpp index c689cd3722..e15d4fa17f 100644 --- a/modules/features2d/test/test_keypoints.cpp +++ b/modules/features2d/test/test_keypoints.cpp @@ -62,7 +62,7 @@ protected: virtual void run(int) { cv::initModule_features2d(); - CV_Assert(!detector.empty()); + CV_Assert(detector); string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME; // Read the test image. diff --git a/modules/features2d/test/test_rotation_and_scale_invariance.cpp b/modules/features2d/test/test_rotation_and_scale_invariance.cpp index dd0e48e7d3..adfe42804b 100644 --- a/modules/features2d/test/test_rotation_and_scale_invariance.cpp +++ b/modules/features2d/test/test_rotation_and_scale_invariance.cpp @@ -196,7 +196,7 @@ public: minKeyPointMatchesRatio(_minKeyPointMatchesRatio), minAngleInliersRatio(_minAngleInliersRatio) { - CV_Assert(!featureDetector.empty()); + CV_Assert(featureDetector); } protected: @@ -307,8 +307,8 @@ public: normType(_normType), minDescInliersRatio(_minDescInliersRatio) { - CV_Assert(!featureDetector.empty()); - CV_Assert(!descriptorExtractor.empty()); + CV_Assert(featureDetector); + CV_Assert(descriptorExtractor); } protected: @@ -392,7 +392,7 @@ public: minKeyPointMatchesRatio(_minKeyPointMatchesRatio), minScaleInliersRatio(_minScaleInliersRatio) { - CV_Assert(!featureDetector.empty()); + CV_Assert(featureDetector); } protected: @@ -510,8 +510,8 @@ public: normType(_normType), minDescInliersRatio(_minDescInliersRatio) { - CV_Assert(!featureDetector.empty()); - CV_Assert(!descriptorExtractor.empty()); + CV_Assert(featureDetector); + CV_Assert(descriptorExtractor); } protected: diff --git a/modules/highgui/doc/user_interface.rst b/modules/highgui/doc/user_interface.rst index 7573a1f7c8..8e9a4c3075 100644 --- a/modules/highgui/doc/user_interface.rst +++ b/modules/highgui/doc/user_interface.rst @@ -81,7 +81,7 @@ The function ``imshow`` displays an image in the specified window. If the window If window was created with OpenGL support, ``imshow`` also support :ocv:class:`ogl::Buffer` , :ocv:class:`ogl::Texture2D` and :ocv:class:`cuda::GpuMat` as input. -.. note:: This function should be followed by ``waitKey`` function which displays the image for specified milliseconds. Otherwise, it won't display the image. +.. note:: This function should be followed by ``waitKey`` function which displays the image for specified milliseconds. Otherwise, it won't display the image. For example, ``waitKey(0)`` will display the window infinitely until any keypress (it is suitable for image display). ``waitKey(25)`` will display a frame for 25 ms, after which display will be automatically closed. (If you put it in a loop to read videos, it will display the video frame-by-frame) namedWindow diff --git a/modules/highgui/include/opencv2/highgui.hpp b/modules/highgui/include/opencv2/highgui.hpp index c20cf883ec..c4fc73a81f 100644 --- a/modules/highgui/include/opencv2/highgui.hpp +++ b/modules/highgui/include/opencv2/highgui.hpp @@ -544,8 +544,8 @@ protected: Ptr writer; }; -template<> CV_EXPORTS void Ptr::delete_obj(); -template<> CV_EXPORTS void Ptr::delete_obj(); +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvCapture* obj) const; +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvVideoWriter* obj) const; } // cv diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp index 453f1dd122..be62ce9d38 100644 --- a/modules/highgui/src/cap.cpp +++ b/modules/highgui/src/cap.cpp @@ -49,10 +49,10 @@ namespace cv { -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvCapture* obj) const { cvReleaseCapture(&obj); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvVideoWriter* obj) const { cvReleaseVideoWriter(&obj); } } @@ -492,14 +492,14 @@ VideoCapture::~VideoCapture() bool VideoCapture::open(const String& filename) { if (isOpened()) release(); - cap = cvCreateFileCapture(filename.c_str()); + cap.reset(cvCreateFileCapture(filename.c_str())); return isOpened(); } bool VideoCapture::open(int device) { if (isOpened()) release(); - cap = cvCreateCameraCapture(device); + cap.reset(cvCreateCameraCapture(device)); return isOpened(); } @@ -578,7 +578,7 @@ VideoWriter::~VideoWriter() bool VideoWriter::open(const String& filename, int _fourcc, double fps, Size frameSize, bool isColor) { - writer = cvCreateVideoWriter(filename.c_str(), _fourcc, fps, frameSize, isColor); + writer.reset(cvCreateVideoWriter(filename.c_str(), _fourcc, fps, frameSize, isColor)); return isOpened(); } diff --git a/modules/highgui/src/grfmt_bmp.cpp b/modules/highgui/src/grfmt_bmp.cpp index 131e84eca5..f7147b5fc1 100644 --- a/modules/highgui/src/grfmt_bmp.cpp +++ b/modules/highgui/src/grfmt_bmp.cpp @@ -70,7 +70,7 @@ void BmpDecoder::close() ImageDecoder BmpDecoder::newDecoder() const { - return new BmpDecoder; + return makePtr(); } bool BmpDecoder::readHeader() @@ -496,7 +496,7 @@ BmpEncoder::~BmpEncoder() ImageEncoder BmpEncoder::newEncoder() const { - return new BmpEncoder; + return makePtr(); } bool BmpEncoder::write( const Mat& img, const std::vector& ) diff --git a/modules/highgui/src/grfmt_exr.cpp b/modules/highgui/src/grfmt_exr.cpp index 33d0ad0f56..079de58340 100644 --- a/modules/highgui/src/grfmt_exr.cpp +++ b/modules/highgui/src/grfmt_exr.cpp @@ -551,7 +551,7 @@ void ExrDecoder::RGBToGray( float *in, float *out ) ImageDecoder ExrDecoder::newDecoder() const { - return new ExrDecoder; + return makePtr(); } /////////////////////// ExrEncoder /////////////////// @@ -726,7 +726,7 @@ bool ExrEncoder::write( const Mat& img, const std::vector& ) ImageEncoder ExrEncoder::newEncoder() const { - return new ExrEncoder; + return makePtr(); } } diff --git a/modules/highgui/src/grfmt_jpeg.cpp b/modules/highgui/src/grfmt_jpeg.cpp index 09db677a43..28c52e8598 100644 --- a/modules/highgui/src/grfmt_jpeg.cpp +++ b/modules/highgui/src/grfmt_jpeg.cpp @@ -208,7 +208,7 @@ void JpegDecoder::close() ImageDecoder JpegDecoder::newDecoder() const { - return new JpegDecoder; + return makePtr(); } bool JpegDecoder::readHeader() @@ -539,7 +539,7 @@ JpegEncoder::~JpegEncoder() ImageEncoder JpegEncoder::newEncoder() const { - return new JpegEncoder; + return makePtr(); } bool JpegEncoder::write( const Mat& img, const std::vector& params ) diff --git a/modules/highgui/src/grfmt_jpeg2000.cpp b/modules/highgui/src/grfmt_jpeg2000.cpp index 4a48e81a65..d711846ce8 100644 --- a/modules/highgui/src/grfmt_jpeg2000.cpp +++ b/modules/highgui/src/grfmt_jpeg2000.cpp @@ -88,7 +88,7 @@ Jpeg2KDecoder::~Jpeg2KDecoder() ImageDecoder Jpeg2KDecoder::newDecoder() const { - return new Jpeg2KDecoder; + return makePtr(); } void Jpeg2KDecoder::close() @@ -403,7 +403,7 @@ Jpeg2KEncoder::~Jpeg2KEncoder() ImageEncoder Jpeg2KEncoder::newEncoder() const { - return new Jpeg2KEncoder; + return makePtr(); } bool Jpeg2KEncoder::isFormatSupported( int depth ) const diff --git a/modules/highgui/src/grfmt_png.cpp b/modules/highgui/src/grfmt_png.cpp index c784d5a5b3..4d5c7793ea 100644 --- a/modules/highgui/src/grfmt_png.cpp +++ b/modules/highgui/src/grfmt_png.cpp @@ -101,7 +101,7 @@ PngDecoder::~PngDecoder() ImageDecoder PngDecoder::newDecoder() const { - return new PngDecoder; + return makePtr(); } void PngDecoder::close() @@ -317,7 +317,7 @@ bool PngEncoder::isFormatSupported( int depth ) const ImageEncoder PngEncoder::newEncoder() const { - return new PngEncoder; + return makePtr(); } diff --git a/modules/highgui/src/grfmt_pxm.cpp b/modules/highgui/src/grfmt_pxm.cpp index 0acf195dd5..425a296cb9 100644 --- a/modules/highgui/src/grfmt_pxm.cpp +++ b/modules/highgui/src/grfmt_pxm.cpp @@ -116,7 +116,7 @@ bool PxMDecoder::checkSignature( const String& signature ) const ImageDecoder PxMDecoder::newDecoder() const { - return new PxMDecoder; + return makePtr(); } void PxMDecoder::close() @@ -357,7 +357,7 @@ PxMEncoder::~PxMEncoder() ImageEncoder PxMEncoder::newEncoder() const { - return new PxMEncoder; + return makePtr(); } diff --git a/modules/highgui/src/grfmt_sunras.cpp b/modules/highgui/src/grfmt_sunras.cpp index a16e5d8004..b67400f337 100644 --- a/modules/highgui/src/grfmt_sunras.cpp +++ b/modules/highgui/src/grfmt_sunras.cpp @@ -63,7 +63,7 @@ SunRasterDecoder::~SunRasterDecoder() ImageDecoder SunRasterDecoder::newDecoder() const { - return new SunRasterDecoder; + return makePtr(); } void SunRasterDecoder::close() @@ -388,7 +388,7 @@ SunRasterEncoder::SunRasterEncoder() ImageEncoder SunRasterEncoder::newEncoder() const { - return new SunRasterEncoder; + return makePtr(); } SunRasterEncoder::~SunRasterEncoder() diff --git a/modules/highgui/src/grfmt_tiff.cpp b/modules/highgui/src/grfmt_tiff.cpp index a0d53f3db8..d8937db251 100644 --- a/modules/highgui/src/grfmt_tiff.cpp +++ b/modules/highgui/src/grfmt_tiff.cpp @@ -108,7 +108,7 @@ int TiffDecoder::normalizeChannelsNumber(int channels) const ImageDecoder TiffDecoder::newDecoder() const { - return new TiffDecoder; + return makePtr(); } bool TiffDecoder::readHeader() @@ -400,7 +400,7 @@ TiffEncoder::~TiffEncoder() ImageEncoder TiffEncoder::newEncoder() const { - return new TiffEncoder; + return makePtr(); } bool TiffEncoder::isFormatSupported( int depth ) const diff --git a/modules/highgui/src/grfmt_webp.cpp b/modules/highgui/src/grfmt_webp.cpp index fd9682a79f..1c64adec60 100644 --- a/modules/highgui/src/grfmt_webp.cpp +++ b/modules/highgui/src/grfmt_webp.cpp @@ -90,7 +90,7 @@ bool WebPDecoder::checkSignature(const String & signature) const ImageDecoder WebPDecoder::newDecoder() const { - return new WebPDecoder; + return makePtr(); } bool WebPDecoder::readHeader() @@ -201,7 +201,7 @@ WebPEncoder::~WebPEncoder() { } ImageEncoder WebPEncoder::newEncoder() const { - return new WebPEncoder(); + return makePtr(); } bool WebPEncoder::write(const Mat& img, const std::vector& params) diff --git a/modules/highgui/src/loadsave.cpp b/modules/highgui/src/loadsave.cpp index a548df54de..58a0a6fbf7 100644 --- a/modules/highgui/src/loadsave.cpp +++ b/modules/highgui/src/loadsave.cpp @@ -58,35 +58,35 @@ struct ImageCodecInitializer { ImageCodecInitializer() { - decoders.push_back( new BmpDecoder ); - encoders.push_back( new BmpEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #ifdef HAVE_JPEG - decoders.push_back( new JpegDecoder ); - encoders.push_back( new JpegEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #endif #ifdef HAVE_WEBP - decoders.push_back( new WebPDecoder ); - encoders.push_back( new WebPEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #endif - decoders.push_back( new SunRasterDecoder ); - encoders.push_back( new SunRasterEncoder ); - decoders.push_back( new PxMDecoder ); - encoders.push_back( new PxMEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #ifdef HAVE_TIFF - decoders.push_back( new TiffDecoder ); + decoders.push_back( makePtr() ); #endif - encoders.push_back( new TiffEncoder ); + encoders.push_back( makePtr() ); #ifdef HAVE_PNG - decoders.push_back( new PngDecoder ); - encoders.push_back( new PngEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #endif #ifdef HAVE_JASPER - decoders.push_back( new Jpeg2KDecoder ); - encoders.push_back( new Jpeg2KEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #endif #ifdef HAVE_OPENEXR - decoders.push_back( new ExrDecoder ); - encoders.push_back( new ExrEncoder ); + decoders.push_back( makePtr() ); + encoders.push_back( makePtr() ); #endif } @@ -198,7 +198,7 @@ imread_( const String& filename, int flags, int hdrtype, Mat* mat=0 ) Mat temp, *data = &temp; ImageDecoder decoder = findDecoder(filename); - if( decoder.empty() ) + if( !decoder ) return 0; decoder->setSource(filename); if( !decoder->readHeader() ) @@ -269,7 +269,7 @@ static bool imwrite_( const String& filename, const Mat& image, CV_Assert( image.channels() == 1 || image.channels() == 3 || image.channels() == 4 ); ImageEncoder encoder = findEncoder( filename ); - if( encoder.empty() ) + if( !encoder ) CV_Error( CV_StsError, "could not find a writer for the specified extension" ); if( !encoder->isFormatSupported(image.depth()) ) @@ -309,7 +309,7 @@ imdecode_( const Mat& buf, int flags, int hdrtype, Mat* mat=0 ) String filename; ImageDecoder decoder = findDecoder(buf); - if( decoder.empty() ) + if( !decoder ) return 0; if( !decoder->setSource(buf) ) @@ -409,7 +409,7 @@ bool imencode( const String& ext, InputArray _image, CV_Assert( channels == 1 || channels == 3 || channels == 4 ); ImageEncoder encoder = findEncoder( ext ); - if( encoder.empty() ) + if( !encoder ) CV_Error( CV_StsError, "could not find encoder for the specified extension" ); if( !encoder->isFormatSupported(image.depth()) ) diff --git a/modules/highgui/test/test_framecount.cpp b/modules/highgui/test/test_framecount.cpp index 875ce6aca4..30f6e67ce6 100644 --- a/modules/highgui/test/test_framecount.cpp +++ b/modules/highgui/test/test_framecount.cpp @@ -71,8 +71,8 @@ void CV_FramecountTest::run(int) { string file_path = src_dir+"video/big_buck_bunny."+ext[i]; - cap = cvCreateFileCapture(file_path.c_str()); - if (cap.empty()) + cap.reset(cvCreateFileCapture(file_path.c_str())); + if (!cap) { ts->printf(cvtest::TS::LOG, "\nFile information (video %d): \n\nName: big_buck_bunny.%s\nFAILED\n\n", i+1, ext[i].c_str()); ts->printf(cvtest::TS::LOG, "Error: cannot read source video file.\n"); diff --git a/modules/imgproc/include/opencv2/imgproc.hpp b/modules/imgproc/include/opencv2/imgproc.hpp index 24d9f4463d..55816ccb7e 100644 --- a/modules/imgproc/include/opencv2/imgproc.hpp +++ b/modules/imgproc/include/opencv2/imgproc.hpp @@ -656,7 +656,7 @@ public: Point dstOfs = Point(0,0), bool isolated = false); //! returns true if the filter is separable - bool isSeparable() const { return (const BaseFilter*)filter2D == 0; } + bool isSeparable() const { return !filter2D; } //! returns the number int remainingInputRows() const; int remainingOutputRows() const; diff --git a/modules/imgproc/src/clahe.cpp b/modules/imgproc/src/clahe.cpp index 4ce479713e..89fb62bd01 100644 --- a/modules/imgproc/src/clahe.cpp +++ b/modules/imgproc/src/clahe.cpp @@ -330,5 +330,5 @@ namespace cv::Ptr cv::createCLAHE(double clipLimit, cv::Size tileGridSize) { - return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height); + return makePtr(clipLimit, tileGridSize.width, tileGridSize.height); } diff --git a/modules/imgproc/src/contours.cpp b/modules/imgproc/src/contours.cpp index 6f5b0c8ac6..797f8c56c8 100644 --- a/modules/imgproc/src/contours.cpp +++ b/modules/imgproc/src/contours.cpp @@ -1339,8 +1339,8 @@ icvFindContoursInInterval( const CvArr* src, if( contourHeaderSize < (int)sizeof(CvContour)) CV_Error( CV_StsBadSize, "Contour header size must be >= sizeof(CvContour)" ); - storage00 = cvCreateChildMemStorage(storage); - storage01 = cvCreateChildMemStorage(storage); + storage00.reset(cvCreateChildMemStorage(storage)); + storage01.reset(cvCreateChildMemStorage(storage)); CvMat stub, *mat; diff --git a/modules/imgproc/src/filter.cpp b/modules/imgproc/src/filter.cpp index 86322e4ba5..f7e7efa854 100644 --- a/modules/imgproc/src/filter.cpp +++ b/modules/imgproc/src/filter.cpp @@ -117,7 +117,7 @@ void FilterEngine::init( const Ptr& _filter2D, if( isSeparable() ) { - CV_Assert( !rowFilter.empty() && !columnFilter.empty() ); + CV_Assert( rowFilter && columnFilter ); ksize = Size(rowFilter->ksize, columnFilter->ksize); anchor = Point(rowFilter->anchor, columnFilter->anchor); } @@ -244,9 +244,9 @@ int FilterEngine::start(Size _wholeSize, Rect _roi, int _maxBufRows) rowCount = dstY = 0; startY = startY0 = std::max(roi.y - anchor.y, 0); endY = std::min(roi.y + roi.height + ksize.height - anchor.y - 1, wholeSize.height); - if( !columnFilter.empty() ) + if( columnFilter ) columnFilter->reset(); - if( !filter2D.empty() ) + if( filter2D ) filter2D->reset(); return startY; @@ -2735,42 +2735,42 @@ cv::Ptr cv::getLinearRowFilter( int srcType, int bufType, if( (symmetryType & (KERNEL_SYMMETRICAL|KERNEL_ASYMMETRICAL)) != 0 && ksize <= 5 ) { if( sdepth == CV_8U && ddepth == CV_32S ) - return Ptr(new SymmRowSmallFilter - (kernel, anchor, symmetryType, SymmRowSmallVec_8u32s(kernel, symmetryType))); + return makePtr > + (kernel, anchor, symmetryType, SymmRowSmallVec_8u32s(kernel, symmetryType)); if( sdepth == CV_32F && ddepth == CV_32F ) - return Ptr(new SymmRowSmallFilter - (kernel, anchor, symmetryType, SymmRowSmallVec_32f(kernel, symmetryType))); + return makePtr > + (kernel, anchor, symmetryType, SymmRowSmallVec_32f(kernel, symmetryType)); } if( sdepth == CV_8U && ddepth == CV_32S ) - return Ptr(new RowFilter - (kernel, anchor, RowVec_8u32s(kernel))); + return makePtr > + (kernel, anchor, RowVec_8u32s(kernel)); if( sdepth == CV_8U && ddepth == CV_32F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_8U && ddepth == CV_64F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_16U && ddepth == CV_32F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_16U && ddepth == CV_64F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_16S && ddepth == CV_32F ) - return Ptr(new RowFilter - (kernel, anchor, RowVec_16s32f(kernel))); + return makePtr > + (kernel, anchor, RowVec_16s32f(kernel)); if( sdepth == CV_16S && ddepth == CV_64F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_32F && ddepth == CV_32F ) - return Ptr(new RowFilter - (kernel, anchor, RowVec_32f(kernel))); + return makePtr > + (kernel, anchor, RowVec_32f(kernel)); if( sdepth == CV_32F && ddepth == CV_64F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); if( sdepth == CV_64F && ddepth == CV_64F ) - return Ptr(new RowFilter(kernel, anchor)); + return makePtr >(kernel, anchor); CV_Error_( CV_StsNotImplemented, ("Unsupported combination of source format (=%d), and buffer format (=%d)", srcType, bufType)); - return Ptr(0); + return Ptr(); } @@ -2789,24 +2789,24 @@ cv::Ptr cv::getLinearColumnFilter( int bufType, int dstTyp if( !(symmetryType & (KERNEL_SYMMETRICAL|KERNEL_ASYMMETRICAL)) ) { if( ddepth == CV_8U && sdepth == CV_32S ) - return Ptr(new ColumnFilter, ColumnNoVec> - (kernel, anchor, delta, FixedPtCastEx(bits))); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, FixedPtCastEx(bits)); if( ddepth == CV_8U && sdepth == CV_32F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_8U && sdepth == CV_64F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_16U && sdepth == CV_32F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_16U && sdepth == CV_64F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_16S && sdepth == CV_32F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_16S && sdepth == CV_64F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_32F && sdepth == CV_32F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); if( ddepth == CV_64F && sdepth == CV_64F ) - return Ptr(new ColumnFilter, ColumnNoVec>(kernel, anchor, delta)); + return makePtr, ColumnNoVec> >(kernel, anchor, delta); } else { @@ -2814,60 +2814,60 @@ cv::Ptr cv::getLinearColumnFilter( int bufType, int dstTyp if( ksize == 3 ) { if( ddepth == CV_8U && sdepth == CV_32S ) - return Ptr(new SymmColumnSmallFilter< - FixedPtCastEx, SymmColumnVec_32s8u> + return makePtr, SymmColumnVec_32s8u> > (kernel, anchor, delta, symmetryType, FixedPtCastEx(bits), - SymmColumnVec_32s8u(kernel, symmetryType, bits, delta))); + SymmColumnVec_32s8u(kernel, symmetryType, bits, delta)); if( ddepth == CV_16S && sdepth == CV_32S && bits == 0 ) - return Ptr(new SymmColumnSmallFilter, - SymmColumnSmallVec_32s16s>(kernel, anchor, delta, symmetryType, - Cast(), SymmColumnSmallVec_32s16s(kernel, symmetryType, bits, delta))); + return makePtr, + SymmColumnSmallVec_32s16s> >(kernel, anchor, delta, symmetryType, + Cast(), SymmColumnSmallVec_32s16s(kernel, symmetryType, bits, delta)); if( ddepth == CV_32F && sdepth == CV_32F ) - return Ptr(new SymmColumnSmallFilter< - Cast,SymmColumnSmallVec_32f> + return makePtr,SymmColumnSmallVec_32f> > (kernel, anchor, delta, symmetryType, Cast(), - SymmColumnSmallVec_32f(kernel, symmetryType, 0, delta))); + SymmColumnSmallVec_32f(kernel, symmetryType, 0, delta)); } if( ddepth == CV_8U && sdepth == CV_32S ) - return Ptr(new SymmColumnFilter, SymmColumnVec_32s8u> + return makePtr, SymmColumnVec_32s8u> > (kernel, anchor, delta, symmetryType, FixedPtCastEx(bits), - SymmColumnVec_32s8u(kernel, symmetryType, bits, delta))); + SymmColumnVec_32s8u(kernel, symmetryType, bits, delta)); if( ddepth == CV_8U && sdepth == CV_32F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_8U && sdepth == CV_64F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_16U && sdepth == CV_32F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_16U && sdepth == CV_64F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_16S && sdepth == CV_32S ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_16S && sdepth == CV_32F ) - return Ptr(new SymmColumnFilter, SymmColumnVec_32f16s> + return makePtr, SymmColumnVec_32f16s> > (kernel, anchor, delta, symmetryType, Cast(), - SymmColumnVec_32f16s(kernel, symmetryType, 0, delta))); + SymmColumnVec_32f16s(kernel, symmetryType, 0, delta)); if( ddepth == CV_16S && sdepth == CV_64F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); if( ddepth == CV_32F && sdepth == CV_32F ) - return Ptr(new SymmColumnFilter, SymmColumnVec_32f> + return makePtr, SymmColumnVec_32f> > (kernel, anchor, delta, symmetryType, Cast(), - SymmColumnVec_32f(kernel, symmetryType, 0, delta))); + SymmColumnVec_32f(kernel, symmetryType, 0, delta)); if( ddepth == CV_64F && sdepth == CV_64F ) - return Ptr(new SymmColumnFilter, ColumnNoVec> - (kernel, anchor, delta, symmetryType)); + return makePtr, ColumnNoVec> > + (kernel, anchor, delta, symmetryType); } CV_Error_( CV_StsNotImplemented, ("Unsupported combination of buffer format (=%d), and destination format (=%d)", bufType, dstType)); - return Ptr(0); + return Ptr(); } @@ -2933,7 +2933,7 @@ cv::Ptr cv::createSeparableLinearFilter( Ptr _columnFilter = getLinearColumnFilter( _bufType, _dstType, columnKernel, _anchor.y, ctype, _delta, bits ); - return Ptr( new FilterEngine(Ptr(0), _rowFilter, _columnFilter, + return Ptr( new FilterEngine(Ptr(), _rowFilter, _columnFilter, _srcType, _dstType, _bufType, _rowBorderType, _columnBorderType, _borderValue )); } @@ -3085,13 +3085,13 @@ cv::Ptr cv::getLinearFilter(int srcType, int dstType, anchor = normalizeAnchor(anchor, _kernel.size()); /*if( sdepth == CV_8U && ddepth == CV_8U && kdepth == CV_32S ) - return Ptr(new Filter2D, FilterVec_8u> + return makePtr, FilterVec_8u> > (_kernel, anchor, delta, FixedPtCastEx(bits), - FilterVec_8u(_kernel, bits, delta))); + FilterVec_8u(_kernel, bits, delta)); if( sdepth == CV_8U && ddepth == CV_16S && kdepth == CV_32S ) - return Ptr(new Filter2D, FilterVec_8u16s> + return makePtr, FilterVec_8u16s> > (_kernel, anchor, delta, FixedPtCastEx(bits), - FilterVec_8u16s(_kernel, bits, delta)));*/ + FilterVec_8u16s(_kernel, bits, delta));*/ kdepth = sdepth == CV_64F || ddepth == CV_64F ? CV_64F : CV_32F; Mat kernel; @@ -3101,53 +3101,53 @@ cv::Ptr cv::getLinearFilter(int srcType, int dstType, _kernel.convertTo(kernel, kdepth, _kernel.type() == CV_32S ? 1./(1 << bits) : 1.); if( sdepth == CV_8U && ddepth == CV_8U ) - return Ptr(new Filter2D, FilterVec_8u> - (kernel, anchor, delta, Cast(), FilterVec_8u(kernel, 0, delta))); + return makePtr, FilterVec_8u> > + (kernel, anchor, delta, Cast(), FilterVec_8u(kernel, 0, delta)); if( sdepth == CV_8U && ddepth == CV_16U ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_8U && ddepth == CV_16S ) - return Ptr(new Filter2D, FilterVec_8u16s> - (kernel, anchor, delta, Cast(), FilterVec_8u16s(kernel, 0, delta))); + return makePtr, FilterVec_8u16s> > + (kernel, anchor, delta, Cast(), FilterVec_8u16s(kernel, 0, delta)); if( sdepth == CV_8U && ddepth == CV_32F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_8U && ddepth == CV_64F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16U && ddepth == CV_16U ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16U && ddepth == CV_32F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16U && ddepth == CV_64F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16S && ddepth == CV_16S ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16S && ddepth == CV_32F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_16S && ddepth == CV_64F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); if( sdepth == CV_32F && ddepth == CV_32F ) - return Ptr(new Filter2D, FilterVec_32f> - (kernel, anchor, delta, Cast(), FilterVec_32f(kernel, 0, delta))); + return makePtr, FilterVec_32f> > + (kernel, anchor, delta, Cast(), FilterVec_32f(kernel, 0, delta)); if( sdepth == CV_64F && ddepth == CV_64F ) - return Ptr(new Filter2D, FilterNoVec>(kernel, anchor, delta)); + return makePtr, FilterNoVec> >(kernel, anchor, delta); CV_Error_( CV_StsNotImplemented, ("Unsupported combination of source format (=%d), and destination format (=%d)", srcType, dstType)); - return Ptr(0); + return Ptr(); } @@ -3178,9 +3178,9 @@ cv::Ptr cv::createLinearFilter( int _srcType, int _dstType, Ptr _filter2D = getLinearFilter(_srcType, _dstType, kernel, _anchor, _delta, bits); - return Ptr(new FilterEngine(_filter2D, Ptr(0), - Ptr(0), _srcType, _dstType, _srcType, - _rowBorderType, _columnBorderType, _borderValue )); + return makePtr(_filter2D, Ptr(), + Ptr(), _srcType, _dstType, _srcType, + _rowBorderType, _columnBorderType, _borderValue ); } diff --git a/modules/imgproc/src/generalized_hough.cpp b/modules/imgproc/src/generalized_hough.cpp index 7ee3b700da..a261d644b8 100644 --- a/modules/imgproc/src/generalized_hough.cpp +++ b/modules/imgproc/src/generalized_hough.cpp @@ -491,7 +491,7 @@ namespace Ptr cv::createGeneralizedHoughBallard() { - return new GeneralizedHoughBallardImpl; + return makePtr(); } // GeneralizedHoughGuil @@ -940,5 +940,5 @@ namespace Ptr cv::createGeneralizedHoughGuil() { - return new GeneralizedHoughGuilImpl; + return makePtr(); } diff --git a/modules/imgproc/src/hough.cpp b/modules/imgproc/src/hough.cpp index f33c6d2033..9c8eaca8f5 100644 --- a/modules/imgproc/src/hough.cpp +++ b/modules/imgproc/src/hough.cpp @@ -766,21 +766,21 @@ icvHoughCirclesGradient( CvMat* img, float dp, float min_dist, float idp, dr; CvSeqReader reader; - edges = cvCreateMat( img->rows, img->cols, CV_8UC1 ); + edges.reset(cvCreateMat( img->rows, img->cols, CV_8UC1 )); cvCanny( img, edges, MAX(canny_threshold/2,1), canny_threshold, 3 ); - dx = cvCreateMat( img->rows, img->cols, CV_16SC1 ); - dy = cvCreateMat( img->rows, img->cols, CV_16SC1 ); + dx.reset(cvCreateMat( img->rows, img->cols, CV_16SC1 )); + dy.reset(cvCreateMat( img->rows, img->cols, CV_16SC1 )); cvSobel( img, dx, 1, 0, 3 ); cvSobel( img, dy, 0, 1, 3 ); if( dp < 1.f ) dp = 1.f; idp = 1.f/dp; - accum = cvCreateMat( cvCeil(img->rows*idp)+2, cvCeil(img->cols*idp)+2, CV_32SC1 ); + accum.reset(cvCreateMat( cvCeil(img->rows*idp)+2, cvCeil(img->cols*idp)+2, CV_32SC1 )); cvZero(accum); - storage = cvCreateMemStorage(); + storage.reset(cvCreateMemStorage()); nz = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage ); centers = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage ); @@ -866,7 +866,7 @@ icvHoughCirclesGradient( CvMat* img, float dp, float min_dist, cvClearSeq( centers ); cvSeqPushMulti( centers, &sort_buf[0], center_count ); - dist_buf = cvCreateMat( 1, nz_count, CV_32FC1 ); + dist_buf.reset(cvCreateMat( 1, nz_count, CV_32FC1 )); ddata = dist_buf->data.fl; dr = dp; @@ -1060,7 +1060,7 @@ void cv::HoughCircles( InputArray _image, OutputArray _circles, double param1, double param2, int minRadius, int maxRadius ) { - Ptr storage = cvCreateMemStorage(STORAGE_SIZE); + Ptr storage(cvCreateMemStorage(STORAGE_SIZE)); Mat image = _image.getMat(); CvMat c_image = image; CvSeq* seq = cvHoughCircles( &c_image, storage, method, diff --git a/modules/imgproc/src/imgwarp.cpp b/modules/imgproc/src/imgwarp.cpp index 05a96300b5..32a1517dbe 100644 --- a/modules/imgproc/src/imgwarp.cpp +++ b/modules/imgproc/src/imgwarp.cpp @@ -3931,8 +3931,8 @@ cvLogPolar( const CvArr* srcarr, CvArr* dstarr, ssize = cvGetMatSize(src); dsize = cvGetMatSize(dst); - mapx = cvCreateMat( dsize.height, dsize.width, CV_32F ); - mapy = cvCreateMat( dsize.height, dsize.width, CV_32F ); + mapx.reset(cvCreateMat( dsize.height, dsize.width, CV_32F )); + mapy.reset(cvCreateMat( dsize.height, dsize.width, CV_32F )); if( !(flags & CV_WARP_INVERSE_MAP) ) { @@ -4049,8 +4049,8 @@ void cvLinearPolar( const CvArr* srcarr, CvArr* dstarr, dsize.width = dst->cols; dsize.height = dst->rows; - mapx = cvCreateMat( dsize.height, dsize.width, CV_32F ); - mapy = cvCreateMat( dsize.height, dsize.width, CV_32F ); + mapx.reset(cvCreateMat( dsize.height, dsize.width, CV_32F )); + mapy.reset(cvCreateMat( dsize.height, dsize.width, CV_32F )); if( !(flags & CV_WARP_INVERSE_MAP) ) { diff --git a/modules/imgproc/src/lsd.cpp b/modules/imgproc/src/lsd.cpp index 58d226f0c4..f468c61873 100644 --- a/modules/imgproc/src/lsd.cpp +++ b/modules/imgproc/src/lsd.cpp @@ -393,9 +393,9 @@ CV_EXPORTS Ptr createLineSegmentDetectorPtr( int _refine, double _scale, double _sigma_scale, double _quant, double _ang_th, double _log_eps, double _density_th, int _n_bins) { - return Ptr(new LineSegmentDetectorImpl( + return makePtr( _refine, _scale, _sigma_scale, _quant, _ang_th, - _log_eps, _density_th, _n_bins)); + _log_eps, _density_th, _n_bins); } ///////////////////////////////////////////////////////////////////////////////////////// diff --git a/modules/imgproc/src/morph.cpp b/modules/imgproc/src/morph.cpp index ef919027ac..33ddcf76c0 100644 --- a/modules/imgproc/src/morph.cpp +++ b/modules/imgproc/src/morph.cpp @@ -857,42 +857,42 @@ cv::Ptr cv::getMorphologyRowFilter(int op, int type, int ksiz if( op == MORPH_ERODE ) { if( depth == CV_8U ) - return Ptr(new MorphRowFilter, - ErodeRowVec8u>(ksize, anchor)); + return makePtr, + ErodeRowVec8u> >(ksize, anchor); if( depth == CV_16U ) - return Ptr(new MorphRowFilter, - ErodeRowVec16u>(ksize, anchor)); + return makePtr, + ErodeRowVec16u> >(ksize, anchor); if( depth == CV_16S ) - return Ptr(new MorphRowFilter, - ErodeRowVec16s>(ksize, anchor)); + return makePtr, + ErodeRowVec16s> >(ksize, anchor); if( depth == CV_32F ) - return Ptr(new MorphRowFilter, - ErodeRowVec32f>(ksize, anchor)); + return makePtr, + ErodeRowVec32f> >(ksize, anchor); if( depth == CV_64F ) - return Ptr(new MorphRowFilter, - ErodeRowVec64f>(ksize, anchor)); + return makePtr, + ErodeRowVec64f> >(ksize, anchor); } else { if( depth == CV_8U ) - return Ptr(new MorphRowFilter, - DilateRowVec8u>(ksize, anchor)); + return makePtr, + DilateRowVec8u> >(ksize, anchor); if( depth == CV_16U ) - return Ptr(new MorphRowFilter, - DilateRowVec16u>(ksize, anchor)); + return makePtr, + DilateRowVec16u> >(ksize, anchor); if( depth == CV_16S ) - return Ptr(new MorphRowFilter, - DilateRowVec16s>(ksize, anchor)); + return makePtr, + DilateRowVec16s> >(ksize, anchor); if( depth == CV_32F ) - return Ptr(new MorphRowFilter, - DilateRowVec32f>(ksize, anchor)); + return makePtr, + DilateRowVec32f> >(ksize, anchor); if( depth == CV_64F ) - return Ptr(new MorphRowFilter, - DilateRowVec64f>(ksize, anchor)); + return makePtr, + DilateRowVec64f> >(ksize, anchor); } CV_Error_( CV_StsNotImplemented, ("Unsupported data type (=%d)", type)); - return Ptr(0); + return Ptr(); } cv::Ptr cv::getMorphologyColumnFilter(int op, int type, int ksize, int anchor) @@ -904,42 +904,42 @@ cv::Ptr cv::getMorphologyColumnFilter(int op, int type, in if( op == MORPH_ERODE ) { if( depth == CV_8U ) - return Ptr(new MorphColumnFilter, - ErodeColumnVec8u>(ksize, anchor)); + return makePtr, + ErodeColumnVec8u> >(ksize, anchor); if( depth == CV_16U ) - return Ptr(new MorphColumnFilter, - ErodeColumnVec16u>(ksize, anchor)); + return makePtr, + ErodeColumnVec16u> >(ksize, anchor); if( depth == CV_16S ) - return Ptr(new MorphColumnFilter, - ErodeColumnVec16s>(ksize, anchor)); + return makePtr, + ErodeColumnVec16s> >(ksize, anchor); if( depth == CV_32F ) - return Ptr(new MorphColumnFilter, - ErodeColumnVec32f>(ksize, anchor)); + return makePtr, + ErodeColumnVec32f> >(ksize, anchor); if( depth == CV_64F ) - return Ptr(new MorphColumnFilter, - ErodeColumnVec64f>(ksize, anchor)); + return makePtr, + ErodeColumnVec64f> >(ksize, anchor); } else { if( depth == CV_8U ) - return Ptr(new MorphColumnFilter, - DilateColumnVec8u>(ksize, anchor)); + return makePtr, + DilateColumnVec8u> >(ksize, anchor); if( depth == CV_16U ) - return Ptr(new MorphColumnFilter, - DilateColumnVec16u>(ksize, anchor)); + return makePtr, + DilateColumnVec16u> >(ksize, anchor); if( depth == CV_16S ) - return Ptr(new MorphColumnFilter, - DilateColumnVec16s>(ksize, anchor)); + return makePtr, + DilateColumnVec16s> >(ksize, anchor); if( depth == CV_32F ) - return Ptr(new MorphColumnFilter, - DilateColumnVec32f>(ksize, anchor)); + return makePtr, + DilateColumnVec32f> >(ksize, anchor); if( depth == CV_64F ) - return Ptr(new MorphColumnFilter, - DilateColumnVec64f>(ksize, anchor)); + return makePtr, + DilateColumnVec64f> >(ksize, anchor); } CV_Error_( CV_StsNotImplemented, ("Unsupported data type (=%d)", type)); - return Ptr(0); + return Ptr(); } @@ -952,32 +952,32 @@ cv::Ptr cv::getMorphologyFilter(int op, int type, InputArray _ke if( op == MORPH_ERODE ) { if( depth == CV_8U ) - return Ptr(new MorphFilter, ErodeVec8u>(kernel, anchor)); + return makePtr, ErodeVec8u> >(kernel, anchor); if( depth == CV_16U ) - return Ptr(new MorphFilter, ErodeVec16u>(kernel, anchor)); + return makePtr, ErodeVec16u> >(kernel, anchor); if( depth == CV_16S ) - return Ptr(new MorphFilter, ErodeVec16s>(kernel, anchor)); + return makePtr, ErodeVec16s> >(kernel, anchor); if( depth == CV_32F ) - return Ptr(new MorphFilter, ErodeVec32f>(kernel, anchor)); + return makePtr, ErodeVec32f> >(kernel, anchor); if( depth == CV_64F ) - return Ptr(new MorphFilter, ErodeVec64f>(kernel, anchor)); + return makePtr, ErodeVec64f> >(kernel, anchor); } else { if( depth == CV_8U ) - return Ptr(new MorphFilter, DilateVec8u>(kernel, anchor)); + return makePtr, DilateVec8u> >(kernel, anchor); if( depth == CV_16U ) - return Ptr(new MorphFilter, DilateVec16u>(kernel, anchor)); + return makePtr, DilateVec16u> >(kernel, anchor); if( depth == CV_16S ) - return Ptr(new MorphFilter, DilateVec16s>(kernel, anchor)); + return makePtr, DilateVec16s> >(kernel, anchor); if( depth == CV_32F ) - return Ptr(new MorphFilter, DilateVec32f>(kernel, anchor)); + return makePtr, DilateVec32f> >(kernel, anchor); if( depth == CV_64F ) - return Ptr(new MorphFilter, DilateVec64f>(kernel, anchor)); + return makePtr, DilateVec64f> >(kernel, anchor); } CV_Error_( CV_StsNotImplemented, ("Unsupported data type (=%d)", type)); - return Ptr(0); + return Ptr(); } @@ -1020,8 +1020,8 @@ cv::Ptr cv::createMorphologyFilter( int op, int type, InputArr depth == CV_32F ? (double)-FLT_MAX : -DBL_MAX); } - return Ptr(new FilterEngine(filter2D, rowFilter, columnFilter, - type, type, type, _rowBorderType, _columnBorderType, borderValue )); + return makePtr(filter2D, rowFilter, columnFilter, + type, type, type, _rowBorderType, _columnBorderType, borderValue ); } diff --git a/modules/imgproc/src/smooth.cpp b/modules/imgproc/src/smooth.cpp index 127a9da363..a4c478a2c9 100644 --- a/modules/imgproc/src/smooth.cpp +++ b/modules/imgproc/src/smooth.cpp @@ -622,29 +622,29 @@ cv::Ptr cv::getRowSumFilter(int srcType, int sumType, int ksi anchor = ksize/2; if( sdepth == CV_8U && ddepth == CV_32S ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_8U && ddepth == CV_64F ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_16U && ddepth == CV_32S ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_16U && ddepth == CV_64F ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_16S && ddepth == CV_32S ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_32S && ddepth == CV_32S ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_16S && ddepth == CV_64F ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_32F && ddepth == CV_64F ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); if( sdepth == CV_64F && ddepth == CV_64F ) - return Ptr(new RowSum(ksize, anchor)); + return makePtr >(ksize, anchor); CV_Error_( CV_StsNotImplemented, ("Unsupported combination of source format (=%d), and buffer format (=%d)", srcType, sumType)); - return Ptr(0); + return Ptr(); } @@ -658,33 +658,33 @@ cv::Ptr cv::getColumnSumFilter(int sumType, int dstType, i anchor = ksize/2; if( ddepth == CV_8U && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_8U && sdepth == CV_64F ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_16U && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_16U && sdepth == CV_64F ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_16S && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_16S && sdepth == CV_64F ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_32S && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_32F && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_32F && sdepth == CV_64F ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_64F && sdepth == CV_32S ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); if( ddepth == CV_64F && sdepth == CV_64F ) - return Ptr(new ColumnSum(ksize, anchor, scale)); + return makePtr >(ksize, anchor, scale); CV_Error_( CV_StsNotImplemented, ("Unsupported combination of sum format (=%d), and destination format (=%d)", sumType, dstType)); - return Ptr(0); + return Ptr(); } @@ -703,8 +703,8 @@ cv::Ptr cv::createBoxFilter( int srcType, int dstType, Size ks Ptr columnFilter = getColumnSumFilter(sumType, dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1); - return Ptr(new FilterEngine(Ptr(0), rowFilter, columnFilter, - srcType, dstType, sumType, borderType )); + return makePtr(Ptr(), rowFilter, columnFilter, + srcType, dstType, sumType, borderType ); } diff --git a/modules/imgproc/test/test_convhull.cpp b/modules/imgproc/test/test_convhull.cpp index cae75d0cb0..49456c6cc9 100644 --- a/modules/imgproc/test/test_convhull.cpp +++ b/modules/imgproc/test/test_convhull.cpp @@ -1626,7 +1626,7 @@ CV_PerimeterAreaSliceTest::~CV_PerimeterAreaSliceTest() {} void CV_PerimeterAreaSliceTest::run( int ) { - Ptr storage = cvCreateMemStorage(); + Ptr storage(cvCreateMemStorage()); RNG& rng = theRNG(); const double min_r = 90, max_r = 120; diff --git a/modules/java/generator/src/cpp/features2d_manual.hpp b/modules/java/generator/src/cpp/features2d_manual.hpp index a51b1eaa30..723f820e08 100644 --- a/modules/java/generator/src/cpp/features2d_manual.hpp +++ b/modules/java/generator/src/cpp/features2d_manual.hpp @@ -11,15 +11,17 @@ namespace cv { -class CV_EXPORTS_AS(FeatureDetector) javaFeatureDetector : public FeatureDetector +class CV_EXPORTS_AS(FeatureDetector) javaFeatureDetector { public: -#if 0 - //DO NOT REMOVE! The block is required for sources parser - CV_WRAP void detect( const Mat& image, CV_OUT std::vector& keypoints, const Mat& mask=Mat() ) const; - CV_WRAP void detect( const std::vector& images, CV_OUT std::vector >& keypoints, const std::vector& masks=std::vector() ) const; - CV_WRAP virtual bool empty() const; -#endif + CV_WRAP void detect( const Mat& image, CV_OUT std::vector& keypoints, const Mat& mask=Mat() ) const + { return wrapped->detect(image, keypoints, mask); } + + CV_WRAP void detect( const std::vector& images, CV_OUT std::vector >& keypoints, const std::vector& masks=std::vector() ) const + { return wrapped->detect(images, keypoints, masks); } + + CV_WRAP bool empty() const + { return wrapped->empty(); } enum { @@ -141,52 +143,74 @@ public: break; } - Ptr detector = FeatureDetector::create(name); - detector.addref(); - return (javaFeatureDetector*)((FeatureDetector*) detector); + return new javaFeatureDetector(FeatureDetector::create(name)); } CV_WRAP void write( const String& fileName ) const { FileStorage fs(fileName, FileStorage::WRITE); - ((FeatureDetector*)this)->write(fs); - fs.release(); + wrapped->write(fs); } CV_WRAP void read( const String& fileName ) { FileStorage fs(fileName, FileStorage::READ); - ((FeatureDetector*)this)->read(fs.root()); - fs.release(); + wrapped->read(fs.root()); } + +private: + javaFeatureDetector(Ptr _wrapped) : wrapped(_wrapped) + {} + + Ptr wrapped; }; -class CV_EXPORTS_AS(DescriptorMatcher) javaDescriptorMatcher : public DescriptorMatcher +class CV_EXPORTS_AS(DescriptorMatcher) javaDescriptorMatcher { public: -#if 0 - //DO NOT REMOVE! The block is required for sources parser - CV_WRAP virtual bool isMaskSupported() const; - CV_WRAP virtual void add( const std::vector& descriptors ); - CV_WRAP const std::vector& getTrainDescriptors() const; - CV_WRAP virtual void clear(); - CV_WRAP virtual bool empty() const; - CV_WRAP virtual void train(); + CV_WRAP bool isMaskSupported() const + { return wrapped->isMaskSupported(); } + + CV_WRAP void add( const std::vector& descriptors ) + { return wrapped->add(descriptors); } + + CV_WRAP const std::vector& getTrainDescriptors() const + { return wrapped->getTrainDescriptors(); } + + CV_WRAP void clear() + { return wrapped->clear(); } + + CV_WRAP bool empty() const + { return wrapped->empty(); } + + CV_WRAP void train() + { return wrapped->train(); } + CV_WRAP void match( const Mat& queryDescriptors, const Mat& trainDescriptors, - CV_OUT std::vector& matches, const Mat& mask=Mat() ) const; + CV_OUT std::vector& matches, const Mat& mask=Mat() ) const + { return wrapped->match(queryDescriptors, trainDescriptors, matches, mask); } + CV_WRAP void knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, CV_OUT std::vector >& matches, int k, - const Mat& mask=Mat(), bool compactResult=false ) const; + const Mat& mask=Mat(), bool compactResult=false ) const + { return wrapped->knnMatch(queryDescriptors, trainDescriptors, matches, k, mask, compactResult); } + CV_WRAP void radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, CV_OUT std::vector >& matches, float maxDistance, - const Mat& mask=Mat(), bool compactResult=false ) const; + const Mat& mask=Mat(), bool compactResult=false ) const + { return wrapped->radiusMatch(queryDescriptors, trainDescriptors, matches, maxDistance, mask, compactResult); } + CV_WRAP void match( const Mat& queryDescriptors, CV_OUT std::vector& matches, - const std::vector& masks=std::vector() ); + const std::vector& masks=std::vector() ) + { return wrapped->match(queryDescriptors, matches, masks); } + CV_WRAP void knnMatch( const Mat& queryDescriptors, CV_OUT std::vector >& matches, int k, - const std::vector& masks=std::vector(), bool compactResult=false ); + const std::vector& masks=std::vector(), bool compactResult=false ) + { return wrapped->knnMatch(queryDescriptors, matches, k, masks, compactResult); } + CV_WRAP void radiusMatch( const Mat& queryDescriptors, CV_OUT std::vector >& matches, float maxDistance, - const std::vector& masks=std::vector(), bool compactResult=false ); -#endif + const std::vector& masks=std::vector(), bool compactResult=false ) + { return wrapped->radiusMatch(queryDescriptors, matches, maxDistance, masks, compactResult); } enum { @@ -200,9 +224,7 @@ public: CV_WRAP_AS(clone) javaDescriptorMatcher* jclone( bool emptyTrainData=false ) const { - Ptr matcher = this->clone(emptyTrainData); - matcher.addref(); - return (javaDescriptorMatcher*)((DescriptorMatcher*) matcher); + return new javaDescriptorMatcher(wrapped->clone(emptyTrainData)); } //supported: FlannBased, BruteForce, BruteForce-L1, BruteForce-Hamming, BruteForce-HammingLUT @@ -235,38 +257,45 @@ public: break; } - Ptr matcher = DescriptorMatcher::create(name); - matcher.addref(); - return (javaDescriptorMatcher*)((DescriptorMatcher*) matcher); + return new javaDescriptorMatcher(DescriptorMatcher::create(name)); } CV_WRAP void write( const String& fileName ) const { FileStorage fs(fileName, FileStorage::WRITE); - ((DescriptorMatcher*)this)->write(fs); - fs.release(); + wrapped->write(fs); } CV_WRAP void read( const String& fileName ) { FileStorage fs(fileName, FileStorage::READ); - ((DescriptorMatcher*)this)->read(fs.root()); - fs.release(); + wrapped->read(fs.root()); } + +private: + javaDescriptorMatcher(Ptr _wrapped) : wrapped(_wrapped) + {} + + Ptr wrapped; }; -class CV_EXPORTS_AS(DescriptorExtractor) javaDescriptorExtractor : public DescriptorExtractor +class CV_EXPORTS_AS(DescriptorExtractor) javaDescriptorExtractor { public: -#if 0 - //DO NOT REMOVE! The block is required for sources parser - CV_WRAP void compute( const Mat& image, CV_IN_OUT std::vector& keypoints, Mat& descriptors ) const; - CV_WRAP void compute( const std::vector& images, CV_IN_OUT std::vector >& keypoints, CV_OUT std::vector& descriptors ) const; - CV_WRAP virtual int descriptorSize() const; - CV_WRAP virtual int descriptorType() const; + CV_WRAP void compute( const Mat& image, CV_IN_OUT std::vector& keypoints, Mat& descriptors ) const + { return wrapped->compute(image, keypoints, descriptors); } - CV_WRAP virtual bool empty() const; -#endif + CV_WRAP void compute( const std::vector& images, CV_IN_OUT std::vector >& keypoints, CV_OUT std::vector& descriptors ) const + { return wrapped->compute(images, keypoints, descriptors); } + + CV_WRAP int descriptorSize() const + { return wrapped->descriptorSize(); } + + CV_WRAP int descriptorType() const + { return wrapped->descriptorType(); } + + CV_WRAP bool empty() const + { return wrapped->empty(); } enum { @@ -327,62 +356,93 @@ public: break; } - Ptr extractor = DescriptorExtractor::create(name); - extractor.addref(); - return (javaDescriptorExtractor*)((DescriptorExtractor*) extractor); + return new javaDescriptorExtractor(DescriptorExtractor::create(name)); } CV_WRAP void write( const String& fileName ) const { FileStorage fs(fileName, FileStorage::WRITE); - ((DescriptorExtractor*)this)->write(fs); - fs.release(); + wrapped->write(fs); } CV_WRAP void read( const String& fileName ) { FileStorage fs(fileName, FileStorage::READ); - ((DescriptorExtractor*)this)->read(fs.root()); - fs.release(); + wrapped->read(fs.root()); } + +private: + javaDescriptorExtractor(Ptr _wrapped) : wrapped(_wrapped) + {} + + Ptr wrapped; }; -class CV_EXPORTS_AS(GenericDescriptorMatcher) javaGenericDescriptorMatcher : public GenericDescriptorMatcher +class CV_EXPORTS_AS(GenericDescriptorMatcher) javaGenericDescriptorMatcher { public: -#if 0 - //DO NOT REMOVE! The block is required for sources parser - CV_WRAP virtual void add( const std::vector& images, - std::vector >& keypoints ); - CV_WRAP const std::vector& getTrainImages() const; - CV_WRAP const std::vector >& getTrainKeypoints() const; - CV_WRAP virtual void clear(); - CV_WRAP virtual bool isMaskSupported(); - CV_WRAP virtual void train(); + CV_WRAP void add( const std::vector& images, + std::vector >& keypoints ) + { return wrapped->add(images, keypoints); } + + CV_WRAP const std::vector& getTrainImages() const + { return wrapped->getTrainImages(); } + + CV_WRAP const std::vector >& getTrainKeypoints() const + { return wrapped->getTrainKeypoints(); } + + CV_WRAP void clear() + { return wrapped->clear(); } + + CV_WRAP bool isMaskSupported() + { return wrapped->isMaskSupported(); } + + CV_WRAP void train() + { return wrapped->train(); } + CV_WRAP void classify( const Mat& queryImage, CV_IN_OUT std::vector& queryKeypoints, - const Mat& trainImage, std::vector& trainKeypoints ) const; - CV_WRAP void classify( const Mat& queryImage, CV_IN_OUT std::vector& queryKeypoints ); + const Mat& trainImage, std::vector& trainKeypoints ) const + { return wrapped->classify(queryImage, queryKeypoints, trainImage, trainKeypoints); } + + CV_WRAP void classify( const Mat& queryImage, CV_IN_OUT std::vector& queryKeypoints ) + { return wrapped->classify(queryImage, queryKeypoints); } + CV_WRAP void match( const Mat& queryImage, std::vector& queryKeypoints, const Mat& trainImage, std::vector& trainKeypoints, - CV_OUT std::vector& matches, const Mat& mask=Mat() ) const; + CV_OUT std::vector& matches, const Mat& mask=Mat() ) const + { return wrapped->match(queryImage, queryKeypoints, trainImage, trainKeypoints, matches, mask); } + CV_WRAP void knnMatch( const Mat& queryImage, std::vector& queryKeypoints, const Mat& trainImage, std::vector& trainKeypoints, CV_OUT std::vector >& matches, int k, - const Mat& mask=Mat(), bool compactResult=false ) const; + const Mat& mask=Mat(), bool compactResult=false ) const + { return wrapped->knnMatch(queryImage, queryKeypoints, trainImage, trainKeypoints, + matches, k, mask, compactResult); } + CV_WRAP void radiusMatch( const Mat& queryImage, std::vector& queryKeypoints, const Mat& trainImage, std::vector& trainKeypoints, CV_OUT std::vector >& matches, float maxDistance, - const Mat& mask=Mat(), bool compactResult=false ) const; + const Mat& mask=Mat(), bool compactResult=false ) const + { return wrapped->radiusMatch(queryImage, queryKeypoints, trainImage, trainKeypoints, + matches, maxDistance, mask, compactResult); } + CV_WRAP void match( const Mat& queryImage, std::vector& queryKeypoints, - CV_OUT std::vector& matches, const std::vector& masks=std::vector() ); + CV_OUT std::vector& matches, const std::vector& masks=std::vector() ) + { return wrapped->match(queryImage, queryKeypoints, matches, masks); } + CV_WRAP void knnMatch( const Mat& queryImage, std::vector& queryKeypoints, CV_OUT std::vector >& matches, int k, - const std::vector& masks=std::vector(), bool compactResult=false ); + const std::vector& masks=std::vector(), bool compactResult=false ) + { return wrapped->knnMatch(queryImage, queryKeypoints, matches, k, masks, compactResult); } + CV_WRAP void radiusMatch( const Mat& queryImage, std::vector& queryKeypoints, CV_OUT std::vector >& matches, float maxDistance, - const std::vector& masks=std::vector(), bool compactResult=false ); - CV_WRAP virtual bool empty() const; -#endif + const std::vector& masks=std::vector(), bool compactResult=false ) + { return wrapped->radiusMatch(queryImage, queryKeypoints, matches, maxDistance, masks, compactResult); } + + CV_WRAP bool empty() const + { return wrapped->empty(); } + enum { @@ -392,9 +452,7 @@ public: CV_WRAP_AS(clone) javaGenericDescriptorMatcher* jclone( bool emptyTrainData=false ) const { - Ptr matcher = this->clone(emptyTrainData); - matcher.addref(); - return (javaGenericDescriptorMatcher*)((GenericDescriptorMatcher*) matcher); + return new javaGenericDescriptorMatcher(wrapped->clone(emptyTrainData)); } //supported: OneWay, Fern @@ -416,24 +474,26 @@ public: break; } - Ptr matcher = GenericDescriptorMatcher::create(name); - matcher.addref(); - return (javaGenericDescriptorMatcher*)((GenericDescriptorMatcher*) matcher); + return new javaGenericDescriptorMatcher(GenericDescriptorMatcher::create(name)); } CV_WRAP void write( const String& fileName ) const { FileStorage fs(fileName, FileStorage::WRITE); - ((GenericDescriptorMatcher*)this)->write(fs); - fs.release(); + wrapped->write(fs); } CV_WRAP void read( const String& fileName ) { FileStorage fs(fileName, FileStorage::READ); - ((GenericDescriptorMatcher*)this)->read(fs.root()); - fs.release(); + wrapped->read(fs.root()); } + +private: + javaGenericDescriptorMatcher(Ptr _wrapped) : wrapped(_wrapped) + {} + + Ptr wrapped; }; #if 0 diff --git a/modules/legacy/src/em.cpp b/modules/legacy/src/em.cpp index c11c23598d..b49eb91316 100644 --- a/modules/legacy/src/em.cpp +++ b/modules/legacy/src/em.cpp @@ -85,13 +85,12 @@ void CvEM::read( CvFileStorage* fs, CvFileNode* node ) void CvEM::write( CvFileStorage* _fs, const char* name ) const { - FileStorage fs = _fs; + FileStorage fs(_fs, false); if(name) fs << name << "{"; emObj.write(fs); if(name) fs << "}"; - fs.fs.obj = 0; } double CvEM::calcLikelihood( const Mat &input_sample ) const diff --git a/modules/legacy/src/features2d.cpp b/modules/legacy/src/features2d.cpp index 578b732928..f313875ac4 100644 --- a/modules/legacy/src/features2d.cpp +++ b/modules/legacy/src/features2d.cpp @@ -73,7 +73,7 @@ cvExtractSURF( const CvArr* _img, const CvArr* _mask, Mat descr; Ptr surf = Algorithm::create("Feature2D.SURF"); - if( surf.empty() ) + if( !surf ) CV_Error(CV_StsNotImplemented, "OpenCV was built without SURF support"); surf->set("hessianThreshold", params.hessianThreshold); @@ -107,10 +107,10 @@ CV_IMPL CvSeq* cvGetStarKeypoints( const CvArr* _img, CvMemStorage* storage, CvStarDetectorParams params ) { - Ptr star = new StarDetector(params.maxSize, params.responseThreshold, - params.lineThresholdProjected, - params.lineThresholdBinarized, - params.suppressNonmaxSize); + Ptr star(new StarDetector(params.maxSize, params.responseThreshold, + params.lineThresholdProjected, + params.lineThresholdBinarized, + params.suppressNonmaxSize)); std::vector kpts; star->detect(cvarrToMat(_img), kpts, Mat()); diff --git a/modules/legacy/src/kdtree.cpp b/modules/legacy/src/kdtree.cpp index a32677b79b..4183950759 100644 --- a/modules/legacy/src/kdtree.cpp +++ b/modules/legacy/src/kdtree.cpp @@ -172,7 +172,7 @@ public: CV_Error(CV_StsUnsupportedFormat, "dist must be CV_64FC1"); if (CV_MAT_TYPE(type()) != CV_MAT_TYPE(desc->type)) { - tmp_desc = cvCreateMat(desc->rows, desc->cols, type()); + tmp_desc.reset(cvCreateMat(desc->rows, desc->cols, type())); cvConvert(desc, tmp_desc); desc = tmp_desc; } diff --git a/modules/legacy/src/oneway.cpp b/modules/legacy/src/oneway.cpp index 7fa4bee33e..43ded85939 100644 --- a/modules/legacy/src/oneway.cpp +++ b/modules/legacy/src/oneway.cpp @@ -1736,7 +1736,7 @@ namespace cv{ { std::vector features; Ptr surf_extractor = FeatureDetector::create("SURF"); - if( surf_extractor.empty() ) + if( !surf_extractor ) CV_Error(CV_StsNotImplemented, "OpenCV was built without SURF support"); surf_extractor->set("hessianThreshold", 1.0); //printf("Extracting SURF features..."); @@ -2186,7 +2186,7 @@ namespace cv{ { clear(); - if( _base.empty() ) + if( !_base ) base = _base; params = _params; @@ -2197,16 +2197,17 @@ namespace cv{ GenericDescriptorMatcher::clear(); prevTrainCount = 0; - if( !base.empty() ) + if( base ) base->clear(); } void OneWayDescriptorMatcher::train() { - if( base.empty() || prevTrainCount < (int)trainPointCollection.keypointCount() ) + if( !base || prevTrainCount < (int)trainPointCollection.keypointCount() ) { - base = new OneWayDescriptorObject( params.patchSize, params.poseCount, params.pcaFilename, - params.trainPath, params.trainImagesList, params.minScale, params.maxScale, params.stepScale ); + base.reset( + new OneWayDescriptorObject( params.patchSize, params.poseCount, params.pcaFilename, + params.trainPath, params.trainImagesList, params.minScale, params.maxScale, params.stepScale )); base->Allocate( (int)trainPointCollection.keypointCount() ); prevTrainCount = (int)trainPointCollection.keypointCount(); @@ -2270,8 +2271,9 @@ namespace cv{ void OneWayDescriptorMatcher::read( const FileNode &fn ) { - base = new OneWayDescriptorObject( params.patchSize, params.poseCount, String (), String (), String (), - params.minScale, params.maxScale, params.stepScale ); + base.reset( + new OneWayDescriptorObject( params.patchSize, params.poseCount, String (), String (), String (), + params.minScale, params.maxScale, params.stepScale )); base->Read (fn); } @@ -2282,12 +2284,12 @@ namespace cv{ bool OneWayDescriptorMatcher::empty() const { - return base.empty() || base->empty(); + return !base || base->empty(); } Ptr OneWayDescriptorMatcher::clone( bool emptyTrainData ) const { - OneWayDescriptorMatcher* matcher = new OneWayDescriptorMatcher( params ); + Ptr matcher = makePtr( params ); if( !emptyTrainData ) { diff --git a/modules/legacy/src/planardetect.cpp b/modules/legacy/src/planardetect.cpp index 2bffea0ed7..fa9152d474 100644 --- a/modules/legacy/src/planardetect.cpp +++ b/modules/legacy/src/planardetect.cpp @@ -1240,7 +1240,7 @@ FernDescriptorMatcher::FernDescriptorMatcher( const Params& _params ) params = _params; if( !params.filename.empty() ) { - classifier = new FernClassifier; + classifier = makePtr(); FileStorage fs(params.filename, FileStorage::READ); if( fs.isOpened() ) classifier->read( fs.getFirstTopLevelNode() ); @@ -1260,7 +1260,7 @@ void FernDescriptorMatcher::clear() void FernDescriptorMatcher::train() { - if( classifier.empty() || prevTrainCount < (int)trainPointCollection.keypointCount() ) + if( !classifier || prevTrainCount < (int)trainPointCollection.keypointCount() ) { assert( params.filename.empty() ); @@ -1268,9 +1268,10 @@ void FernDescriptorMatcher::train() for( size_t imgIdx = 0; imgIdx < trainPointCollection.imageCount(); imgIdx++ ) KeyPoint::convert( trainPointCollection.getKeypoints((int)imgIdx), points[imgIdx] ); - classifier = new FernClassifier( points, trainPointCollection.getImages(), std::vector >(), 0, // each points is a class - params.patchSize, params.signatureSize, params.nstructs, params.structSize, - params.nviews, params.compressionMethod, params.patchGenerator ); + classifier.reset( + new FernClassifier( points, trainPointCollection.getImages(), std::vector >(), 0, // each points is a class + params.patchSize, params.signatureSize, params.nstructs, params.structSize, + params.nviews, params.compressionMethod, params.patchGenerator )); } } @@ -1384,12 +1385,12 @@ void FernDescriptorMatcher::write( FileStorage& fs ) const bool FernDescriptorMatcher::empty() const { - return classifier.empty() || classifier->empty(); + return !classifier || classifier->empty(); } Ptr FernDescriptorMatcher::clone( bool emptyTrainData ) const { - FernDescriptorMatcher* matcher = new FernDescriptorMatcher( params ); + Ptr matcher = makePtr( params ); if( !emptyTrainData ) { CV_Error( CV_StsNotImplemented, "deep clone dunctionality is not implemented, because " diff --git a/modules/ml/include/opencv2/ml.hpp b/modules/ml/include/opencv2/ml.hpp index 5e7871da3e..2b84d67ca7 100644 --- a/modules/ml/include/opencv2/ml.hpp +++ b/modules/ml/include/opencv2/ml.hpp @@ -2148,7 +2148,7 @@ typedef CvANN_MLP NeuralNet_MLP; typedef CvGBTreesParams GradientBoostingTreeParams; typedef CvGBTrees GradientBoostingTrees; -template<> CV_EXPORTS void Ptr::delete_obj(); +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvDTreeSplit* obj) const; CV_EXPORTS bool initModule_ml(void); } diff --git a/modules/ml/src/ml_init.cpp b/modules/ml/src/ml_init.cpp index 3d6669c263..3ff7d9baee 100644 --- a/modules/ml/src/ml_init.cpp +++ b/modules/ml/src/ml_init.cpp @@ -56,7 +56,7 @@ CV_INIT_ALGORITHM(EM, "StatModel.EM", bool initModule_ml(void) { - Ptr em = createEM_hidden(); + Ptr em = createEM_ptr_hidden(); return em->info() != 0; } diff --git a/modules/ml/src/rtrees.cpp b/modules/ml/src/rtrees.cpp index fcb1baf6b0..c41b842142 100644 --- a/modules/ml/src/rtrees.cpp +++ b/modules/ml/src/rtrees.cpp @@ -126,7 +126,7 @@ void ForestTreeBestSplitFinder::operator()(const BlockedRange& range) } if( res && bestSplit->quality < split->quality ) - memcpy( (CvDTreeSplit*)bestSplit, (CvDTreeSplit*)split, splitSize ); + memcpy( bestSplit.get(), split.get(), splitSize ); } } } diff --git a/modules/ml/src/tree.cpp b/modules/ml/src/tree.cpp index d195385d71..3a67cdd375 100644 --- a/modules/ml/src/tree.cpp +++ b/modules/ml/src/tree.cpp @@ -1882,7 +1882,7 @@ double CvDTree::calc_node_dir( CvDTreeNode* node ) namespace cv { -template<> CV_EXPORTS void Ptr::delete_obj() +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvDTreeSplit* obj) const { fastFree(obj); } @@ -1893,12 +1893,12 @@ DTreeBestSplitFinder::DTreeBestSplitFinder( CvDTree* _tree, CvDTreeNode* _node) node = _node; splitSize = tree->get_data()->split_heap->elem_size; - bestSplit = (CvDTreeSplit*)fastMalloc(splitSize); - memset((CvDTreeSplit*)bestSplit, 0, splitSize); + bestSplit.reset((CvDTreeSplit*)fastMalloc(splitSize)); + memset(bestSplit.get(), 0, splitSize); bestSplit->quality = -1; bestSplit->condensed_idx = INT_MIN; - split = (CvDTreeSplit*)fastMalloc(splitSize); - memset((CvDTreeSplit*)split, 0, splitSize); + split.reset((CvDTreeSplit*)fastMalloc(splitSize)); + memset(split.get(), 0, splitSize); //haveSplit = false; } @@ -1908,10 +1908,10 @@ DTreeBestSplitFinder::DTreeBestSplitFinder( const DTreeBestSplitFinder& finder, node = finder.node; splitSize = tree->get_data()->split_heap->elem_size; - bestSplit = (CvDTreeSplit*)fastMalloc(splitSize); - memcpy((CvDTreeSplit*)(bestSplit), (const CvDTreeSplit*)finder.bestSplit, splitSize); - split = (CvDTreeSplit*)fastMalloc(splitSize); - memset((CvDTreeSplit*)split, 0, splitSize); + bestSplit.reset((CvDTreeSplit*)fastMalloc(splitSize)); + memcpy(bestSplit.get(), finder.bestSplit.get(), splitSize); + split.reset((CvDTreeSplit*)fastMalloc(splitSize)); + memset(split.get(), 0, splitSize); } void DTreeBestSplitFinder::operator()(const BlockedRange& range) @@ -1944,14 +1944,14 @@ void DTreeBestSplitFinder::operator()(const BlockedRange& range) } if( res && bestSplit->quality < split->quality ) - memcpy( (CvDTreeSplit*)bestSplit, (CvDTreeSplit*)split, splitSize ); + memcpy( bestSplit.get(), split.get(), splitSize ); } } void DTreeBestSplitFinder::join( DTreeBestSplitFinder& rhs ) { if( bestSplit->quality < rhs.bestSplit->quality ) - memcpy( (CvDTreeSplit*)bestSplit, (CvDTreeSplit*)rhs.bestSplit, splitSize ); + memcpy( bestSplit.get(), rhs.bestSplit.get(), splitSize ); } } diff --git a/modules/nonfree/src/nonfree_init.cpp b/modules/nonfree/src/nonfree_init.cpp index 827853cfd6..ac804dd9a6 100644 --- a/modules/nonfree/src/nonfree_init.cpp +++ b/modules/nonfree/src/nonfree_init.cpp @@ -67,7 +67,7 @@ CV_INIT_ALGORITHM(SIFT, "Feature2D.SIFT", bool initModule_nonfree(void) { - Ptr sift = createSIFT_hidden(), surf = createSURF_hidden(); + Ptr sift = createSIFT_ptr_hidden(), surf = createSURF_ptr_hidden(); return sift->info() != 0 && surf->info() != 0; } diff --git a/modules/nonfree/test/test_features2d.cpp b/modules/nonfree/test/test_features2d.cpp index bff8a387f4..7c888e261e 100644 --- a/modules/nonfree/test/test_features2d.cpp +++ b/modules/nonfree/test/test_features2d.cpp @@ -231,7 +231,7 @@ void CV_FeatureDetectorTest::regressionTest() void CV_FeatureDetectorTest::run( int /*start_from*/ ) { - if( fdetector.empty() ) + if( !fdetector ) { ts->printf( cvtest::TS::LOG, "Feature detector is empty.\n" ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); @@ -464,7 +464,7 @@ protected: void run(int) { createDescriptorExtractor(); - if( dextractor.empty() ) + if( !dextractor ) { ts->printf(cvtest::TS::LOG, "Descriptor extractor is empty.\n"); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); @@ -1101,7 +1101,7 @@ protected: void run(int) { Ptr f = Algorithm::create("Feature2D." + fname); - if(f.empty()) + if(!f) return; string path = string(ts->get_data_path()) + "detectors_descriptors_evaluation/planar/"; string imgname1 = path + "box.png"; @@ -1156,7 +1156,7 @@ public: FeatureDetectorUsingMaskTest(const Ptr& featureDetector) : featureDetector_(featureDetector) { - CV_Assert(!featureDetector_.empty()); + CV_Assert(featureDetector_); } protected: diff --git a/modules/nonfree/test/test_keypoints.cpp b/modules/nonfree/test/test_keypoints.cpp index 3984f19d89..b046d7534c 100644 --- a/modules/nonfree/test/test_keypoints.cpp +++ b/modules/nonfree/test/test_keypoints.cpp @@ -62,7 +62,7 @@ protected: virtual void run(int) { cv::initModule_features2d(); - CV_Assert(!detector.empty()); + CV_Assert(detector); string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME; // Read the test image. diff --git a/modules/nonfree/test/test_rotation_and_scale_invariance.cpp b/modules/nonfree/test/test_rotation_and_scale_invariance.cpp index b63b8b7489..47efc60eb8 100644 --- a/modules/nonfree/test/test_rotation_and_scale_invariance.cpp +++ b/modules/nonfree/test/test_rotation_and_scale_invariance.cpp @@ -210,7 +210,7 @@ public: minKeyPointMatchesRatio(_minKeyPointMatchesRatio), minAngleInliersRatio(_minAngleInliersRatio) { - CV_Assert(!featureDetector.empty()); + CV_Assert(featureDetector); } protected: @@ -323,8 +323,8 @@ public: normType(_normType), minDescInliersRatio(_minDescInliersRatio) { - CV_Assert(!featureDetector.empty()); - CV_Assert(!descriptorExtractor.empty()); + CV_Assert(featureDetector); + CV_Assert(descriptorExtractor); } protected: @@ -410,7 +410,7 @@ public: minKeyPointMatchesRatio(_minKeyPointMatchesRatio), minScaleInliersRatio(_minScaleInliersRatio) { - CV_Assert(!featureDetector.empty()); + CV_Assert(featureDetector); } protected: @@ -530,8 +530,8 @@ public: normType(_normType), minDescInliersRatio(_minDescInliersRatio) { - CV_Assert(!featureDetector.empty()); - CV_Assert(!descriptorExtractor.empty()); + CV_Assert(featureDetector); + CV_Assert(descriptorExtractor); } protected: diff --git a/modules/objdetect/include/opencv2/objdetect.hpp b/modules/objdetect/include/opencv2/objdetect.hpp index febd3aed57..f1b371610d 100644 --- a/modules/objdetect/include/opencv2/objdetect.hpp +++ b/modules/objdetect/include/opencv2/objdetect.hpp @@ -141,7 +141,7 @@ public: static Ptr create(int type); }; -template<> CV_EXPORTS void Ptr::delete_obj(); +template<> CV_EXPORTS void DefaultDeleter::operator ()(CvHaarClassifierCascade* obj) const; enum { CASCADE_DO_CANNY_PRUNING = 1, CASCADE_SCALE_IMAGE = 2, diff --git a/modules/objdetect/include/opencv2/objdetect/erfilter.hpp b/modules/objdetect/include/opencv2/objdetect/erfilter.hpp index d1bfeaed0f..8a1b580c3a 100644 --- a/modules/objdetect/include/opencv2/objdetect/erfilter.hpp +++ b/modules/objdetect/include/opencv2/objdetect/erfilter.hpp @@ -171,7 +171,7 @@ public: \param nonMaxSuppression Whenever non-maximum suppression is done over the branch probabilities \param minProbability The minimum probability difference between local maxima and local minima ERs */ -CV_EXPORTS Ptr createERFilterNM1(const Ptr& cb = NULL, +CV_EXPORTS Ptr createERFilterNM1(const Ptr& cb = Ptr(), int thresholdDelta = 1, float minArea = 0.000025, float maxArea = 0.13, float minProbability = 0.2, bool nonMaxSuppression = true, @@ -190,7 +190,7 @@ CV_EXPORTS Ptr createERFilterNM1(const Ptr& cb = N if omitted tries to load a default classifier from file trained_classifierNM2.xml \param minProbability The minimum probability P(er|character) allowed for retreived ER's */ -CV_EXPORTS Ptr createERFilterNM2(const Ptr& cb = NULL, +CV_EXPORTS Ptr createERFilterNM2(const Ptr& cb = Ptr(), float minProbability = 0.85); } diff --git a/modules/objdetect/src/cascadedetect.cpp b/modules/objdetect/src/cascadedetect.cpp index 04ec41d24b..88f463faa0 100644 --- a/modules/objdetect/src/cascadedetect.cpp +++ b/modules/objdetect/src/cascadedetect.cpp @@ -467,7 +467,7 @@ bool HaarEvaluator::Feature :: read( const FileNode& node ) HaarEvaluator::HaarEvaluator() { - features = new std::vector(); + features = makePtr >(); } HaarEvaluator::~HaarEvaluator() { @@ -492,7 +492,7 @@ bool HaarEvaluator::read(const FileNode& node) Ptr HaarEvaluator::clone() const { - HaarEvaluator* ret = new HaarEvaluator; + Ptr ret = makePtr(); ret->origWinSize = origWinSize; ret->features = features; ret->featuresPtr = &(*ret->features)[0]; @@ -582,7 +582,7 @@ bool LBPEvaluator::Feature :: read(const FileNode& node ) LBPEvaluator::LBPEvaluator() { - features = new std::vector(); + features = makePtr >(); } LBPEvaluator::~LBPEvaluator() { @@ -603,7 +603,7 @@ bool LBPEvaluator::read( const FileNode& node ) Ptr LBPEvaluator::clone() const { - LBPEvaluator* ret = new LBPEvaluator; + Ptr ret = makePtr(); ret->origWinSize = origWinSize; ret->features = features; ret->featuresPtr = &(*ret->features)[0]; @@ -662,7 +662,7 @@ bool HOGEvaluator::Feature :: read( const FileNode& node ) HOGEvaluator::HOGEvaluator() { - features = new std::vector(); + features = makePtr >(); } HOGEvaluator::~HOGEvaluator() @@ -684,7 +684,7 @@ bool HOGEvaluator::read( const FileNode& node ) Ptr HOGEvaluator::clone() const { - HOGEvaluator* ret = new HOGEvaluator; + Ptr ret = makePtr(); ret->origWinSize = origWinSize; ret->features = features; ret->featuresPtr = &(*ret->features)[0]; @@ -849,7 +849,7 @@ CascadeClassifier::~CascadeClassifier() bool CascadeClassifier::empty() const { - return oldCascade.empty() && data.stages.empty(); + return !oldCascade && data.stages.empty(); } bool CascadeClassifier::load(const String& filename) @@ -867,13 +867,13 @@ bool CascadeClassifier::load(const String& filename) fs.release(); - oldCascade = Ptr((CvHaarClassifierCascade*)cvLoad(filename.c_str(), 0, 0, 0)); + oldCascade.reset((CvHaarClassifierCascade*)cvLoad(filename.c_str(), 0, 0, 0)); return !oldCascade.empty(); } int CascadeClassifier::runAt( Ptr& evaluator, Point pt, double& weight ) { - CV_Assert( oldCascade.empty() ); + CV_Assert( !oldCascade ); assert( data.featureType == FeatureEvaluator::HAAR || data.featureType == FeatureEvaluator::LBP || @@ -1022,7 +1022,7 @@ bool CascadeClassifier::detectSingleScale( const Mat& image, int stripCount, Siz #endif Mat currentMask; - if (!maskGenerator.empty()) { + if (maskGenerator) { currentMask=maskGenerator->generateMask(image); } @@ -1097,7 +1097,7 @@ void CascadeClassifier::detectMultiScaleNoGrouping( const Mat& image, std::vecto { candidates.clear(); - if (!maskGenerator.empty()) + if (maskGenerator) maskGenerator->initializeMask(image); if( maxObjectSize.height == 0 || maxObjectSize.width == 0 ) @@ -1350,7 +1350,7 @@ bool CascadeClassifier::read(const FileNode& root) return featureEvaluator->read(fn); } -template<> void Ptr::delete_obj() +template<> void DefaultDeleter::operator ()(CvHaarClassifierCascade* obj) const { cvReleaseHaarClassifierCascade(&obj); } } // namespace cv diff --git a/modules/objdetect/src/erfilter.cpp b/modules/objdetect/src/erfilter.cpp index ac8fc70e84..b8e964f5d8 100644 --- a/modules/objdetect/src/erfilter.cpp +++ b/modules/objdetect/src/erfilter.cpp @@ -179,7 +179,6 @@ ERFilterNM::ERFilterNM() minProbabilityDiff = 1.; num_accepted_regions = 0; num_rejected_regions = 0; - classifier = NULL; } // the key method. Takes image on input, vector of ERStat is output for the first stage, @@ -1085,10 +1084,10 @@ Ptr createERFilterNM1(const Ptr& cb, int threshold CV_Assert( (thresholdDelta >= 0) && (thresholdDelta <= 128) ); CV_Assert( (minProbabilityDiff >= 0.) && (minProbabilityDiff <= 1.) ); - Ptr filter = new ERFilterNM(); + Ptr filter = makePtr(); if (cb == NULL) - filter->setCallback(new ERClassifierNM1()); + filter->setCallback(makePtr()); else filter->setCallback(cb); @@ -1119,11 +1118,11 @@ Ptr createERFilterNM2(const Ptr& cb, float minProb CV_Assert( (minProbability >= 0.) && (minProbability <= 1.) ); - Ptr filter = new ERFilterNM(); + Ptr filter = makePtr(); if (cb == NULL) - filter->setCallback(new ERClassifierNM2()); + filter->setCallback(makePtr()); else filter->setCallback(cb); diff --git a/modules/objdetect/src/haar.cpp b/modules/objdetect/src/haar.cpp index 2212b6c67a..cbb60b0917 100644 --- a/modules/objdetect/src/haar.cpp +++ b/modules/objdetect/src/haar.cpp @@ -1536,15 +1536,15 @@ cvHaarDetectObjectsForROC( const CvArr* _img, maxSize.width = img->cols; } - temp = cvCreateMat( img->rows, img->cols, CV_8UC1 ); - sum = cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ); - sqsum = cvCreateMat( img->rows + 1, img->cols + 1, CV_64FC1 ); + temp.reset(cvCreateMat( img->rows, img->cols, CV_8UC1 )); + sum.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 )); + sqsum.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_64FC1 )); if( !cascade->hid_cascade ) icvCreateHidHaarClassifierCascade(cascade); if( cascade->hid_cascade->has_tilted_features ) - tilted = cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ); + tilted.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 )); result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), storage ); @@ -1566,7 +1566,7 @@ cvHaarDetectObjectsForROC( const CvArr* _img, if( use_ipp ) normImg = cvCreateMat( img->rows, img->cols, CV_32FC1 ); #endif - imgSmall = cvCreateMat( img->rows + 1, img->cols + 1, CV_8UC1 ); + imgSmall.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_8UC1 )); for( factor = 1; ; factor *= scaleFactor ) { @@ -1635,7 +1635,7 @@ cvHaarDetectObjectsForROC( const CvArr* _img, if( doCannyPruning ) { - sumcanny = cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ); + sumcanny.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 )); cvCanny( img, temp, 0, 50, 3 ); cvIntegral( temp, sumcanny ); } diff --git a/modules/objdetect/src/hog.cpp b/modules/objdetect/src/hog.cpp index 80b5972597..5cc7f6a61b 100644 --- a/modules/objdetect/src/hog.cpp +++ b/modules/objdetect/src/hog.cpp @@ -1353,8 +1353,7 @@ public: { if(ptr && _fs) { - FileStorage fs(_fs); - fs.fs.addref(); + FileStorage fs(_fs, false); ((const _ClsName*)ptr)->write(fs, String(name)); } } diff --git a/modules/objdetect/src/linemod.cpp b/modules/objdetect/src/linemod.cpp index 0fd3433a50..e8fc8e4aac 100644 --- a/modules/objdetect/src/linemod.cpp +++ b/modules/objdetect/src/linemod.cpp @@ -204,11 +204,11 @@ void QuantizedPyramid::selectScatteredFeatures(const std::vector& can Ptr Modality::create(const String& modality_type) { if (modality_type == "ColorGradient") - return new ColorGradient(); + return makePtr(); else if (modality_type == "DepthNormal") - return new DepthNormal(); + return makePtr(); else - return NULL; + return Ptr(); } Ptr Modality::create(const FileNode& fn) @@ -574,7 +574,7 @@ String ColorGradient::name() const Ptr ColorGradient::processImpl(const Mat& src, const Mat& mask) const { - return new ColorGradientPyramid(src, mask, weak_threshold, num_features, strong_threshold); + return makePtr(src, mask, weak_threshold, num_features, strong_threshold); } void ColorGradient::read(const FileNode& fn) @@ -889,8 +889,8 @@ String DepthNormal::name() const Ptr DepthNormal::processImpl(const Mat& src, const Mat& mask) const { - return new DepthNormalPyramid(src, mask, distance_threshold, difference_threshold, - num_features, extract_threshold); + return makePtr(src, mask, distance_threshold, difference_threshold, + num_features, extract_threshold); } void DepthNormal::read(const FileNode& fn) @@ -1828,16 +1828,16 @@ static const int T_DEFAULTS[] = {5, 8}; Ptr getDefaultLINE() { std::vector< Ptr > modalities; - modalities.push_back(new ColorGradient); - return new Detector(modalities, std::vector(T_DEFAULTS, T_DEFAULTS + 2)); + modalities.push_back(makePtr()); + return makePtr(modalities, std::vector(T_DEFAULTS, T_DEFAULTS + 2)); } Ptr getDefaultLINEMOD() { std::vector< Ptr > modalities; - modalities.push_back(new ColorGradient); - modalities.push_back(new DepthNormal); - return new Detector(modalities, std::vector(T_DEFAULTS, T_DEFAULTS + 2)); + modalities.push_back(makePtr()); + modalities.push_back(makePtr()); + return makePtr(modalities, std::vector(T_DEFAULTS, T_DEFAULTS + 2)); } } // namespace linemod diff --git a/modules/objdetect/test/test_cascadeandhog.cpp b/modules/objdetect/test/test_cascadeandhog.cpp index b4fd541a18..a301099058 100644 --- a/modules/objdetect/test/test_cascadeandhog.cpp +++ b/modules/objdetect/test/test_cascadeandhog.cpp @@ -426,10 +426,10 @@ int CV_CascadeDetectorTest::detectMultiScale_C( const string& filename, int di, const Mat& img, vector& objects ) { - Ptr c_cascade = cvLoadHaarClassifierCascade(filename.c_str(), cvSize(0,0)); - Ptr storage = cvCreateMemStorage(); + Ptr c_cascade(cvLoadHaarClassifierCascade(filename.c_str(), cvSize(0,0))); + Ptr storage(cvCreateMemStorage()); - if( c_cascade.empty() ) + if( !c_cascade ) { ts->printf( cvtest::TS::LOG, "cascade %s can not be opened"); return cvtest::TS::FAIL_INVALID_TEST_DATA; diff --git a/modules/ocl/src/filtering.cpp b/modules/ocl/src/filtering.cpp index 713854299d..4c952b8372 100644 --- a/modules/ocl/src/filtering.cpp +++ b/modules/ocl/src/filtering.cpp @@ -163,7 +163,7 @@ public: Ptr cv::ocl::createFilter2D_GPU(const Ptr filter2D) { - return Ptr(new Filter2DEngine_GPU(filter2D)); + return makePtr(filter2D); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -452,7 +452,7 @@ Ptr cv::ocl::createMorphologyFilter_GPU(int op, int type, cons Ptr filter2D = getMorphologyFilter_GPU(op, type, kernel, ksize, anchor); - return Ptr(new MorphologyFilterEngine_GPU(filter2D, iterations)); + return makePtr(filter2D, iterations); } namespace @@ -690,8 +690,8 @@ Ptr cv::ocl::getLinearFilter_GPU(int srcType, int dstType, const normalizeKernel(kernel, gpu_krnl, CV_32FC1); normalizeAnchor(norm_archor, ksize); - return Ptr(new LinearFilter_GPU(ksize, anchor, gpu_krnl, GPUFilter2D_callers[CV_MAT_CN(srcType)], - borderType)); + return makePtr(ksize, anchor, gpu_krnl, GPUFilter2D_callers[CV_MAT_CN(srcType)], + borderType); } Ptr cv::ocl::createLinearFilter_GPU(int srcType, int dstType, const Mat &kernel, const Point &anchor, @@ -773,7 +773,7 @@ public: Ptr cv::ocl::createSeparableFilter_GPU(const Ptr &rowFilter, const Ptr &columnFilter) { - return Ptr(new SeparableFilterEngine_GPU(rowFilter, columnFilter)); + return makePtr(rowFilter, columnFilter); } /* @@ -1044,8 +1044,8 @@ Ptr cv::ocl::getBoxFilter_GPU(int srcType, int dstType, normalizeAnchor(anchor, ksize); - return Ptr(new GPUBoxFilter(ksize, anchor, - borderType, FilterBox_callers[(CV_MAT_DEPTH(srcType) == CV_32F)][CV_MAT_CN(srcType)])); + return makePtr(ksize, anchor, + borderType, FilterBox_callers[(CV_MAT_DEPTH(srcType) == CV_32F)][CV_MAT_CN(srcType)]); } Ptr cv::ocl::createBoxFilter_GPU(int srcType, int dstType, @@ -1228,8 +1228,8 @@ Ptr cv::ocl::getLinearRowFilter_GPU(int srcType, int /*bufTyp normalizeAnchor(anchor, ksize); - return Ptr(new GpuLinearRowFilter(ksize, anchor, mat_kernel, - gpuFilter1D_callers[CV_MAT_DEPTH(srcType)], bordertype)); + return makePtr(ksize, anchor, mat_kernel, + gpuFilter1D_callers[CV_MAT_DEPTH(srcType)], bordertype); } namespace @@ -1397,8 +1397,8 @@ Ptr cv::ocl::getLinearColumnFilter_GPU(int /*bufType*/, in normalizeAnchor(anchor, ksize); - return Ptr(new GpuLinearColumnFilter(ksize, anchor, mat_kernel, - gpuFilter1D_callers[CV_MAT_DEPTH(dstType)], bordertype)); + return makePtr(ksize, anchor, mat_kernel, + gpuFilter1D_callers[CV_MAT_DEPTH(dstType)], bordertype); } Ptr cv::ocl::createSeparableLinearFilter_GPU(int srcType, int dstType, diff --git a/modules/ocl/src/imgproc.cpp b/modules/ocl/src/imgproc.cpp index 143e0e8a91..0dc7fe9cea 100644 --- a/modules/ocl/src/imgproc.cpp +++ b/modules/ocl/src/imgproc.cpp @@ -1692,7 +1692,7 @@ namespace cv cv::Ptr createCLAHE(double clipLimit, cv::Size tileGridSize) { - return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height); + return makePtr(clipLimit, tileGridSize.width, tileGridSize.height); } //////////////////////////////////bilateralFilter//////////////////////////////////////////////////// diff --git a/modules/ocl/src/mcwutil.cpp b/modules/ocl/src/mcwutil.cpp index 612165165c..c520cb8d48 100644 --- a/modules/ocl/src/mcwutil.cpp +++ b/modules/ocl/src/mcwutil.cpp @@ -246,7 +246,7 @@ namespace cv Ptr bindTexturePtr(const oclMat &mat) { - return Ptr(new TextureCL(bindTexture(mat), mat.rows, mat.cols, mat.type())); + return makePtr(bindTexture(mat), mat.rows, mat.cols, mat.type()); } void releaseTexture(cl_mem& texture) { diff --git a/modules/photo/src/inpaint.cpp b/modules/photo/src/inpaint.cpp index ec91e3c1bf..f91db5f545 100644 --- a/modules/photo/src/inpaint.cpp +++ b/modules/photo/src/inpaint.cpp @@ -718,7 +718,7 @@ icvNSInpaintFMM(const CvMat *f, CvMat *t, CvMat *out, int range, CvPriorityQueue } namespace cv { -template<> void cv::Ptr::delete_obj() +template<> void cv::DefaultDeleter::operator ()(IplConvKernel* obj) const { cvReleaseStructuringElement(&obj); } @@ -759,11 +759,11 @@ cvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_i ecols = input_img->cols + 2; erows = input_img->rows + 2; - f = cvCreateMat(erows, ecols, CV_8UC1); - t = cvCreateMat(erows, ecols, CV_32FC1); - band = cvCreateMat(erows, ecols, CV_8UC1); - mask = cvCreateMat(erows, ecols, CV_8UC1); - el_cross = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_CROSS,NULL); + f.reset(cvCreateMat(erows, ecols, CV_8UC1)); + t.reset(cvCreateMat(erows, ecols, CV_32FC1)); + band.reset(cvCreateMat(erows, ecols, CV_8UC1)); + mask.reset(cvCreateMat(erows, ecols, CV_8UC1)); + el_cross.reset(cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_CROSS,NULL)); cvCopy( input_img, output_img ); cvSet(mask,cvScalar(KNOWN,0,0,0)); @@ -772,7 +772,7 @@ cvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_i cvSet(f,cvScalar(KNOWN,0,0,0)); cvSet(t,cvScalar(1.0e6f,0,0,0)); cvDilate(mask,band,el_cross,1); // image with narrow band - Heap=new CvPriorityQueueFloat; + Heap=cv::makePtr(); if (!Heap->Init(band)) return; cvSub(band,mask,band,NULL); @@ -785,12 +785,12 @@ cvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_i if( flags == cv::INPAINT_TELEA ) { - out = cvCreateMat(erows, ecols, CV_8UC1); - el_range = cvCreateStructuringElementEx(2*range+1,2*range+1, - range,range,CV_SHAPE_RECT,NULL); + out.reset(cvCreateMat(erows, ecols, CV_8UC1)); + el_range.reset(cvCreateStructuringElementEx(2*range+1,2*range+1, + range,range,CV_SHAPE_RECT,NULL)); cvDilate(mask,out,el_range,1); cvSub(out,mask,out,NULL); - Out=new CvPriorityQueueFloat; + Out=cv::makePtr(); if (!Out->Init(out)) return; if (!Out->Add(band)) diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index e94da958af..6b50abcc53 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -1058,7 +1058,7 @@ bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * na template bool pyopencv_to(PyObject *o, Ptr& p, const char *name) { - p = new T(); + p = makePtr(); return pyopencv_to(o, *p, name); } diff --git a/modules/python/src2/gen2.py b/modules/python/src2/gen2.py index 816a386c02..c5df21a399 100755 --- a/modules/python/src2/gen2.py +++ b/modules/python/src2/gen2.py @@ -13,20 +13,24 @@ ignored_arg_types = ["RNG*"] gen_template_check_self = Template(""" if(!PyObject_TypeCheck(self, &pyopencv_${name}_Type)) return failmsgp("Incorrect type of self (must be '${name}' or its derivative)"); - $cname* _self_ = ${amp}((pyopencv_${name}_t*)self)->v; + $cname* _self_ = ${amp}((pyopencv_${name}_t*)self)->v${get}; """) gen_template_check_self_algo = Template(""" if(!PyObject_TypeCheck(self, &pyopencv_${name}_Type)) return failmsgp("Incorrect type of self (must be '${name}' or its derivative)"); - $cname* _self_ = dynamic_cast<$cname*>(${amp}((pyopencv_${name}_t*)self)->v.obj); + $cname* _self_ = dynamic_cast<$cname*>(${amp}((pyopencv_${name}_t*)self)->v.get()); """) -gen_template_call_constructor = Template("""self = PyObject_NEW(pyopencv_${name}_t, &pyopencv_${name}_Type); +gen_template_call_constructor_prelude = Template("""self = PyObject_NEW(pyopencv_${name}_t, &pyopencv_${name}_Type); new (&(self->v)) Ptr<$cname>(); // init Ptr with placement new - if(self) ERRWRAP2(self->v = new $cname""") + if(self) """) -gen_template_simple_call_constructor = Template("""self = PyObject_NEW(pyopencv_${name}_t, &pyopencv_${name}_Type); - if(self) ERRWRAP2(self->v = $cname""") +gen_template_call_constructor = Template("""self->v.reset(new ${cname}${args})""") + +gen_template_simple_call_constructor_prelude = Template("""self = PyObject_NEW(pyopencv_${name}_t, &pyopencv_${name}_Type); + if(self) """) + +gen_template_simple_call_constructor = Template("""self->v = ${cname}${args}""") gen_template_parse_args = Template("""const char* keywords[] = { $kw_list, NULL }; if( PyArg_ParseTupleAndKeywords(args, kw, "$fmtspec", (char**)keywords, $parse_arglist)$code_cvt )""") @@ -34,7 +38,7 @@ gen_template_parse_args = Template("""const char* keywords[] = { $kw_list, NULL gen_template_func_body = Template("""$code_decl $code_parse { - $code_fcall; + ${code_prelude}ERRWRAP2($code_fcall); $code_ret; } """) @@ -124,7 +128,7 @@ template<> bool pyopencv_to(PyObject* src, Ptr<${cname}>& dst, const char* name) failmsg("Expected ${cname} for argument '%%s'", name); return false; } - dst = ((pyopencv_${name}_t*)src)->v; + dst = ((pyopencv_${name}_t*)src)->v.dynamicCast<${cname}>(); return true; } @@ -187,7 +191,7 @@ static PyObject* pyopencv_${name}_get_${member}(pyopencv_${name}_t* p, void *clo gen_template_get_prop_algo = Template(""" static PyObject* pyopencv_${name}_get_${member}(pyopencv_${name}_t* p, void *closure) { - return pyopencv_from(dynamic_cast<$cname*>(p->v.obj)${access}${member}); + return pyopencv_from(dynamic_cast<$cname*>(p->v.get())${access}${member}); } """) @@ -211,7 +215,7 @@ static int pyopencv_${name}_set_${member}(pyopencv_${name}_t* p, PyObject *value PyErr_SetString(PyExc_TypeError, "Cannot delete the ${member} attribute"); return -1; } - return pyopencv_to(value, dynamic_cast<$cname*>(p->v.obj)${access}${member}) ? 0 : -1; + return pyopencv_to(value, dynamic_cast<$cname*>(p->v.get())${access}${member}) ? 0 : -1; } """) @@ -559,39 +563,22 @@ class FuncInfo(object): if self.classname: selfinfo = all_classes[self.classname] if not self.isconstructor: - amp = "" - if selfinfo.issimple: - amp = "&" + amp = "&" if selfinfo.issimple else "" if selfinfo.isalgorithm: code += gen_template_check_self_algo.substitute(name=selfinfo.name, cname=selfinfo.cname, amp=amp) else: - code += gen_template_check_self.substitute(name=selfinfo.name, cname=selfinfo.cname, amp=amp) + get = "" if selfinfo.issimple else ".get()" + code += gen_template_check_self.substitute(name=selfinfo.name, cname=selfinfo.cname, amp=amp, get=get) fullname = selfinfo.wname + "." + fullname all_code_variants = [] declno = -1 for v in self.variants: code_decl = "" - code_fcall = "" code_ret = "" code_cvt_list = [] - if self.isconstructor: - code_decl += " pyopencv_%s_t* self = 0;\n" % selfinfo.name - templ = gen_template_call_constructor - if selfinfo.issimple: - templ = gen_template_simple_call_constructor - code_fcall = templ.substitute(name=selfinfo.name, cname=selfinfo.cname) - else: - code_fcall = "ERRWRAP2( " - if v.rettype: - code_decl += " " + v.rettype + " retval;\n" - code_fcall += "retval = " - if ismethod: - code_fcall += "_self_->" + self.cname - else: - code_fcall += self.cname - code_fcall += "(" + code_args = "(" all_cargs = [] parse_arglist = [] @@ -605,9 +592,9 @@ class FuncInfo(object): if not defval and a.tp.endswith("*"): defval = 0 assert defval - if not code_fcall.endswith("("): - code_fcall += ", " - code_fcall += defval + if not code_args.endswith("("): + code_args += ", " + code_args += defval all_cargs.append([[None, ""], ""]) continue tp1 = tp = a.tp @@ -649,11 +636,34 @@ class FuncInfo(object): else: code_decl += " %s %s;\n" % (amapping[0], a.name) - if not code_fcall.endswith("("): - code_fcall += ", " - code_fcall += amp + a.name + if not code_args.endswith("("): + code_args += ", " + code_args += amp + a.name - code_fcall += "))" + code_args += ")" + + if self.isconstructor: + code_decl += " pyopencv_%s_t* self = 0;\n" % selfinfo.name + if selfinfo.issimple: + templ_prelude = gen_template_simple_call_constructor_prelude + templ = gen_template_simple_call_constructor + else: + templ_prelude = gen_template_call_constructor_prelude + templ = gen_template_call_constructor + + code_prelude = templ_prelude.substitute(name=selfinfo.name, cname=selfinfo.cname) + code_fcall = templ.substitute(name=selfinfo.name, cname=selfinfo.cname, args=code_args) + else: + code_prelude = "" + code_fcall = "" + if v.rettype: + code_decl += " " + v.rettype + " retval;\n" + code_fcall += "retval = " + if ismethod: + code_fcall += "_self_->" + self.cname + else: + code_fcall += self.cname + code_fcall += code_args if code_cvt_list: code_cvt_list = [""] + code_cvt_list @@ -706,7 +716,7 @@ class FuncInfo(object): (fmtspec, ", ".join(["pyopencv_from(" + aname + ")" for aname, argno in v.py_outlist])) all_code_variants.append(gen_template_func_body.substitute(code_decl=code_decl, - code_parse=code_parse, code_fcall=code_fcall, code_ret=code_ret)) + code_parse=code_parse, code_prelude=code_prelude, code_fcall=code_fcall, code_ret=code_ret)) if len(all_code_variants)==1: # if the function/method has only 1 signature, then just put it diff --git a/modules/softcascade/src/detector_cuda.cpp b/modules/softcascade/src/detector_cuda.cpp index 6747c232ca..328b7d42dd 100644 --- a/modules/softcascade/src/detector_cuda.cpp +++ b/modules/softcascade/src/detector_cuda.cpp @@ -58,7 +58,7 @@ cv::softcascade::ChannelsProcessor::ChannelsProcessor() { throw_no_cuda(); } cv::softcascade::ChannelsProcessor::~ChannelsProcessor() { throw_no_cuda(); } cv::Ptr cv::softcascade::ChannelsProcessor::create(const int, const int, const int) -{ throw_no_cuda(); return cv::Ptr(0); } +{ throw_no_cuda(); return cv::Ptr(); } #else @@ -594,7 +594,7 @@ private: cv::Ptr cv::softcascade::ChannelsProcessor::create(const int s, const int b, const int m) { CV_Assert((m && SEPARABLE)); - return cv::Ptr(new SeparablePreprocessor(s, b)); + return makePtr(s, b); } cv::softcascade::ChannelsProcessor::ChannelsProcessor() { } diff --git a/modules/softcascade/src/softcascade_init.cpp b/modules/softcascade/src/softcascade_init.cpp index 6978c4a8a8..6f3c8b6a5d 100644 --- a/modules/softcascade/src/softcascade_init.cpp +++ b/modules/softcascade/src/softcascade_init.cpp @@ -58,8 +58,8 @@ CV_INIT_ALGORITHM(SCascade, "CascadeDetector.SCascade", bool initModule_softcascade(void) { - Ptr sc = createSCascade_hidden(); - Ptr sc1 = createDetector_hidden(); + Ptr sc = createSCascade_ptr_hidden(); + Ptr sc1 = createDetector_ptr_hidden(); return (sc1->info() != 0) && (sc->info() != 0); } diff --git a/modules/stitching/include/opencv2/stitching/warpers.hpp b/modules/stitching/include/opencv2/stitching/warpers.hpp index 0dae219bb1..da5fe26183 100644 --- a/modules/stitching/include/opencv2/stitching/warpers.hpp +++ b/modules/stitching/include/opencv2/stitching/warpers.hpp @@ -58,33 +58,33 @@ public: class PlaneWarper : public WarperCreator { public: - Ptr create(float scale) const { return new detail::PlaneWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class CylindricalWarper: public WarperCreator { public: - Ptr create(float scale) const { return new detail::CylindricalWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class SphericalWarper: public WarperCreator { public: - Ptr create(float scale) const { return new detail::SphericalWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class FisheyeWarper : public WarperCreator { public: - Ptr create(float scale) const { return new detail::FisheyeWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class StereographicWarper: public WarperCreator { public: - Ptr create(float scale) const { return new detail::StereographicWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class CompressedRectilinearWarper: public WarperCreator @@ -95,7 +95,7 @@ public: { a = A; b = B; } - Ptr create(float scale) const { return new detail::CompressedRectilinearWarper(scale, a, b); } + Ptr create(float scale) const { return makePtr(scale, a, b); } }; class CompressedRectilinearPortraitWarper: public WarperCreator @@ -106,7 +106,7 @@ public: { a = A; b = B; } - Ptr create(float scale) const { return new detail::CompressedRectilinearPortraitWarper(scale, a, b); } + Ptr create(float scale) const { return makePtr(scale, a, b); } }; class PaniniWarper: public WarperCreator @@ -117,7 +117,7 @@ public: { a = A; b = B; } - Ptr create(float scale) const { return new detail::PaniniWarper(scale, a, b); } + Ptr create(float scale) const { return makePtr(scale, a, b); } }; class PaniniPortraitWarper: public WarperCreator @@ -128,19 +128,19 @@ public: { a = A; b = B; } - Ptr create(float scale) const { return new detail::PaniniPortraitWarper(scale, a, b); } + Ptr create(float scale) const { return makePtr(scale, a, b); } }; class MercatorWarper: public WarperCreator { public: - Ptr create(float scale) const { return new detail::MercatorWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class TransverseMercatorWarper: public WarperCreator { public: - Ptr create(float scale) const { return new detail::TransverseMercatorWarper(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; @@ -149,21 +149,21 @@ public: class PlaneWarperGpu: public WarperCreator { public: - Ptr create(float scale) const { return new detail::PlaneWarperGpu(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class CylindricalWarperGpu: public WarperCreator { public: - Ptr create(float scale) const { return new detail::CylindricalWarperGpu(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; class SphericalWarperGpu: public WarperCreator { public: - Ptr create(float scale) const { return new detail::SphericalWarperGpu(scale); } + Ptr create(float scale) const { return makePtr(scale); } }; #endif diff --git a/modules/stitching/perf/perf_stich.cpp b/modules/stitching/perf/perf_stich.cpp index e42dea968a..8cf89651fe 100644 --- a/modules/stitching/perf/perf_stich.cpp +++ b/modules/stitching/perf/perf_stich.cpp @@ -34,12 +34,12 @@ PERF_TEST_P(stitch, a123, TEST_DETECTORS) imgs.push_back( imread( getDataPath("stitching/a3.png") ) ); Ptr featuresFinder = GetParam() == "orb" - ? (detail::FeaturesFinder*)new detail::OrbFeaturesFinder() - : (detail::FeaturesFinder*)new detail::SurfFeaturesFinder(); + ? Ptr(new detail::OrbFeaturesFinder()) + : Ptr(new detail::SurfFeaturesFinder()); Ptr featuresMatcher = GetParam() == "orb" - ? new detail::BestOf2NearestMatcher(false, ORB_MATCH_CONFIDENCE) - : new detail::BestOf2NearestMatcher(false, SURF_MATCH_CONFIDENCE); + ? makePtr(false, ORB_MATCH_CONFIDENCE) + : makePtr(false, SURF_MATCH_CONFIDENCE); declare.time(30 * 20).iterations(20); @@ -48,7 +48,7 @@ PERF_TEST_P(stitch, a123, TEST_DETECTORS) Stitcher stitcher = Stitcher::createDefault(); stitcher.setFeaturesFinder(featuresFinder); stitcher.setFeaturesMatcher(featuresMatcher); - stitcher.setWarper(new SphericalWarper()); + stitcher.setWarper(makePtr()); stitcher.setRegistrationResol(WORK_MEGAPIX); startTimer(); @@ -72,12 +72,12 @@ PERF_TEST_P(stitch, b12, TEST_DETECTORS) imgs.push_back( imread( getDataPath("stitching/b2.png") ) ); Ptr featuresFinder = GetParam() == "orb" - ? (detail::FeaturesFinder*)new detail::OrbFeaturesFinder() - : (detail::FeaturesFinder*)new detail::SurfFeaturesFinder(); + ? Ptr(new detail::OrbFeaturesFinder()) + : Ptr(new detail::SurfFeaturesFinder()); Ptr featuresMatcher = GetParam() == "orb" - ? new detail::BestOf2NearestMatcher(false, ORB_MATCH_CONFIDENCE) - : new detail::BestOf2NearestMatcher(false, SURF_MATCH_CONFIDENCE); + ? makePtr(false, ORB_MATCH_CONFIDENCE) + : makePtr(false, SURF_MATCH_CONFIDENCE); declare.time(30 * 20).iterations(20); @@ -86,7 +86,7 @@ PERF_TEST_P(stitch, b12, TEST_DETECTORS) Stitcher stitcher = Stitcher::createDefault(); stitcher.setFeaturesFinder(featuresFinder); stitcher.setFeaturesMatcher(featuresMatcher); - stitcher.setWarper(new SphericalWarper()); + stitcher.setWarper(makePtr()); stitcher.setRegistrationResol(WORK_MEGAPIX); startTimer(); @@ -114,13 +114,13 @@ PERF_TEST_P( match, bestOf2Nearest, TEST_DETECTORS) Ptr matcher; if (GetParam() == "surf") { - finder = new detail::SurfFeaturesFinder(); - matcher = new detail::BestOf2NearestMatcher(false, SURF_MATCH_CONFIDENCE); + finder = makePtr(); + matcher = makePtr(false, SURF_MATCH_CONFIDENCE); } else if (GetParam() == "orb") { - finder = new detail::OrbFeaturesFinder(); - matcher = new detail::BestOf2NearestMatcher(false, ORB_MATCH_CONFIDENCE); + finder = makePtr(); + matcher = makePtr(false, ORB_MATCH_CONFIDENCE); } else { @@ -169,13 +169,13 @@ PERF_TEST_P( matchVector, bestOf2NearestVectorFeatures, testing::Combine( int featuresVectorSize = get<1>(GetParam()); if (detectorName == "surf") { - finder = new detail::SurfFeaturesFinder(); - matcher = new detail::BestOf2NearestMatcher(false, SURF_MATCH_CONFIDENCE); + finder = makePtr(); + matcher = makePtr(false, SURF_MATCH_CONFIDENCE); } else if (detectorName == "orb") { - finder = new detail::OrbFeaturesFinder(); - matcher = new detail::BestOf2NearestMatcher(false, ORB_MATCH_CONFIDENCE); + finder = makePtr(); + matcher = makePtr(false, ORB_MATCH_CONFIDENCE); } else { diff --git a/modules/stitching/src/blenders.cpp b/modules/stitching/src/blenders.cpp index ca4b991323..3e9cfb7c7d 100644 --- a/modules/stitching/src/blenders.cpp +++ b/modules/stitching/src/blenders.cpp @@ -50,13 +50,13 @@ static const float WEIGHT_EPS = 1e-5f; Ptr Blender::createDefault(int type, bool try_gpu) { if (type == NO) - return new Blender(); + return makePtr(); if (type == FEATHER) - return new FeatherBlender(); + return makePtr(); if (type == MULTI_BAND) - return new MultiBandBlender(try_gpu); + return makePtr(try_gpu); CV_Error(Error::StsBadArg, "unsupported blending method"); - return NULL; + return Ptr(); } diff --git a/modules/stitching/src/exposure_compensate.cpp b/modules/stitching/src/exposure_compensate.cpp index 0a22daeb7e..78ce6d3714 100644 --- a/modules/stitching/src/exposure_compensate.cpp +++ b/modules/stitching/src/exposure_compensate.cpp @@ -48,13 +48,13 @@ namespace detail { Ptr ExposureCompensator::createDefault(int type) { if (type == NO) - return new NoExposureCompensator(); + return makePtr(); if (type == GAIN) - return new GainCompensator(); + return makePtr(); if (type == GAIN_BLOCKS) - return new BlocksGainCompensator(); + return makePtr(); CV_Error(Error::StsBadArg, "unsupported exposure compensation method"); - return NULL; + return Ptr(); } diff --git a/modules/stitching/src/matchers.cpp b/modules/stitching/src/matchers.cpp index 013f32790c..f463518b63 100644 --- a/modules/stitching/src/matchers.cpp +++ b/modules/stitching/src/matchers.cpp @@ -155,8 +155,8 @@ void CpuMatcher::match(const ImageFeatures &features1, const ImageFeatures &feat matches_info.matches.clear(); - Ptr indexParams = new flann::KDTreeIndexParams(); - Ptr searchParams = new flann::SearchParams(); + Ptr indexParams = makePtr(); + Ptr searchParams = makePtr(); if (features2.descriptors.depth() == CV_8U) { @@ -314,7 +314,7 @@ SurfFeaturesFinder::SurfFeaturesFinder(double hess_thresh, int num_octaves, int if (num_octaves_descr == num_octaves && num_layers_descr == num_layers) { surf = Algorithm::create("Feature2D.SURF"); - if( surf.empty() ) + if( !surf ) CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" ); surf->set("hessianThreshold", hess_thresh); surf->set("nOctaves", num_octaves); @@ -325,7 +325,7 @@ SurfFeaturesFinder::SurfFeaturesFinder(double hess_thresh, int num_octaves, int detector_ = Algorithm::create("Feature2D.SURF"); extractor_ = Algorithm::create("Feature2D.SURF"); - if( detector_.empty() || extractor_.empty() ) + if( !detector_ || !extractor_ ) CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" ); detector_->set("hessianThreshold", hess_thresh); @@ -349,7 +349,7 @@ void SurfFeaturesFinder::find(const Mat &image, ImageFeatures &features) { gray_image = image; } - if (surf.empty()) + if (!surf) { detector_->detect(gray_image, features.keypoints); extractor_->compute(gray_image, features.keypoints, features.descriptors); @@ -365,7 +365,7 @@ void SurfFeaturesFinder::find(const Mat &image, ImageFeatures &features) OrbFeaturesFinder::OrbFeaturesFinder(Size _grid_size, int n_features, float scaleFactor, int nlevels) { grid_size = _grid_size; - orb = new ORB(n_features * (99 + grid_size.area())/100/grid_size.area(), scaleFactor, nlevels); + orb = makePtr(n_features * (99 + grid_size.area())/100/grid_size.area(), scaleFactor, nlevels); } void OrbFeaturesFinder::find(const Mat &image, ImageFeatures &features) @@ -534,12 +534,12 @@ BestOf2NearestMatcher::BestOf2NearestMatcher(bool try_use_gpu, float match_conf, #ifdef HAVE_OPENCV_CUDAFEATURES2D if (try_use_gpu && getCudaEnabledDeviceCount() > 0) { - impl_ = new GpuMatcher(match_conf); + impl_ = makePtr(match_conf); } else #endif { - impl_ = new CpuMatcher(match_conf); + impl_ = makePtr(match_conf); } is_thread_safe_ = impl_->isThreadSafe(); diff --git a/modules/stitching/src/stitcher.cpp b/modules/stitching/src/stitcher.cpp index 8658ddb6f3..5683ec3083 100644 --- a/modules/stitching/src/stitcher.cpp +++ b/modules/stitching/src/stitcher.cpp @@ -53,34 +53,34 @@ Stitcher Stitcher::createDefault(bool try_use_gpu) stitcher.setPanoConfidenceThresh(1); stitcher.setWaveCorrection(true); stitcher.setWaveCorrectKind(detail::WAVE_CORRECT_HORIZ); - stitcher.setFeaturesMatcher(new detail::BestOf2NearestMatcher(try_use_gpu)); - stitcher.setBundleAdjuster(new detail::BundleAdjusterRay()); + stitcher.setFeaturesMatcher(makePtr(try_use_gpu)); + stitcher.setBundleAdjuster(makePtr()); #ifdef HAVE_OPENCV_CUDA if (try_use_gpu && cuda::getCudaEnabledDeviceCount() > 0) { #ifdef HAVE_OPENCV_NONFREE - stitcher.setFeaturesFinder(new detail::SurfFeaturesFinderGpu()); + stitcher.setFeaturesFinder(makePtr()); #else - stitcher.setFeaturesFinder(new detail::OrbFeaturesFinder()); + stitcher.setFeaturesFinder(makePtr()); #endif - stitcher.setWarper(new SphericalWarperGpu()); - stitcher.setSeamFinder(new detail::GraphCutSeamFinderGpu()); + stitcher.setWarper(makePtr()); + stitcher.setSeamFinder(makePtr()); } else #endif { #ifdef HAVE_OPENCV_NONFREE - stitcher.setFeaturesFinder(new detail::SurfFeaturesFinder()); + stitcher.setFeaturesFinder(makePtr()); #else - stitcher.setFeaturesFinder(new detail::OrbFeaturesFinder()); + stitcher.setFeaturesFinder(makePtr()); #endif - stitcher.setWarper(new SphericalWarper()); - stitcher.setSeamFinder(new detail::GraphCutSeamFinder(detail::GraphCutSeamFinderBase::COST_COLOR)); + stitcher.setWarper(makePtr()); + stitcher.setSeamFinder(makePtr(detail::GraphCutSeamFinderBase::COST_COLOR)); } - stitcher.setExposureCompensator(new detail::BlocksGainCompensator()); - stitcher.setBlender(new detail::MultiBandBlender(try_use_gpu)); + stitcher.setExposureCompensator(makePtr()); + stitcher.setBlender(makePtr(try_use_gpu)); return stitcher; } diff --git a/modules/stitching/test/test_matchers.cpp b/modules/stitching/test/test_matchers.cpp index ba5c43ae22..c7f068b7fe 100644 --- a/modules/stitching/test/test_matchers.cpp +++ b/modules/stitching/test/test_matchers.cpp @@ -49,7 +49,7 @@ using namespace std; TEST(SurfFeaturesFinder, CanFindInROIs) { - Ptr finder = new detail::SurfFeaturesFinder(); + Ptr finder = makePtr(); Mat img = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/lena.png"); vector rois; diff --git a/modules/superres/perf/perf_superres.cpp b/modules/superres/perf/perf_superres.cpp index 212e415b70..810460bd46 100644 --- a/modules/superres/perf/perf_superres.cpp +++ b/modules/superres/perf/perf_superres.cpp @@ -153,7 +153,7 @@ PERF_TEST_P(Size_MatType, SuperResolution_BTVL1, superRes->set("temporalAreaRadius", temporalAreaRadius); superRes->set("opticalFlow", opticalFlow); - superRes->setInput(new OneFrameSource_CUDA(GpuMat(frame))); + superRes->setInput(makePtr(GpuMat(frame))); GpuMat dst; superRes->nextFrame(dst); @@ -171,7 +171,7 @@ PERF_TEST_P(Size_MatType, SuperResolution_BTVL1, superRes->set("temporalAreaRadius", temporalAreaRadius); superRes->set("opticalFlow", opticalFlow); - superRes->setInput(new OneFrameSource_CPU(frame)); + superRes->setInput(makePtr(frame)); Mat dst; superRes->nextFrame(dst); diff --git a/modules/superres/perf/perf_superres_ocl.cpp b/modules/superres/perf/perf_superres_ocl.cpp index 1d3fee2a15..ce8f5934e0 100644 --- a/modules/superres/perf/perf_superres_ocl.cpp +++ b/modules/superres/perf/perf_superres_ocl.cpp @@ -134,7 +134,7 @@ PERF_TEST_P(Size_MatType, SuperResolution_BTVL1_OCL, superRes_ocl->set("temporalAreaRadius", temporalAreaRadius); superRes_ocl->set("opticalFlow", opticalFlowOcl); - superRes_ocl->setInput(new OneFrameSource_OCL(frame_ocl)); + superRes_ocl->setInput(makePtr(frame_ocl)); ocl::oclMat dst_ocl; superRes_ocl->nextFrame(dst_ocl); diff --git a/modules/superres/src/btv_l1.cpp b/modules/superres/src/btv_l1.cpp index 178e434ade..e0ee7db63a 100644 --- a/modules/superres/src/btv_l1.cpp +++ b/modules/superres/src/btv_l1.cpp @@ -337,7 +337,7 @@ namespace // update blur filter and btv weights - if (filter_.empty() || blurKernelSize_ != curBlurKernelSize_ || blurSigma_ != curBlurSigma_ || src[0].type() != curSrcType_) + if (!filter_ || blurKernelSize_ != curBlurKernelSize_ || blurSigma_ != curBlurSigma_ || src[0].type() != curSrcType_) { filter_ = createGaussianFilter(src[0].type(), Size(blurKernelSize_, blurKernelSize_), blurSigma_); curBlurKernelSize_ = blurKernelSize_; @@ -614,5 +614,5 @@ namespace Ptr cv::superres::createSuperResolution_BTVL1() { - return new BTVL1; + return makePtr(); } diff --git a/modules/superres/src/btv_l1_cuda.cpp b/modules/superres/src/btv_l1_cuda.cpp index 2377cf6bf4..1ec71f220c 100644 --- a/modules/superres/src/btv_l1_cuda.cpp +++ b/modules/superres/src/btv_l1_cuda.cpp @@ -578,7 +578,7 @@ namespace Ptr cv::superres::createSuperResolution_BTVL1_CUDA() { - return new BTVL1_CUDA; + return makePtr(); } #endif // HAVE_CUDA diff --git a/modules/superres/src/btv_l1_ocl.cpp b/modules/superres/src/btv_l1_ocl.cpp index ff60303e44..9d94e61ceb 100644 --- a/modules/superres/src/btv_l1_ocl.cpp +++ b/modules/superres/src/btv_l1_ocl.cpp @@ -743,6 +743,6 @@ namespace Ptr cv::superres::createSuperResolution_BTVL1_OCL() { - return new BTVL1_OCL; + return makePtr(); } #endif diff --git a/modules/superres/src/frame_source.cpp b/modules/superres/src/frame_source.cpp index 9bfa3e066e..14481b852a 100644 --- a/modules/superres/src/frame_source.cpp +++ b/modules/superres/src/frame_source.cpp @@ -74,7 +74,7 @@ namespace Ptr cv::superres::createFrameSource_Empty() { - return new EmptyFrameSource; + return makePtr(); } ////////////////////////////////////////////////////// @@ -186,12 +186,12 @@ namespace Ptr cv::superres::createFrameSource_Video(const String& fileName) { - return new VideoFrameSource(fileName); + return makePtr(fileName); } Ptr cv::superres::createFrameSource_Camera(int deviceId) { - return new CameraFrameSource(deviceId); + return makePtr(deviceId); } #endif // HAVE_OPENCV_HIGHGUI @@ -257,7 +257,7 @@ namespace Ptr cv::superres::createFrameSource_Video_CUDA(const String& fileName) { - return new VideoFrameSource(fileName); + return makePtr(fileName); } #endif // HAVE_OPENCV_CUDACODEC diff --git a/modules/superres/src/optical_flow.cpp b/modules/superres/src/optical_flow.cpp index 2bbb47dc3f..e32c5f044d 100644 --- a/modules/superres/src/optical_flow.cpp +++ b/modules/superres/src/optical_flow.cpp @@ -169,7 +169,7 @@ namespace Ptr cv::superres::createOptFlow_Farneback() { - return new Farneback; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -258,7 +258,7 @@ namespace Ptr cv::superres::createOptFlow_Simple() { - return new Simple; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -337,7 +337,7 @@ namespace Ptr cv::superres::createOptFlow_DualTVL1() { - return new DualTVL1; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -503,7 +503,7 @@ namespace Ptr cv::superres::createOptFlow_Brox_CUDA() { - return new Brox_CUDA; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -562,7 +562,7 @@ namespace Ptr cv::superres::createOptFlow_PyrLK_CUDA() { - return new PyrLK_CUDA; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -636,7 +636,7 @@ namespace Ptr cv::superres::createOptFlow_Farneback_CUDA() { - return new Farneback_CUDA; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -714,7 +714,7 @@ namespace Ptr cv::superres::createOptFlow_DualTVL1_CUDA() { - return new DualTVL1_CUDA; + return makePtr(); } #endif // HAVE_OPENCV_CUDAOPTFLOW @@ -827,7 +827,7 @@ namespace Ptr cv::superres::createOptFlow_PyrLK_OCL() { - return new PyrLK_OCL; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -906,7 +906,7 @@ namespace Ptr cv::superres::createOptFlow_DualTVL1_OCL() { - return new DualTVL1_OCL; + return makePtr(); } /////////////////////////////////////////////////////////////////// @@ -980,7 +980,7 @@ namespace Ptr cv::superres::createOptFlow_Farneback_OCL() { - return new FarneBack_OCL; + return makePtr(); } #endif diff --git a/modules/superres/test/test_superres.cpp b/modules/superres/test/test_superres.cpp index 693713ff14..6777a526f7 100644 --- a/modules/superres/test/test_superres.cpp +++ b/modules/superres/test/test_superres.cpp @@ -59,7 +59,7 @@ private: AllignedFrameSource::AllignedFrameSource(const cv::Ptr& base, int scale) : base_(base), scale_(scale) { - CV_Assert( !base_.empty() ); + CV_Assert( base_ ); } void AllignedFrameSource::nextFrame(cv::OutputArray frame) @@ -101,7 +101,7 @@ private: DegradeFrameSource::DegradeFrameSource(const cv::Ptr& base, int scale) : base_(base), iscale_(1.0 / scale) { - CV_Assert( !base_.empty() ); + CV_Assert( base_ ); } void addGaussNoise(cv::Mat& image, double sigma) @@ -229,7 +229,8 @@ void SuperResolution::RunTest(cv::Ptr superRes) superRes->set("temporalAreaRadius", temporalAreaRadius); cv::Ptr goldSource(new AllignedFrameSource(cv::superres::createFrameSource_Video(inputVideoName), scale)); - cv::Ptr lowResSource(new DegradeFrameSource(new AllignedFrameSource(cv::superres::createFrameSource_Video(inputVideoName), scale), scale)); + cv::Ptr lowResSource(new DegradeFrameSource( + cv::makePtr(cv::superres::createFrameSource_Video(inputVideoName), scale), scale)); // skip first frame cv::Mat frame; diff --git a/modules/video/src/bgfg_gaussmix.cpp b/modules/video/src/bgfg_gaussmix.cpp index a1a224d973..b5ad039e27 100644 --- a/modules/video/src/bgfg_gaussmix.cpp +++ b/modules/video/src/bgfg_gaussmix.cpp @@ -464,7 +464,7 @@ void BackgroundSubtractorMOGImpl::apply(InputArray _image, OutputArray _fgmask, Ptr createBackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma) { - return new BackgroundSubtractorMOGImpl(history, nmixtures, backgroundRatio, noiseSigma); + return makePtr(history, nmixtures, backgroundRatio, noiseSigma); } } diff --git a/modules/video/src/bgfg_gaussmix2.cpp b/modules/video/src/bgfg_gaussmix2.cpp index 2c99c01b05..485e34d26d 100644 --- a/modules/video/src/bgfg_gaussmix2.cpp +++ b/modules/video/src/bgfg_gaussmix2.cpp @@ -769,7 +769,7 @@ void BackgroundSubtractorMOG2Impl::getBackgroundImage(OutputArray backgroundImag Ptr createBackgroundSubtractorMOG2(int _history, double _varThreshold, bool _bShadowDetection) { - return new BackgroundSubtractorMOG2Impl(_history, (float)_varThreshold, _bShadowDetection); + return makePtr(_history, (float)_varThreshold, _bShadowDetection); } } diff --git a/modules/video/src/bgfg_gmg.cpp b/modules/video/src/bgfg_gmg.cpp index e3e4232111..f5b7881a0a 100644 --- a/modules/video/src/bgfg_gmg.cpp +++ b/modules/video/src/bgfg_gmg.cpp @@ -485,7 +485,7 @@ void BackgroundSubtractorGMGImpl::release() Ptr createBackgroundSubtractorGMG(int initializationFrames, double decisionThreshold) { - Ptr bgfg = new BackgroundSubtractorGMGImpl; + Ptr bgfg = makePtr(); bgfg->setNumFrames(initializationFrames); bgfg->setDecisionThreshold(decisionThreshold); diff --git a/modules/video/src/tvl1flow.cpp b/modules/video/src/tvl1flow.cpp index cdf42f91ef..8d59932750 100644 --- a/modules/video/src/tvl1flow.cpp +++ b/modules/video/src/tvl1flow.cpp @@ -953,5 +953,5 @@ CV_INIT_ALGORITHM(OpticalFlowDual_TVL1, "DenseOpticalFlow.DualTVL1", Ptr cv::createOptFlow_DualTVL1() { - return new OpticalFlowDual_TVL1; + return makePtr(); } diff --git a/modules/video/test/test_backgroundsubtractor_gbh.cpp b/modules/video/test/test_backgroundsubtractor_gbh.cpp index a7261516ab..99d53e3d32 100644 --- a/modules/video/test/test_backgroundsubtractor_gbh.cpp +++ b/modules/video/test/test_backgroundsubtractor_gbh.cpp @@ -40,7 +40,7 @@ void CV_BackgroundSubtractorTest::run(int) Ptr fgbg = createBackgroundSubtractorGMG(); Mat fgmask; - if (fgbg.empty()) + if (!fgbg) CV_Error(Error::StsError,"Failed to create Algorithm\n"); /** diff --git a/modules/videostab/src/frame_source.cpp b/modules/videostab/src/frame_source.cpp index 0032202115..7ca4b73de7 100644 --- a/modules/videostab/src/frame_source.cpp +++ b/modules/videostab/src/frame_source.cpp @@ -111,10 +111,10 @@ VideoFileSource::VideoFileSource(const String &path, bool volatileFrame) void VideoFileSource::reset() { impl->reset(); } Mat VideoFileSource::nextFrame() { return impl->nextFrame(); } -int VideoFileSource::width() { return ((VideoFileSourceImpl*)impl.obj)->width(); } -int VideoFileSource::height() { return ((VideoFileSourceImpl*)impl.obj)->height(); } -int VideoFileSource::count() { return ((VideoFileSourceImpl*)impl.obj)->count(); } -double VideoFileSource::fps() { return ((VideoFileSourceImpl*)impl.obj)->fps(); } +int VideoFileSource::width() { return ((VideoFileSourceImpl*)impl.get())->width(); } +int VideoFileSource::height() { return ((VideoFileSourceImpl*)impl.get())->height(); } +int VideoFileSource::count() { return ((VideoFileSourceImpl*)impl.get())->count(); } +double VideoFileSource::fps() { return ((VideoFileSourceImpl*)impl.get())->fps(); } } // namespace videostab } // namespace cv diff --git a/modules/videostab/src/global_motion.cpp b/modules/videostab/src/global_motion.cpp index 702d826e94..1fa449e855 100644 --- a/modules/videostab/src/global_motion.cpp +++ b/modules/videostab/src/global_motion.cpp @@ -671,9 +671,9 @@ Mat ToFileMotionWriter::estimate(const Mat &frame0, const Mat &frame1, bool *ok) KeypointBasedMotionEstimator::KeypointBasedMotionEstimator(Ptr estimator) : ImageMotionEstimatorBase(estimator->motionModel()), motionEstimator_(estimator) { - setDetector(new GoodFeaturesToTrackDetector()); - setOpticalFlowEstimator(new SparsePyrLkOptFlowEstimator()); - setOutlierRejector(new NullOutlierRejector()); + setDetector(makePtr()); + setOpticalFlowEstimator(makePtr()); + setOutlierRejector(makePtr()); } @@ -708,7 +708,7 @@ Mat KeypointBasedMotionEstimator::estimate(const Mat &frame0, const Mat &frame1, // perform outlier rejection - IOutlierRejector *outlRejector = static_cast(outlierRejector_); + IOutlierRejector *outlRejector = outlierRejector_.get(); if (!dynamic_cast(outlRejector)) { pointsPrev_.swap(pointsPrevGood_); @@ -745,7 +745,7 @@ KeypointBasedMotionEstimatorGpu::KeypointBasedMotionEstimatorGpu(Ptr 0); - setOutlierRejector(new NullOutlierRejector()); + setOutlierRejector(makePtr()); } @@ -784,7 +784,7 @@ Mat KeypointBasedMotionEstimatorGpu::estimate(const cuda::GpuMat &frame0, const // perform outlier rejection - IOutlierRejector *rejector = static_cast(outlierRejector_); + IOutlierRejector *rejector = outlierRejector_.get(); if (!dynamic_cast(rejector)) { outlierRejector_->process(frame0.size(), hostPointsPrev_, hostPoints_, rejectionStatus_); diff --git a/modules/videostab/src/inpainting.cpp b/modules/videostab/src/inpainting.cpp index 8ae71883c6..991112712d 100644 --- a/modules/videostab/src/inpainting.cpp +++ b/modules/videostab/src/inpainting.cpp @@ -324,7 +324,7 @@ public: MotionInpainter::MotionInpainter() { #ifdef HAVE_OPENCV_CUDAOPTFLOW - setOptFlowEstimator(new DensePyrLkOptFlowEstimatorGpu()); + setOptFlowEstimator(makePtr()); #else CV_Error(Error::StsNotImplemented, "Current implementation of MotionInpainter requires CUDA"); #endif diff --git a/modules/videostab/src/motion_stabilizing.cpp b/modules/videostab/src/motion_stabilizing.cpp index c1f3442e78..65bbd73bd1 100644 --- a/modules/videostab/src/motion_stabilizing.cpp +++ b/modules/videostab/src/motion_stabilizing.cpp @@ -532,9 +532,9 @@ void LpMotionStabilizer::stabilize( model.scaling(1); ClpPresolve presolveInfo; - Ptr presolvedModel = presolveInfo.presolvedModel(model); + Ptr presolvedModel(presolveInfo.presolvedModel(model)); - if (!presolvedModel.empty()) + if (presolvedModel) { presolvedModel->dual(); presolveInfo.postsolve(true); diff --git a/modules/videostab/src/stabilizer.cpp b/modules/videostab/src/stabilizer.cpp index 50ac05c6f7..f9c09ba36c 100644 --- a/modules/videostab/src/stabilizer.cpp +++ b/modules/videostab/src/stabilizer.cpp @@ -54,11 +54,11 @@ namespace videostab StabilizerBase::StabilizerBase() { - setLog(new LogToStdout()); - setFrameSource(new NullFrameSource()); - setMotionEstimator(new KeypointBasedMotionEstimator(new MotionEstimatorRansacL2())); - setDeblurer(new NullDeblurer()); - setInpainter(new NullInpainter()); + setLog(makePtr()); + setFrameSource(makePtr()); + setMotionEstimator(makePtr(makePtr())); + setDeblurer(makePtr()); + setInpainter(makePtr()); setRadius(15); setTrimRatio(0); setCorrectionForInclusion(false); @@ -156,7 +156,7 @@ bool StabilizerBase::doOneIteration() void StabilizerBase::setUp(const Mat &firstFrame) { - InpainterBase *inpaint = static_cast(inpainter_); + InpainterBase *inpaint = inpainter_.get(); doInpainting_ = dynamic_cast(inpaint) == 0; if (doInpainting_) { @@ -167,7 +167,7 @@ void StabilizerBase::setUp(const Mat &firstFrame) inpainter_->setStabilizationMotions(stabilizationMotions_); } - DeblurerBase *deblurer = static_cast(deblurer_); + DeblurerBase *deblurer = deblurer_.get(); doDeblurring_ = dynamic_cast(deblurer) == 0; if (doDeblurring_) { @@ -252,7 +252,7 @@ void StabilizerBase::logProcessingTime() OnePassStabilizer::OnePassStabilizer() { - setMotionFilter(new GaussianMotionFilter()); + setMotionFilter(makePtr()); reset(); } @@ -308,8 +308,8 @@ Mat OnePassStabilizer::postProcessFrame(const Mat &frame) TwoPassStabilizer::TwoPassStabilizer() { - setMotionStabilizer(new GaussianMotionFilter()); - setWobbleSuppressor(new NullWobbleSuppressor()); + setMotionStabilizer(makePtr()); + setWobbleSuppressor(makePtr()); setEstimateTrimRatio(false); reset(); } @@ -371,7 +371,7 @@ void TwoPassStabilizer::runPrePassIfNecessary() { // check if we must do wobble suppression - WobbleSuppressorBase *wobble = static_cast(wobbleSuppressor_); + WobbleSuppressorBase *wobble = wobbleSuppressor_.get(); doWobbleSuppression_ = dynamic_cast(wobble) == 0; // estimate motions @@ -469,7 +469,7 @@ void TwoPassStabilizer::setUp(const Mat &firstFrame) for (int i = -radius_; i <= 0; ++i) at(i, frames_) = firstFrame; - WobbleSuppressorBase *wobble = static_cast(wobbleSuppressor_); + WobbleSuppressorBase *wobble = wobbleSuppressor_.get(); doWobbleSuppression_ = dynamic_cast(wobble) == 0; if (doWobbleSuppression_) { diff --git a/modules/videostab/src/wobble_suppression.cpp b/modules/videostab/src/wobble_suppression.cpp index bdddc95350..e2635d5e08 100644 --- a/modules/videostab/src/wobble_suppression.cpp +++ b/modules/videostab/src/wobble_suppression.cpp @@ -60,7 +60,7 @@ namespace videostab WobbleSuppressorBase::WobbleSuppressorBase() : motions_(0), stabilizationMotions_(0) { - setMotionEstimator(new KeypointBasedMotionEstimator(new MotionEstimatorRansacL2(MM_HOMOGRAPHY))); + setMotionEstimator(makePtr(makePtr(MM_HOMOGRAPHY))); } diff --git a/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp b/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp index e0e53e3701..33a8334c6a 100644 --- a/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp +++ b/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp @@ -26,7 +26,7 @@ public: Detector(detector) { LOGD("CascadeDetectorAdapter::Detect::Detect"); - CV_Assert(!detector.empty()); + CV_Assert(detector); } void detect(const cv::Mat &Image, std::vector &objects) @@ -57,11 +57,11 @@ struct DetectorAgregator mainDetector(_mainDetector), trackingDetector(_trackingDetector) { - CV_Assert(!_mainDetector.empty()); - CV_Assert(!_trackingDetector.empty()); + CV_Assert(_mainDetector); + CV_Assert(_trackingDetector); DetectionBasedTracker::Parameters DetectorParams; - tracker = new DetectionBasedTracker(mainDetector.ptr(), trackingDetector.ptr(), DetectorParams); + tracker = makePtr(mainDetector, trackingDetector, DetectorParams); } }; @@ -77,8 +77,10 @@ JNIEXPORT jlong JNICALL Java_org_opencv_samples_facedetect_DetectionBasedTracker try { - cv::Ptr mainDetector = new CascadeDetectorAdapter(new CascadeClassifier(stdFileName)); - cv::Ptr trackingDetector = new CascadeDetectorAdapter(new CascadeClassifier(stdFileName)); + cv::Ptr mainDetector = makePtr( + makePtr(stdFileName)); + cv::Ptr trackingDetector = makePtr( + makePtr(stdFileName)); result = (jlong)new DetectorAgregator(mainDetector, trackingDetector); if (faceSize > 0) { diff --git a/samples/cpp/bagofwords_classification.cpp b/samples/cpp/bagofwords_classification.cpp index e24a770f8e..4506e5b9de 100644 --- a/samples/cpp/bagofwords_classification.cpp +++ b/samples/cpp/bagofwords_classification.cpp @@ -2563,19 +2563,19 @@ int main(int argc, char** argv) Ptr featureDetector = FeatureDetector::create( ddmParams.detectorType ); Ptr descExtractor = DescriptorExtractor::create( ddmParams.descriptorType ); Ptr bowExtractor; - if( featureDetector.empty() || descExtractor.empty() ) + if( !featureDetector || !descExtractor ) { cout << "featureDetector or descExtractor was not created" << endl; return -1; } { Ptr descMatcher = DescriptorMatcher::create( ddmParams.matcherType ); - if( featureDetector.empty() || descExtractor.empty() || descMatcher.empty() ) + if( !featureDetector || !descExtractor || !descMatcher ) { cout << "descMatcher was not created" << endl; return -1; } - bowExtractor = new BOWImgDescriptorExtractor( descExtractor, descMatcher ); + bowExtractor = makePtr( descExtractor, descMatcher ); } // Print configuration to screen diff --git a/samples/cpp/bgfg_gmg.cpp b/samples/cpp/bgfg_gmg.cpp index ea1df98d08..226eea4635 100644 --- a/samples/cpp/bgfg_gmg.cpp +++ b/samples/cpp/bgfg_gmg.cpp @@ -35,7 +35,7 @@ int main(int argc, char** argv) setNumThreads(8); Ptr fgbg = createBackgroundSubtractorGMG(20, 0.7); - if (fgbg.empty()) + if (!fgbg) { std::cerr << "Failed to create BackgroundSubtractor.GMG Algorithm." << std::endl; return -1; diff --git a/samples/cpp/dbt_face_detection.cpp b/samples/cpp/dbt_face_detection.cpp index c2e6d0a815..651eaff73f 100644 --- a/samples/cpp/dbt_face_detection.cpp +++ b/samples/cpp/dbt_face_detection.cpp @@ -22,7 +22,7 @@ class CascadeDetectorAdapter: public DetectionBasedTracker::IDetector IDetector(), Detector(detector) { - CV_Assert(!detector.empty()); + CV_Assert(detector); } void detect(const cv::Mat &Image, std::vector &objects) @@ -51,11 +51,11 @@ int main(int , char** ) } std::string cascadeFrontalfilename = "../../data/lbpcascades/lbpcascade_frontalface.xml"; - cv::Ptr cascade = new cv::CascadeClassifier(cascadeFrontalfilename); - cv::Ptr MainDetector = new CascadeDetectorAdapter(cascade); + cv::Ptr cascade = makePtr(cascadeFrontalfilename); + cv::Ptr MainDetector = makePtr(cascade); - cascade = new cv::CascadeClassifier(cascadeFrontalfilename); - cv::Ptr TrackingDetector = new CascadeDetectorAdapter(cascade); + cascade = makePtr(cascadeFrontalfilename); + cv::Ptr TrackingDetector = makePtr(cascade); DetectionBasedTracker::Parameters params; DetectionBasedTracker Detector(MainDetector, TrackingDetector, params); diff --git a/samples/cpp/descriptor_extractor_matcher.cpp b/samples/cpp/descriptor_extractor_matcher.cpp index 43baed2fe5..7df3cd02b0 100644 --- a/samples/cpp/descriptor_extractor_matcher.cpp +++ b/samples/cpp/descriptor_extractor_matcher.cpp @@ -153,7 +153,7 @@ static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective, { cout << "< Evaluate descriptor matcher..." << endl; vector curve; - Ptr gdm = new VectorDescriptorMatcher( descriptorExtractor, descriptorMatcher ); + Ptr gdm = makePtr( descriptorExtractor, descriptorMatcher ); evaluateGenericDescriptorMatcher( img1, img2, H12, keypoints1, keypoints2, 0, 0, curve, gdm ); Point2f firstPoint = *curve.begin(); @@ -253,7 +253,7 @@ int main(int argc, char** argv) int mactherFilterType = getMatcherFilterType( argv[4] ); bool eval = !isWarpPerspective ? false : (atoi(argv[6]) == 0 ? false : true); cout << ">" << endl; - if( detector.empty() || descriptorExtractor.empty() || descriptorMatcher.empty() ) + if( !detector || !descriptorExtractor || !descriptorMatcher ) { cout << "Can not create detector or descriptor exstractor or descriptor matcher of given types" << endl; return -1; diff --git a/samples/cpp/detection_based_tracker_sample.cpp b/samples/cpp/detection_based_tracker_sample.cpp index 1debff7e3f..81afa789c3 100644 --- a/samples/cpp/detection_based_tracker_sample.cpp +++ b/samples/cpp/detection_based_tracker_sample.cpp @@ -67,7 +67,7 @@ class CascadeDetectorAdapter: public DetectionBasedTracker::IDetector CascadeDetectorAdapter(cv::Ptr detector): Detector(detector) { - CV_Assert(!detector.empty()); + CV_Assert(detector); } void detect(const cv::Mat &Image, std::vector &objects) @@ -117,11 +117,11 @@ static int test_FaceDetector(int argc, char *argv[]) } std::string cascadeFrontalfilename=cascadefile; - cv::Ptr cascade = new cv::CascadeClassifier(cascadeFrontalfilename); - cv::Ptr MainDetector = new CascadeDetectorAdapter(cascade); + cv::Ptr cascade = makePtr(cascadeFrontalfilename); + cv::Ptr MainDetector = makePtr(cascade); - cascade = new cv::CascadeClassifier(cascadeFrontalfilename); - cv::Ptr TrackingDetector = new CascadeDetectorAdapter(cascade); + cascade = makePtr(cascadeFrontalfilename); + cv::Ptr TrackingDetector = makePtr(cascade); DetectionBasedTracker::Parameters params; DetectionBasedTracker fd(MainDetector, TrackingDetector, params); diff --git a/samples/cpp/detector_descriptor_evaluation.cpp b/samples/cpp/detector_descriptor_evaluation.cpp index ece735a506..dd3cd800e5 100644 --- a/samples/cpp/detector_descriptor_evaluation.cpp +++ b/samples/cpp/detector_descriptor_evaluation.cpp @@ -535,7 +535,7 @@ void DetectorQualityEvaluator::readAlgorithm () { defaultDetector = FeatureDetector::create( algName ); specificDetector = FeatureDetector::create( algName ); - if( defaultDetector.empty() ) + if( !defaultDetector ) { printf( "Algorithm can not be read\n" ); exit(-1); @@ -769,14 +769,14 @@ void DescriptorQualityEvaluator::readAlgorithm( ) defaultDescMatcher = GenericDescriptorMatcher::create( algName ); specificDescMatcher = GenericDescriptorMatcher::create( algName ); - if( defaultDescMatcher.empty() ) + if( !defaultDescMatcher ) { Ptr extractor = DescriptorExtractor::create( algName ); Ptr matcher = DescriptorMatcher::create( matcherName ); - defaultDescMatcher = new VectorDescriptorMatch( extractor, matcher ); - specificDescMatcher = new VectorDescriptorMatch( extractor, matcher ); + defaultDescMatcher = makePtr( extractor, matcher ); + specificDescMatcher = makePtr( extractor, matcher ); - if( extractor.empty() || matcher.empty() ) + if( !extractor || !matcher ) { printf("Algorithm can not be read\n"); exit(-1); @@ -881,8 +881,9 @@ public: virtual void readAlgorithm( ) { string classifierFile = data_path + "/features2d/calonder_classifier.rtc"; - defaultDescMatcher = new VectorDescriptorMatch( new CalonderDescriptorExtractor( classifierFile ), - new BFMatcher(NORM_L2) ); + defaultDescMatcher = makePtr( + makePtr >( classifierFile ), + makePtr(int(NORM_L2))); specificDescMatcher = defaultDescMatcher; } }; @@ -922,10 +923,11 @@ void OneWayDescriptorQualityTest::processRunParamsFile () readAllDatasetsRunParams(); - OneWayDescriptorBase *base = new OneWayDescriptorBase(patchSize, poseCount, pcaFilename, - trainPath, trainImagesList); + Ptr base( + new OneWayDescriptorBase(patchSize, poseCount, pcaFilename, + trainPath, trainImagesList)); - OneWayDescriptorMatch *match = new OneWayDescriptorMatch (); + Ptr match = makePtr(); match->initialize( OneWayDescriptorMatch::Params (), base ); defaultDescMatcher = match; writeAllDatasetsRunParams(); @@ -958,18 +960,18 @@ int main( int argc, char** argv ) Ptr evals[] = { - new DetectorQualityEvaluator( "FAST", "quality-detector-fast" ), - new DetectorQualityEvaluator( "GFTT", "quality-detector-gftt" ), - new DetectorQualityEvaluator( "HARRIS", "quality-detector-harris" ), - new DetectorQualityEvaluator( "MSER", "quality-detector-mser" ), - new DetectorQualityEvaluator( "STAR", "quality-detector-star" ), - new DetectorQualityEvaluator( "SIFT", "quality-detector-sift" ), - new DetectorQualityEvaluator( "SURF", "quality-detector-surf" ), + makePtr( "FAST", "quality-detector-fast" ), + makePtr( "GFTT", "quality-detector-gftt" ), + makePtr( "HARRIS", "quality-detector-harris" ), + makePtr( "MSER", "quality-detector-mser" ), + makePtr( "STAR", "quality-detector-star" ), + makePtr( "SIFT", "quality-detector-sift" ), + makePtr( "SURF", "quality-detector-surf" ), - new DescriptorQualityEvaluator( "SIFT", "quality-descriptor-sift", "BruteForce" ), - new DescriptorQualityEvaluator( "SURF", "quality-descriptor-surf", "BruteForce" ), - new DescriptorQualityEvaluator( "FERN", "quality-descriptor-fern"), - new CalonderDescriptorQualityEvaluator() + makePtr( "SIFT", "quality-descriptor-sift", "BruteForce" ), + makePtr( "SURF", "quality-descriptor-surf", "BruteForce" ), + makePtr( "FERN", "quality-descriptor-fern"), + makePtr() }; for( size_t i = 0; i < sizeof(evals)/sizeof(evals[0]); i++ ) diff --git a/samples/cpp/fabmap_sample.cpp b/samples/cpp/fabmap_sample.cpp index 75febb1340..cd06b55cb8 100644 --- a/samples/cpp/fabmap_sample.cpp +++ b/samples/cpp/fabmap_sample.cpp @@ -131,11 +131,11 @@ int main(int argc, char * argv[]) { //generate test data cout << "Extracting Test Data from images" << endl << endl; - Ptr detector = + Ptr detector( new DynamicAdaptedFeatureDetector( - AdjusterAdapter::create("STAR"), 130, 150, 5); - Ptr extractor = - new SurfDescriptorExtractor(1000, 4, 2, false, true); + AdjusterAdapter::create("STAR"), 130, 150, 5)); + Ptr extractor( + new SurfDescriptorExtractor(1000, 4, 2, false, true)); Ptr matcher = DescriptorMatcher::create("FlannBased"); @@ -183,8 +183,8 @@ int main(int argc, char * argv[]) { endl; Ptr fabmap; - fabmap = new of2::FabMap2(tree, 0.39, 0, of2::FabMap::SAMPLED | - of2::FabMap::CHOW_LIU); + fabmap.reset(new of2::FabMap2(tree, 0.39, 0, of2::FabMap::SAMPLED | + of2::FabMap::CHOW_LIU)); fabmap->addTraining(trainData); vector matches; diff --git a/samples/cpp/generic_descriptor_match.cpp b/samples/cpp/generic_descriptor_match.cpp index 888c24f7ec..359f3c08e1 100644 --- a/samples/cpp/generic_descriptor_match.cpp +++ b/samples/cpp/generic_descriptor_match.cpp @@ -33,7 +33,7 @@ int main(int argc, char** argv) std::string params_filename = std::string(argv[4]); Ptr descriptorMatcher = GenericDescriptorMatcher::create(alg_name, params_filename); - if( descriptorMatcher.empty() ) + if( !descriptorMatcher ) { printf ("Cannot create descriptor\n"); return 0; diff --git a/samples/cpp/image.cpp b/samples/cpp/image.cpp index 806926b042..80f80c7aff 100644 --- a/samples/cpp/image.cpp +++ b/samples/cpp/image.cpp @@ -31,8 +31,8 @@ int main( int argc, char** argv ) help(); const char* imagename = argc > 1 ? argv[1] : "lena.jpg"; #if DEMO_MIXED_API_USE - Ptr iplimg = cvLoadImage(imagename); // Ptr is safe ref-conting pointer class - if(iplimg.empty()) + Ptr iplimg(cvLoadImage(imagename)); // Ptr is safe ref-counting pointer class + if(!iplimg) { fprintf(stderr, "Can not load image %s\n", imagename); return -1; diff --git a/samples/cpp/linemod.cpp b/samples/cpp/linemod.cpp index 08d2a00354..4d11da36b5 100644 --- a/samples/cpp/linemod.cpp +++ b/samples/cpp/linemod.cpp @@ -114,7 +114,7 @@ private: // Functions to store detector and templates in single XML/YAML file static cv::Ptr readLinemod(const std::string& filename) { - cv::Ptr detector = new cv::linemod::Detector; + cv::Ptr detector = cv::makePtr(); cv::FileStorage fs(filename, cv::FileStorage::READ); detector->read(fs.root()); diff --git a/samples/cpp/matching_to_many_images.cpp b/samples/cpp/matching_to_many_images.cpp index 7a346e3f49..152b400645 100644 --- a/samples/cpp/matching_to_many_images.cpp +++ b/samples/cpp/matching_to_many_images.cpp @@ -84,7 +84,7 @@ static bool createDetectorDescriptorMatcher( const string& detectorType, const s descriptorMatcher = DescriptorMatcher::create( matcherType ); cout << ">" << endl; - bool isCreated = !( featureDetector.empty() || descriptorExtractor.empty() || descriptorMatcher.empty() ); + bool isCreated = featureDetector && descriptorExtractor && descriptorMatcher; if( !isCreated ) cout << "Can not create feature detector or descriptor extractor or descriptor matcher of given types." << endl << ">" << endl; diff --git a/samples/cpp/stitching_detailed.cpp b/samples/cpp/stitching_detailed.cpp index c1172b130d..b6eefc6f99 100644 --- a/samples/cpp/stitching_detailed.cpp +++ b/samples/cpp/stitching_detailed.cpp @@ -358,14 +358,14 @@ int main(int argc, char* argv[]) { #ifdef HAVE_OPENCV_NONFREE if (try_gpu && cuda::getCudaEnabledDeviceCount() > 0) - finder = new SurfFeaturesFinderGpu(); + finder = makePtr(); else #endif - finder = new SurfFeaturesFinder(); + finder = makePtr(); } else if (features_type == "orb") { - finder = new OrbFeaturesFinder(); + finder = makePtr(); } else { @@ -484,8 +484,8 @@ int main(int argc, char* argv[]) } Ptr adjuster; - if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj(); - else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay(); + if (ba_cost_func == "reproj") adjuster = makePtr(); + else if (ba_cost_func == "ray") adjuster = makePtr(); else { cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n"; @@ -555,31 +555,49 @@ int main(int argc, char* argv[]) #ifdef HAVE_OPENCV_CUDAWARPING if (try_gpu && cuda::getCudaEnabledDeviceCount() > 0) { - if (warp_type == "plane") warper_creator = new cv::PlaneWarperGpu(); - else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarperGpu(); - else if (warp_type == "spherical") warper_creator = new cv::SphericalWarperGpu(); + if (warp_type == "plane") + warper_creator = makePtr(); + else if (warp_type == "cylindrical") + warper_creator = makePtr(); + else if (warp_type == "spherical") + warper_creator = makePtr(); } else #endif { - if (warp_type == "plane") warper_creator = new cv::PlaneWarper(); - else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper(); - else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper(); - else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper(); - else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper(); - else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1); - else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1); - else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1); - else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1); - else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1); - else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1); - else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1); - else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1); - else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper(); - else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper(); + if (warp_type == "plane") + warper_creator = makePtr(); + else if (warp_type == "cylindrical") + warper_creator = makePtr(); + else if (warp_type == "spherical") + warper_creator = makePtr(); + else if (warp_type == "fisheye") + warper_creator = makePtr(); + else if (warp_type == "stereographic") + warper_creator = makePtr(); + else if (warp_type == "compressedPlaneA2B1") + warper_creator = makePtr(2.0f, 1.0f); + else if (warp_type == "compressedPlaneA1.5B1") + warper_creator = makePtr(1.5f, 1.0f); + else if (warp_type == "compressedPlanePortraitA2B1") + warper_creator = makePtr(2.0f, 1.0f); + else if (warp_type == "compressedPlanePortraitA1.5B1") + warper_creator = makePtr(1.5f, 1.0f); + else if (warp_type == "paniniA2B1") + warper_creator = makePtr(2.0f, 1.0f); + else if (warp_type == "paniniA1.5B1") + warper_creator = makePtr(1.5f, 1.0f); + else if (warp_type == "paniniPortraitA2B1") + warper_creator = makePtr(2.0f, 1.0f); + else if (warp_type == "paniniPortraitA1.5B1") + warper_creator = makePtr(1.5f, 1.0f); + else if (warp_type == "mercator") + warper_creator = makePtr(); + else if (warp_type == "transverseMercator") + warper_creator = makePtr(); } - if (warper_creator.empty()) + if (!warper_creator) { cout << "Can't create the following warper '" << warp_type << "'\n"; return 1; @@ -612,32 +630,32 @@ int main(int argc, char* argv[]) Ptr seam_finder; if (seam_find_type == "no") - seam_finder = new detail::NoSeamFinder(); + seam_finder = makePtr(); else if (seam_find_type == "voronoi") - seam_finder = new detail::VoronoiSeamFinder(); + seam_finder = makePtr(); else if (seam_find_type == "gc_color") { #ifdef HAVE_OPENCV_CUDA if (try_gpu && cuda::getCudaEnabledDeviceCount() > 0) - seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR); + seam_finder = makePtr(GraphCutSeamFinderBase::COST_COLOR); else #endif - seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR); + seam_finder = makePtr(GraphCutSeamFinderBase::COST_COLOR); } else if (seam_find_type == "gc_colorgrad") { #ifdef HAVE_OPENCV_CUDA if (try_gpu && cuda::getCudaEnabledDeviceCount() > 0) - seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR_GRAD); + seam_finder = makePtr(GraphCutSeamFinderBase::COST_COLOR_GRAD); else #endif - seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR_GRAD); + seam_finder = makePtr(GraphCutSeamFinderBase::COST_COLOR_GRAD); } else if (seam_find_type == "dp_color") - seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR); + seam_finder = makePtr(DpSeamFinder::COLOR); else if (seam_find_type == "dp_colorgrad") - seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR_GRAD); - if (seam_finder.empty()) + seam_finder = makePtr(DpSeamFinder::COLOR_GRAD); + if (!seam_finder) { cout << "Can't create the following seam finder '" << seam_find_type << "'\n"; return 1; @@ -735,7 +753,7 @@ int main(int argc, char* argv[]) resize(dilated_mask, seam_mask, mask_warped.size()); mask_warped = seam_mask & mask_warped; - if (blender.empty()) + if (!blender) { blender = Blender::createDefault(blend_type, try_gpu); Size dst_sz = resultRoi(corners, sizes).size(); @@ -744,13 +762,13 @@ int main(int argc, char* argv[]) blender = Blender::createDefault(Blender::NO, try_gpu); else if (blend_type == Blender::MULTI_BAND) { - MultiBandBlender* mb = dynamic_cast(static_cast(blender)); + MultiBandBlender* mb = dynamic_cast(blender.get()); mb->setNumBands(static_cast(ceil(log(blend_width)/log(2.)) - 1.)); LOGLN("Multi-band blender, number of bands: " << mb->numBands()); } else if (blend_type == Blender::FEATHER) { - FeatherBlender* fb = dynamic_cast(static_cast(blender)); + FeatherBlender* fb = dynamic_cast(blender.get()); fb->setSharpness(1.f/blend_width); LOGLN("Feather blender, sharpness: " << fb->sharpness()); } diff --git a/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp b/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp index 6c681d643a..e13f2b6960 100644 --- a/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp +++ b/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp @@ -32,8 +32,8 @@ int main( int argc, char** argv ) const char* imagename = argc > 1 ? argv[1] : "lena.jpg"; #ifdef DEMO_MIXED_API_USE - Ptr IplI = cvLoadImage(imagename); // Ptr is safe ref-counting pointer class - if(IplI.empty()) + Ptr IplI(cvLoadImage(imagename)); // Ptr is a safe ref-counting pointer class + if(!IplI) { cerr << "Can not load image " << imagename << endl; return -1; diff --git a/samples/cpp/video_homography.cpp b/samples/cpp/video_homography.cpp index c8388007dd..bf2559fbaf 100644 --- a/samples/cpp/video_homography.cpp +++ b/samples/cpp/video_homography.cpp @@ -152,7 +152,7 @@ int main(int ac, char ** av) Mat train_desc, query_desc; const int DESIRED_FTRS = 500; - GridAdaptedFeatureDetector detector(new FastFeatureDetector(10, true), DESIRED_FTRS, 4, 4); + GridAdaptedFeatureDetector detector(makePtr(10, true), DESIRED_FTRS, 4, 4); Mat H_prev = Mat::eye(3, 3, CV_32FC1); for (;;) diff --git a/samples/cpp/videostab.cpp b/samples/cpp/videostab.cpp index 668ee59d21..675d483f3d 100644 --- a/samples/cpp/videostab.cpp +++ b/samples/cpp/videostab.cpp @@ -193,7 +193,7 @@ public: virtual Ptr build() { - MotionEstimatorRansacL2 *est = new MotionEstimatorRansacL2(motionModel(arg(prefix + "model"))); + Ptr est = makePtr(motionModel(arg(prefix + "model"))); RansacParams ransac = est->ransacParams(); if (arg(prefix + "subset") != "auto") @@ -205,10 +205,10 @@ public: est->setMinInlierRatio(argf(prefix + "min-inlier-ratio")); - Ptr outlierRejector = new NullOutlierRejector(); + Ptr outlierRejector = makePtr(); if (arg(prefix + "local-outlier-rejection") == "yes") { - TranslationBasedLocalOutlierRejector *tblor = new TranslationBasedLocalOutlierRejector(); + Ptr tblor = makePtr(); RansacParams ransacParams = tblor->ransacParams(); if (arg(prefix + "thresh") != "auto") ransacParams.thresh = argf(prefix + "thresh"); @@ -219,14 +219,14 @@ public: #if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDA) && defined(HAVE_OPENCV_CUDAOPTFLOW) if (gpu) { - KeypointBasedMotionEstimatorGpu *kbest = new KeypointBasedMotionEstimatorGpu(est); + Ptr kbest = makePtr(est); kbest->setOutlierRejector(outlierRejector); return kbest; } #endif - KeypointBasedMotionEstimator *kbest = new KeypointBasedMotionEstimator(est); - kbest->setDetector(new GoodFeaturesToTrackDetector(argi(prefix + "nkps"))); + Ptr kbest = makePtr(est); + kbest->setDetector(makePtr(argi(prefix + "nkps"))); kbest->setOutlierRejector(outlierRejector); return kbest; } @@ -244,12 +244,12 @@ public: virtual Ptr build() { - MotionEstimatorL1 *est = new MotionEstimatorL1(motionModel(arg(prefix + "model"))); + Ptr est = makePtr(motionModel(arg(prefix + "model"))); - Ptr outlierRejector = new NullOutlierRejector(); + Ptr outlierRejector = makePtr(); if (arg(prefix + "local-outlier-rejection") == "yes") { - TranslationBasedLocalOutlierRejector *tblor = new TranslationBasedLocalOutlierRejector(); + Ptr tblor = makePtr(); RansacParams ransacParams = tblor->ransacParams(); if (arg(prefix + "thresh") != "auto") ransacParams.thresh = argf(prefix + "thresh"); @@ -260,14 +260,14 @@ public: #if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDA) && defined(HAVE_OPENCV_CUDAOPTFLOW) if (gpu) { - KeypointBasedMotionEstimatorGpu *kbest = new KeypointBasedMotionEstimatorGpu(est); + Ptr kbest = makePtr(est); kbest->setOutlierRejector(outlierRejector); return kbest; } #endif - KeypointBasedMotionEstimator *kbest = new KeypointBasedMotionEstimator(est); - kbest->setDetector(new GoodFeaturesToTrackDetector(argi(prefix + "nkps"))); + Ptr kbest = makePtr(est); + kbest->setDetector(makePtr(argi(prefix + "nkps"))); kbest->setOutlierRejector(outlierRejector); return kbest; } @@ -363,7 +363,7 @@ int main(int argc, const char **argv) // get source video parameters - VideoFileSource *source = new VideoFileSource(inputPath); + Ptr source = makePtr(inputPath); cout << "frame count (rough): " << source->count() << endl; if (arg("fps") == "auto") outputFps = source->fps(); @@ -374,15 +374,15 @@ int main(int argc, const char **argv) Ptr motionEstBuilder; if (arg("lin-prog-motion-est") == "yes") - motionEstBuilder = new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes"); + motionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes")); else - motionEstBuilder = new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes"); + motionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes")); Ptr wsMotionEstBuilder; if (arg("ws-lp") == "yes") - wsMotionEstBuilder = new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes", "ws-"); + wsMotionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes", "ws-")); else - wsMotionEstBuilder = new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes", "ws-"); + wsMotionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes", "ws-")); // determine whether we must use one pass or two pass stabilizer bool isTwoPass = @@ -400,7 +400,7 @@ int main(int argc, const char **argv) if (arg("lin-prog-stab") == "yes") { - LpMotionStabilizer *stab = new LpMotionStabilizer(); + Ptr stab = makePtr(); stab->setFrameSize(Size(source->width(), source->height())); stab->setTrimRatio(arg("lps-trim-ratio") == "auto" ? argf("trim-ratio") : argf("lps-trim-ratio")); stab->setWeight1(argf("lps-w1")); @@ -410,18 +410,18 @@ int main(int argc, const char **argv) twoPassStabilizer->setMotionStabilizer(stab); } else if (arg("stdev") == "auto") - twoPassStabilizer->setMotionStabilizer(new GaussianMotionFilter(argi("radius"))); + twoPassStabilizer->setMotionStabilizer(makePtr(argi("radius"))); else - twoPassStabilizer->setMotionStabilizer(new GaussianMotionFilter(argi("radius"), argf("stdev"))); + twoPassStabilizer->setMotionStabilizer(makePtr(argi("radius"), argf("stdev"))); // init wobble suppressor if necessary if (arg("wobble-suppress") == "yes") { - MoreAccurateMotionWobbleSuppressorBase *ws = new MoreAccurateMotionWobbleSuppressor(); + Ptr ws = makePtr(); if (arg("gpu") == "yes") #ifdef HAVE_OPENCV_CUDA - ws = new MoreAccurateMotionWobbleSuppressorGpu(); + ws = makePtr(); #else throw runtime_error("OpenCV is built without CUDA support"); #endif @@ -433,12 +433,12 @@ int main(int argc, const char **argv) MotionModel model = ws->motionEstimator()->motionModel(); if (arg("load-motions2") != "no") { - ws->setMotionEstimator(new FromFileMotionReader(arg("load-motions2"))); + ws->setMotionEstimator(makePtr(arg("load-motions2"))); ws->motionEstimator()->setMotionModel(model); } if (arg("save-motions2") != "no") { - ws->setMotionEstimator(new ToFileMotionWriter(arg("save-motions2"), ws->motionEstimator())); + ws->setMotionEstimator(makePtr(arg("save-motions2"), ws->motionEstimator())); ws->motionEstimator()->setMotionModel(model); } } @@ -450,26 +450,26 @@ int main(int argc, const char **argv) OnePassStabilizer *onePassStabilizer = new OnePassStabilizer(); stabilizer = onePassStabilizer; if (arg("stdev") == "auto") - onePassStabilizer->setMotionFilter(new GaussianMotionFilter(argi("radius"))); + onePassStabilizer->setMotionFilter(makePtr(argi("radius"))); else - onePassStabilizer->setMotionFilter(new GaussianMotionFilter(argi("radius"), argf("stdev"))); + onePassStabilizer->setMotionFilter(makePtr(argi("radius"), argf("stdev"))); } stabilizer->setFrameSource(source); stabilizer->setMotionEstimator(motionEstBuilder->build()); // cast stabilizer to simple frame source interface to read stabilized frames - stabilizedFrames = dynamic_cast(stabilizer); + stabilizedFrames.reset(dynamic_cast(stabilizer)); MotionModel model = stabilizer->motionEstimator()->motionModel(); if (arg("load-motions") != "no") { - stabilizer->setMotionEstimator(new FromFileMotionReader(arg("load-motions"))); + stabilizer->setMotionEstimator(makePtr(arg("load-motions"))); stabilizer->motionEstimator()->setMotionModel(model); } if (arg("save-motions") != "no") { - stabilizer->setMotionEstimator(new ToFileMotionWriter(arg("save-motions"), stabilizer->motionEstimator())); + stabilizer->setMotionEstimator(makePtr(arg("save-motions"), stabilizer->motionEstimator())); stabilizer->motionEstimator()->setMotionModel(model); } @@ -478,7 +478,7 @@ int main(int argc, const char **argv) // init deblurer if (arg("deblur") == "yes") { - WeightingDeblurer *deblurer = new WeightingDeblurer(); + Ptr deblurer = makePtr(); deblurer->setRadius(argi("radius")); deblurer->setSensitivity(argf("deblur-sens")); stabilizer->setDeblurer(deblurer); @@ -503,22 +503,22 @@ int main(int argc, const char **argv) Ptr inpainters_(inpainters); if (arg("mosaic") == "yes") { - ConsistentMosaicInpainter *inp = new ConsistentMosaicInpainter(); + Ptr inp = makePtr(); inp->setStdevThresh(argf("mosaic-stdev")); inpainters->pushBack(inp); } if (arg("motion-inpaint") == "yes") { - MotionInpainter *inp = new MotionInpainter(); + Ptr inp = makePtr(); inp->setDistThreshold(argf("mi-dist-thresh")); inpainters->pushBack(inp); } if (arg("color-inpaint") == "average") - inpainters->pushBack(new ColorAverageInpainter()); + inpainters->pushBack(makePtr()); else if (arg("color-inpaint") == "ns") - inpainters->pushBack(new ColorInpainter(INPAINT_NS, argd("ci-radius"))); + inpainters->pushBack(makePtr(int(INPAINT_NS), argd("ci-radius"))); else if (arg("color-inpaint") == "telea") - inpainters->pushBack(new ColorInpainter(INPAINT_TELEA, argd("ci-radius"))); + inpainters->pushBack(makePtr(int(INPAINT_TELEA), argd("ci-radius"))); else if (arg("color-inpaint") != "no") throw runtime_error("unknown color inpainting method: " + arg("color-inpaint")); if (!inpainters->empty()) diff --git a/samples/gpu/performance/tests.cpp b/samples/gpu/performance/tests.cpp index ea01552085..3ca9e6a72f 100644 --- a/samples/gpu/performance/tests.cpp +++ b/samples/gpu/performance/tests.cpp @@ -1269,7 +1269,7 @@ TEST(FarnebackOpticalFlow) namespace cv { - template<> void Ptr::delete_obj() + template<> void DefaultDeleter::operator ()(CvBGStatModel* obj) const { cvReleaseBGStatModel(&obj); } diff --git a/samples/gpu/stereo_multi.cpp b/samples/gpu/stereo_multi.cpp index 4ecddf9340..bb75cf5e31 100644 --- a/samples/gpu/stereo_multi.cpp +++ b/samples/gpu/stereo_multi.cpp @@ -291,11 +291,11 @@ StereoMultiGpuStream::StereoMultiGpuStream() { cuda::setDevice(0); d_algs[0] = cuda::createStereoBM(256); - streams[0] = new Stream; + streams[0] = makePtr(); cuda::setDevice(1); d_algs[1] = cuda::createStereoBM(256); - streams[1] = new Stream; + streams[1] = makePtr(); } StereoMultiGpuStream::~StereoMultiGpuStream() diff --git a/samples/gpu/super_resolution.cpp b/samples/gpu/super_resolution.cpp index b982c334c9..7b9decc3ac 100644 --- a/samples/gpu/super_resolution.cpp +++ b/samples/gpu/super_resolution.cpp @@ -53,7 +53,7 @@ static Ptr createOptFlow(const string& name, bool useGpu) { cerr << "Incorrect Optical Flow algorithm - " << name << endl; } - return 0; + return Ptr(); } #if defined(HAVE_OPENCV_OCL) static Ptr createOptFlow(const string& name) @@ -73,7 +73,7 @@ static Ptr createOptFlow(const string& name) else if (name == "brox") { std::cout<<"brox has not been implemented!\n"; - return NULL; + return Ptr(); } else if (name == "pyrlk") return createOptFlow_PyrLK_OCL(); @@ -81,7 +81,7 @@ static Ptr createOptFlow(const string& name) { cerr << "Incorrect Optical Flow algorithm - " << name << endl; } - return 0; + return Ptr(); } #endif int main(int argc, const char* argv[]) @@ -197,7 +197,7 @@ int main(int argc, const char* argv[]) frameSource.release(); } } - if (frameSource.empty()) + if (!frameSource) frameSource = createFrameSource_Video(inputVideoName); // skip first frame, it is usually corrupted