OpenCV 3.0 was released recently, and you might be thinking of upgrading your code base. OpenCV 2 code will most likely not compile with OpenCV 3 because the new version is not backwardly compatible. So you need a mechanism to make sure your code is compatible with both OpenCV 3 and OpenCV 2. This post explains how to detect the version of OpenCV inside your code. Example C++ and Python code is shown below.
How to Detect OpenCV Version in Python
Everything is easy in Python. cv2.__version__ gives you the version string. You can extract major and minor version from it as shown in the example below.
import cv2
# Print version string
print "OpenCV version : {0}".format(cv2.__version__)
# Extract major, minor, and subminor version numbers
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
print "Major version : {0}".format(major_ver)
print "Minor version : {0}".format(minor_ver)
print "Submior version : {0}".format(subminor_ver)
if int(major_ver) < 3 :
'''
Old OpenCV 2 code goes here
'''
else :
'''
New OpenCV 3 code goes here
'''
How to Detect OpenCV Version in C++
In C++ several macros are defined to easily detect the version — CV_VERSION, CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION. See the sample code below as an example.
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
cout << "OpenCV version : " << CV_VERSION << endl;
cout << "Major version : " << CV_MAJOR_VERSION << endl;
cout << "Minor version : " << CV_MINOR_VERSION << endl;
cout << "Subminor version : " << CV_SUBMINOR_VERSION << endl;
if ( CV_MAJOR_VERSION < 3)
{
// Old OpenCV 2 code goes here.
} else
{
// New OpenCV 3 code goes here.
}
}
You can see another example at my post about Blob Detector.