1 Transition guide {#tutorial_transition_guide} 2 ================ 3 4 @tableofcontents 5 6 Changes overview {#tutorial_transition_overview} 7 ================ 8 This document is intended to software developers who want to migrate their code to OpenCV 3.0. 9 10 OpenCV 3.0 introduced many new algorithms and features comparing to version 2.4. Some modules have been rewritten, some have been reorganized. Although most of the algorithms from 2.4 are still present, the interfaces can differ. 11 12 This section describes most notable changes in general, all details and examples of transition actions are in the next part of the document. 13 14 ##### Contrib repository 15 <https://github.com/Itseez/opencv_contrib> 16 17 This is a place for all new, experimental and non-free algorithms. It does not receive so much attention from the support team comparing to main repository, but the community makes an effort to keep it in a good shape. 18 19 To build OpenCV with _contrib_ repository, add the following option to your cmake command: 20 @code{.sh} 21 -DOPENCV_EXTRA_MODULES_PATH=<path-to-opencv_contrib>/modules 22 @endcode 23 24 ##### Headers layout 25 In 2.4 all headers are located in corresponding module subfolder (_opencv2/\<module\>/\<module\>.hpp_), in 3.0 there are top-level module headers containing the most of the module functionality: _opencv2/\<module\>.hpp_ and all C-style API definitions have been moved to separate headers (for example opencv2/core/core_c.h). 26 27 ##### Algorithm interfaces 28 General algorithm usage pattern has changed: now it must be created on heap wrapped in smart pointer cv::Ptr. Version 2.4 allowed both stack and heap allocations, directly or via smart pointer. 29 30 _get_ and _set_ methods have been removed from the cv::Algorithm class along with _CV_INIT_ALGORITHM_ macro. In 3.0 all properties have been converted to the pairs of _getProperty/setProperty_ pure virtual methods. As a result it is __not__ possible to create and use cv::Algorithm instance by name (using generic _Algorithm::create(String)_ method), one should call corresponding factory method explicitly. 31 32 ##### Changed modules 33 - _ml_ module has been rewritten 34 - _highgui_ module has been split into parts: _imgcodecs_, _videoio_ and _highgui_ itself 35 - _features2d_ module have been reorganized (some feature detectors has been moved to _opencv_contrib/xfeatures2d_ module) 36 - _legacy_, _nonfree_ modules have been removed. Some algorithms have been moved to different locations and some have been completely rewritten or removed 37 - CUDA API has been updated (_gpu_ module -> several _cuda_ modules, namespace _gpu_ -> namespace _cuda_) 38 - OpenCL API has changed (_ocl_ module has been removed, separate _ocl::_ implementations -> Transparent API) 39 - Some other methods and classes have been relocated 40 41 Transition hints {#tutorial_transition_hints} 42 ================ 43 This section describes concrete actions with examples. 44 45 Prepare 2.4 {#tutorial_transition_hints_24} 46 ----------- 47 Some changes made in the latest 2.4.11 OpenCV version allow you to prepare current codebase to migration: 48 49 - cv::makePtr function is now available 50 - _opencv2/\<module\>.hpp_ headers have been created 51 52 New headers layout {#tutorial_transition_hints_headers} 53 ------------------ 54 __Note:__ 55 Changes intended to ease the migration have been made in OpenCV 3.0, thus the following instructions are not necessary, but recommended. 56 57 1. Replace inclusions of old module headers: 58 @code{.cpp} 59 // old header 60 #include "opencv2/<module>/<module>.hpp" 61 // new header 62 #include "opencv2/<module>.hpp" 63 @endcode 64 65 2. If your code is using C API (`cv*` functions, `Cv*` structures or `CV_*` enumerations), include corresponding `*_c.h` headers. Although it is recommended to use C++ API, most of C-functions are still accessible in separate header files (opencv2/core/core_c.h, opencv2/core/types_c.h, opencv2/imgproc/imgproc_c.h, etc.). 66 67 Modern way to use algorithm {#tutorial_transition_algorithm} 68 --------------------------- 69 1. Algorithm instances must be created with cv::makePtr function or corresponding static factory method if available: 70 @code{.cpp} 71 // good ways 72 Ptr<SomeAlgo> algo = makePtr<SomeAlgo>(...); 73 Ptr<SomeAlgo> algo = SomeAlgo::create(...); 74 @endcode 75 Other ways are deprecated: 76 @code{.cpp} 77 // bad ways 78 Ptr<SomeAlgo> algo = new SomeAlgo(...); 79 SomeAlgo * algo = new SomeAlgo(...); 80 SomeAlgo algo(...); 81 Ptr<SomeAlgo> algo = Algorithm::create<SomeAlgo>("name"); 82 @endcode 83 84 2. Algorithm properties should be accessed via corresponding virtual methods, _getSomeProperty/setSomeProperty_, generic _get/set_ methods have been removed: 85 @code{.cpp} 86 // good way 87 double clipLimit = clahe->getClipLimit(); 88 clahe->setClipLimit(clipLimit); 89 // bad way 90 double clipLimit = clahe->getDouble("clipLimit"); 91 clahe->set("clipLimit", clipLimit); 92 clahe->setDouble("clipLimit", clipLimit); 93 @endcode 94 95 96 3. Remove `initModule_<moduleName>()` calls 97 98 Machine learning module {#tutorial_transition_hints_ml} 99 ----------------------- 100 Since this module has been rewritten, it will take some effort to adapt your software to it. All algorithms are located in separate _ml_ namespace along with their base class _StatModel_. Separate _SomeAlgoParams_ classes have been replaced with a sets of corresponding _getProperty/setProperty_ methods. 101 102 The following table illustrates correspondence between 2.4 and 3.0 machine learning classes. 103 104 | 2.4 | 3.0 | 105 | --------- | --------- | 106 | CvStatModel | cv::ml::StatModel | 107 | CvNormalBayesClassifier | cv::ml::NormalBayesClassifier | 108 | CvKNearest | cv::ml::KNearest | 109 | CvSVM | cv::ml::SVM | 110 | CvDTree | cv::ml::DTrees | 111 | CvBoost | cv::ml::Boost | 112 | CvGBTrees | _Not implemented_ | 113 | CvRTrees | cv::ml::RTrees | 114 | CvERTrees | _Not implemented_ | 115 | EM | cv::ml::EM | 116 | CvANN_MLP | cv::ml::ANN_MLP | 117 | _Not implemented_ | cv::ml::LogisticRegression | 118 | CvMLData | cv::ml::TrainData | 119 120 Although rewritten _ml_ algorithms in 3.0 allow you to load old trained models from _xml/yml_ file, deviations in prediction process are possible. 121 122 The following code snippets from the `points_classifier.cpp` example illustrate differences in model training process: 123 @code{.cpp} 124 using namespace cv; 125 // ======== version 2.4 ======== 126 Mat trainSamples, trainClasses; 127 prepare_train_data( trainSamples, trainClasses ); 128 CvBoost boost; 129 Mat var_types( 1, trainSamples.cols + 1, CV_8UC1, Scalar(CV_VAR_ORDERED) ); 130 var_types.at<uchar>( trainSamples.cols ) = CV_VAR_CATEGORICAL; 131 CvBoostParams params( CvBoost::DISCRETE, // boost_type 132 100, // weak_count 133 0.95, // weight_trim_rate 134 2, // max_depth 135 false, //use_surrogates 136 0 // priors 137 ); 138 boost.train( trainSamples, CV_ROW_SAMPLE, trainClasses, Mat(), Mat(), var_types, Mat(), params ); 139 140 // ======== version 3.0 ======== 141 Ptr<Boost> boost = Boost::create(); 142 boost->setBoostType(Boost::DISCRETE); 143 boost->setWeakCount(100); 144 boost->setWeightTrimRate(0.95); 145 boost->setMaxDepth(2); 146 boost->setUseSurrogates(false); 147 boost->setPriors(Mat()); 148 boost->train(prepare_train_data()); // 'prepare_train_data' returns an instance of ml::TrainData class 149 @endcode 150 151 Features detect {#tutorial_transition_hints_features} 152 --------------- 153 Some algorithms (FREAK, BRIEF, SIFT, SURF) has been moved to _opencv_contrib_ repository, to _xfeatures2d_ module, _xfeatures2d_ namespace. Their interface has been also changed (inherit from `cv::Feature2D` base class). 154 155 List of _xfeatures2d_ module classes: 156 157 - cv::xfeatures2d::BriefDescriptorExtractor - Class for computing BRIEF descriptors (2.4 location: _features2d_) 158 - cv::xfeatures2d::FREAK - Class implementing the FREAK (Fast Retina Keypoint) keypoint descriptor (2.4 location: _features2d_) 159 - cv::xfeatures2d::StarDetector - The class implements the CenSurE detector (2.4 location: _features2d_) 160 - cv::xfeatures2d::SIFT - Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform (SIFT) algorithm (2.4 location: _nonfree_) 161 - cv::xfeatures2d::SURF - Class for extracting Speeded Up Robust Features from an image (2.4 location: _nonfree_) 162 163 Following steps are needed: 164 1. Add _opencv_contrib_ to compilation process 165 2. Include `opencv2/xfeatures2d.h` header 166 3. Use namespace `xfeatures2d` 167 4. Replace `operator()` calls with `detect`, `compute` or `detectAndCompute` if needed 168 169 Some classes now use general methods `detect`, `compute` or `detectAndCompute` provided by `Feature2D` base class instead of custom `operator()` 170 171 Following code snippets illustrate the difference (from `video_homography.cpp` example): 172 @code{.cpp} 173 using namespace cv; 174 // ====== 2.4 ======= 175 #include "opencv2/features2d/features2d.hpp" 176 BriefDescriptorExtractor brief(32); 177 GridAdaptedFeatureDetector detector(new FastFeatureDetector(10, true), DESIRED_FTRS, 4, 4); 178 // ... 179 detector.detect(gray, query_kpts); //Find interest points 180 brief.compute(gray, query_kpts, query_desc); //Compute brief descriptors at each keypoint location 181 // ====== 3.0 ======= 182 #include "opencv2/features2d.hpp" 183 #include "opencv2/xfeatures2d.hpp" 184 using namespace cv::xfeatures2d; 185 Ptr<BriefDescriptorExtractor> brief = BriefDescriptorExtractor::create(32); 186 Ptr<FastFeatureDetector> detector = FastFeatureDetector::create(10, true); 187 // ... 188 detector->detect(gray, query_kpts); //Find interest points 189 brief->compute(gray, query_kpts, query_desc); //Compute brief descriptors at each keypoint location 190 @endcode 191 192 OpenCL {#tutorial_transition_hints_opencl} 193 ------ 194 All specialized `ocl` implemetations has been hidden behind general C++ algorithm interface. Now the function execution path can be selected dynamically at runtime: CPU or OpenCL; this mechanism is also called "Transparent API". 195 196 New class cv::UMat is intended to hide data exchange with OpenCL device in a convinient way. 197 198 Following example illustrate API modifications (from [OpenCV site](http://opencv.org/platforms/opencl.html)): 199 200 - OpenCL-aware code OpenCV-2.x 201 @code{.cpp} 202 // initialization 203 VideoCapture vcap(...); 204 ocl::OclCascadeClassifier fd("haar_ff.xml"); 205 ocl::oclMat frame, frameGray; 206 Mat frameCpu; 207 vector<Rect> faces; 208 for(;;){ 209 // processing loop 210 vcap >> frameCpu; 211 frame = frameCpu; 212 ocl::cvtColor(frame, frameGray, BGR2GRAY); 213 ocl::equalizeHist(frameGray, frameGray); 214 fd.detectMultiScale(frameGray, faces, ...); 215 // draw rectangles 216 // show image 217 } 218 @endcode 219 - OpenCL-aware code OpenCV-3.x 220 @code{.cpp} 221 // initialization 222 VideoCapture vcap(...); 223 CascadeClassifier fd("haar_ff.xml"); 224 UMat frame, frameGray; // the only change from plain CPU version 225 vector<Rect> faces; 226 for(;;){ 227 // processing loop 228 vcap >> frame; 229 cvtColor(frame, frameGray, BGR2GRAY); 230 equalizeHist(frameGray, frameGray); 231 fd.detectMultiScale(frameGray, faces, ...); 232 // draw rectangles 233 // show image 234 } 235 @endcode 236 237 CUDA {#tutorial_transition_hints_cuda} 238 ---- 239 _cuda_ module has been split into several smaller pieces: 240 - _cuda_ - @ref cuda 241 - _cudaarithm_ - @ref cudaarithm 242 - _cudabgsegm_ - @ref cudabgsegm 243 - _cudacodec_ - @ref cudacodec 244 - _cudafeatures2d_ - @ref cudafeatures2d 245 - _cudafilters_ - @ref cudafilters 246 - _cudaimgproc_ - @ref cudaimgproc 247 - _cudalegacy_ - @ref cudalegacy 248 - _cudaoptflow_ - @ref cudaoptflow 249 - _cudastereo_ - @ref cudastereo 250 - _cudawarping_ - @ref cudawarping 251 - _cudev_ - @ref cudev 252 253 `gpu` namespace has been removed, use cv::cuda namespace instead. Many classes has also been renamed, for example: 254 - `gpu::FAST_GPU` -> cv::cuda::FastFeatureDetector 255 - `gpu::createBoxFilter_GPU` -> cv::cuda::createBoxFilter 256 257 Documentation format {#tutorial_transition_docs} 258 -------------------- 259 Documentation has been converted to Doxygen format. You can find updated documentation writing guide in _Tutorials_ section of _OpenCV_ reference documentation (@ref tutorial_documentation). 260 261 Support both versions {#tutorial_transition_both} 262 --------------------- 263 In some cases it is possible to support both versions of OpenCV. 264 265 ### Source code 266 267 To check library major version in your application source code, the following method should be used: 268 @code{.cpp} 269 #include "opencv2/core/version.hpp" 270 #if CV_MAJOR_VERSION == 2 271 // do opencv 2 code 272 #elif CV_MAJOR_VERSION == 3 273 // do opencv 3 code 274 #endif 275 @endcode 276 277 @note Do not use __CV_VERSION_MAJOR__, it has different meaning for 2.4 and 3.x branches! 278 279 ### Build system 280 281 It is possible to link different modules or enable/disable some of the features in your application by checking library version in the build system. Standard cmake or pkg-config variables can be used for this: 282 - `OpenCV_VERSION` for cmake will contain full version: "2.4.11" or "3.0.0" for example 283 - `OpenCV_VERSION_MAJOR` for cmake will contain only major version number: 2 or 3 284 - pkg-config file has standard field `Version` 285 286 Example: 287 @code{.cmake} 288 if(OpenCV_VERSION VERSION_LESS "3.0") 289 # use 2.4 modules 290 else() 291 # use 3.x modules 292 endif() 293 @endcode 294