Title: Checking your OpenCV version using Python - PyImageSearch

URL Source: https://pyimagesearch.com/2015/08/10/checking-your-opencv-version-using-python/

Published Time: 2015-08-10T14:00:13+00:00

Markdown Content:
[![Image 1: opencv_versions_header](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20808'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/opencv_versions_header.jpg)

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!

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

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](https://github.com/jrosebr1/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](https://github.com/jrosebr1/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:

[![Image 3: Figure 1: We are going to utilize OpenCV 2.4.X and OpenCV 3 to detect the contours of the Tetris blocks.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20482%20250'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/tetris_blocks.png)

**Figure 1:** We are going to utilize OpenCV 2.4.X and OpenCV 3 to detect the contours (i.e. outlines) of the Tetris blocks.

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:

[![Image 4: Figure 2: Our call to cv2.findContours is working in OpenCV 2.4.X.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20411'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/opencv_versions_contours_working.jpg)

**Figure 2:** Our call to cv2.findContours is working in OpenCV 2.4.X.

And the same is true for OpenCV 3:

[![Image 5: Figure 3: And the same is true for OpenCV 3 since we are using the is_cv2 and is_cv3 functions to detect OpenCV versions with Python.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20400'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/opencv_versions_contours_working_cv3.jpg)

**Figure 3:** And the same is true for OpenCV 3 since we are using the is\_cv2 and is\_cv3 functions to detect OpenCV versions with Python.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 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:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ 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_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

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](https://github.com/jrosebr1/imutils) 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.

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### 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!