It was unavoidable — the OpenCV 3 release was bound to break backwards compatibility with some OpenCV 2.4.X functions: cv2.findContours
and cv2.normalize
come to mind right off the top of my head.
So how do you ensure that your code will work no matter which version of OpenCV your production environment is using?
Well, the short answer is that you’ll need to create if
statements around each of the offending functions (or abstract the functions away to a separate method that handles calling the appropriate function based on your OpenCV version).
In order to do this, you’ll need to be able to check your OpenCV version from within your using Python — and that’s exactly what the rest of this blog will show you how to do!
Checking your OpenCV version using Python
The OpenCV version is contained within a special cv2.__version__
variable, which you can access like this:
$ python >>> import cv2 >>> cv2.__version__ '3.0.0'
The cv2.__version__
variable is simply a string which you can split into the major and minor versions:
>>> (major, minor, _) = cv2.__version__.split(".") >>> major '3' >>> minor '0'
Of course, having to perform this operation every time you need to check your OpenCV version is a bit of pain. To resolve this problem, I have added three new functions to my imutils package, a series of convenience functions to make basic image processing functions with OpenCV and Python easier.
You can see my is_cv2
, is_cv3
, and check_opencv_version
functions below:
def is_cv2(): # if we are using OpenCV 2, then our cv2.__version__ will start # with '2.' return check_opencv_version("2.") def is_cv3(): # if we are using OpenCV 3.X, then our cv2.__version__ will start # with '3.' return check_opencv_version("3.") def is_cv4(): # if we are using OpenCV 3.X, then our cv2.__version__ will start # with '4.' return check_opencv_version("4.") def check_opencv_version(major, lib=None): # if the supplied library is None, import OpenCV if lib is None: import cv2 as lib # return whether or not the current OpenCV version matches the # major version number return lib.__version__.startswith(major)
The code here is fairly straightforward — I’m simply checking if the cv2.__version__
string starts with a 2
, indicating we are using OpenCV 2.X, a 3
, to indicate that we are using OpenCV 3, or a 4
, to indicate that we are using OpenCV 4.
Again, these functions have already been included in the imutils package, which you can install using pip:
$ pip install imutils
If you already have imutils
installed, you can upgrade to the latest version using:
$ pip install --upgrade imutils
Checking your OpenCV version: a real-world example
Now that we know how to check our OpenCV version using Python as well as defined a couple convenience functions to make the version check easier, let’s see how we can use these functions in a real-world example.
Our goal here is to detect contours in the following image:
In order to detect contours in an image, we’ll need to use the cv2.findContours
function. However, as we know, the return signature of cv2.findContours
has changed slightly between version 3 and 2.4 of OpenCV (the OpenCV 3 version of cv2.findContours
returns an extra value in the tuple) — thus we’ll need to perform a check to our OpenCV version prior to making a call to cv2.findContours
to ensure our script does not error out. Let’s take a look at how we can make this check:
# import the necessary packages from __future__ import print_function import imutils import cv2 # load the Tetris block image, convert it to grayscale, and threshold # the image print("OpenCV Version: {}".format(cv2.__version__)) image = cv2.imread("tetris_blocks.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1] # check to see if we are using OpenCV 2.X or OpenCV 4 if imutils.is_cv2() or imutils.is_cv4(): (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # check to see if we are using OpenCV 3 elif imutils.is_cv3(): (_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # draw the contours on the image cv2.drawContours(image, cnts, -1, (240, 0, 159), 3) cv2.imshow("Image", image) cv2.waitKey(0)
As you can see, all we need to do is make a call to is_cv2
, is_cv4
, and is_cv3
and then wrap our version specific code inside the if
statement blocks — that’s it!
Now when I go to execute my script using OpenCV 2.4, it works without a problem:
And the same is true for OpenCV 3:
What's next? We recommend PyImageSearch University.
86+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: April 2025
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 86+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ hours hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this blog post we learned how to check our OpenCV version using Python. The OpenCV version is included in a special string variable named cv2.__version__
. All we need to do is check this variable and we’ll be able to determine our OpenCV version.
Finally, I have defined a few convenience methods inside the imutils package to make checking your OpenCV version easier and more Pythonic. Consider checking the library out if you find yourself needing to consistently check OpenCV versions.
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Thanks for the tutorial, Adrian.
Unfortunately, imutils is no avail for windows. How could it be solved?
You can install it via pip:
pip install imutils
Yes, Adrian!
It works again. Thanks!
Hi Adrian. Get tutorials.
I’m attempting a project using a RasPi which sorts small building blocks by size and colour. Firstly, its looking for cube blocks of a certain size – anything too small/large/long etc it ignores and secondly, if the correct size, it determines the block colour. Its looking for red, blue and yellow.
Could I use the code type above to detect block size? I’m thinking threshold (background will be white) and get object area in pixels. Compare this to area of ‘ideal’ block?
I tried previously using object detection with a template image of an ‘ideal’ block but the Pi seemed quite slow at this and the camera focus isn’t great at close distances.
I’d love to hear your thoughts! Thanks
Hey Brian, if you’re looking to compute the size of the block, use the
cv2.contourArea
function. You can see an example of computing the contour area in this post.Hey Adrian,
I am using opencv 3.1.0 but the repo on github to which I want to contribute to uses ‘import cv’ statement to use it so which OpenCV version should I install to use it.
I know it is a silly question but it is very important to get the answer.
Thanks
If you want access to the old “cv” bindings you should either (1) use OpenCV 2.4 where you an access them via
cv2.cv.*
or (2) you can compile OpenCV 3 with the previous bindings enabled. I’m not sure what the configuration switch to CMake is to do that. I would suggest runningccmake ..
(note the two “c’s” in the command and then enabling any option related to “opencv world”.For OpenCV versions prior to 2.4.0 the cv2.__versions__ string looks like “$Rev: 1234 $” so your split example will fail and your is_cv2 will not work in all cases.
Very true, thanks for pointing this out Andrew. However, if you’re using OpenCV prior to v2.4.0, you likely have other issues 🙂
Thanks for providing imutils – it’s very useful!
No problem! 🙂
Awesome support.Thanks for the help.
Glad I could help Rishabh!
Hello again adrian,
adrian i get an problem.
when i want to check my opencv. i can’t find anything
when i check the python, the last update of python was ini january.
i following your step to install python dan opencv in middle of october, but i can’t find anything.
but in the file manager opencv is already.
could you help me adrian? thank you so much..
Hi Olivia — I’m not sure what your question is here. What do you mean by “I can’t find anything”? You cannot import OpenCV into your Python scripts?
Bravo~ : )
Hi, I like your articles and I’ve purchased your on-line book.
However …
New-comers to this topic (Opencv, Python, etc) often experience problems with code examples caused by lack of clear information about what versions of the various items should be used ;- Python 2.7 ?? or 3.x ??, opencv 2.4 or 3.x ??, etc, etc
I strongly recommend that ‘experts’ such as yourself add comments at the start of every program, such as;-
“ ….Know to work with …Python X.X, opencv X.X, Windows X, …etc
or
Versions required;- opencv X.x, imutils X.x or later, Python X.x (might not work with earlier versions) … “
It may seem tedious or obvious to ‘Experts’, but lack of clarity about needed versions often causes problems for new-comers.
Such information will help many people and will also will reduce the time needed later to fix bugs after they happen.
Please, please do this going forward , thanks.
(I’m using Python 2.7, cv2 2.4, imutils 0.4.6, Windows 7 home premium, service pack 1., 64 bit)