Introduction to OpenCV

Introduction to OpenCV

Learn how to setup OpenCV-Python on your computer!

Introduction to OpenCV-Python Tutorials


OpenCV was started at Intel in 1999 by Gary Bradsky and the first release came out in 2000. Vadim Pisarevsky joined Gary Bradsky to manage Intel’s Russian software OpenCV team. In 2005, OpenCV was used on Stanley, the vehicle who won 2005 DARPA Grand Challenge. Later its active development continued under the support of Willow Garage, with Gary Bradsky and Vadim Pisarevsky leading the project. Right now, OpenCV supports a lot of algorithms related to Computer Vision and Machine Learning and it is expanding day-by-day.

Currently OpenCV supports a wide variety of programming languages like C++, Python, Java etc and is available on different platforms including Windows, Linux, OS X, Android, iOS etc. Also, interfaces based on CUDA and OpenCL are also under active development for high-speed GPU operations.

OpenCV-Python is the Python API of OpenCV. It combines the best qualities of OpenCV C++ API and Python language.


Python is a general purpose programming language started by Guido van Rossum, which became very popular in short time mainly because of its simplicity and code readability. It enables the programmer to express his ideas in fewer lines of code without reducing any readability.

Compared to other languages like C/C++, Python is slower. But another important feature of Python is that it can be easily extended with C/C++. This feature helps us to write computationally intensive codes in C/C++ and create a Python wrapper for it so that we can use these wrappers as Python modules. This gives us two advantages: first, our code is as fast as original C/C++ code (since it is the actual C++ code working in background) and second, it is very easy to code in Python. This is how OpenCV-Python works, it is a Python wrapper around original C++ implementation.

And the support of Numpy makes the task more easier. Numpy is a highly optimized library for numerical operations. It gives a MATLAB-style syntax. All the OpenCV array structures are converted to-and-from Numpy arrays. So whatever operations you can do in Numpy, you can combine it with OpenCV, which increases number of weapons in your arsenal. Besides that, several other libraries like SciPy, Matplotlib which supports Numpy can be used with this.

So OpenCV-Python is an appropriate tool for fast prototyping of computer vision problems.

OpenCV-Python Tutorials

OpenCV introduces a new set of tutorials which will guide you through various functions available in OpenCV-Python. This guide is mainly focused on OpenCV 3.x version (although most of the tutorials will work with OpenCV 2.x also).

A prior knowledge on Python and Numpy is required before starting because they won’t be covered in this guide. Especially, a good knowledge on Numpy is must to write optimized codes in OpenCV-Python.

This tutorial has been started by Abid Rahman K. as part of Google Summer of Code 2013 program, under the guidance of Alexander Mordvintsev.

OpenCV Needs You !!

Since OpenCV is an open source initiative, all are welcome to make contributions to this library. And it is same for this tutorial also.

So, if you find any mistake in this tutorial (whether it be a small spelling mistake or a big error in code or concepts, whatever), feel free to correct it.

And that will be a good task for freshers who begin to contribute to open source projects. Just fork the OpenCV in github, make necessary corrections and send a pull request to OpenCV. OpenCV developers will check your pull request, give you important feedback and once it passes the approval of the reviewer, it will be merged to OpenCV. Then you become a open source contributor. Similar is the case with other tutorials, documentation etc.

As new modules are added to OpenCV-Python, this tutorial will have to be expanded. So those who knows about particular algorithm can write up a tutorial which includes a basic theory of the algorithm and a code showing basic usage of the algorithm and submit it to OpenCV.

Remember, we together can make this project a great success !!!

Install OpenCV-Python in Windows


In this tutorial

  • We will learn to setup OpenCV-Python in your Windows system.

Below steps are tested in a Windows 7-64 bit machine with Visual Studio 2010 and Visual Studio 2012. The screenshots shows VS2012.

Installing OpenCV from prebuilt binaries

  1. Below Python packages are to be downloaded and installed to their default locations.
> 1.1\. [Python-2.7.x](
> 1.2\. [Numpy](
> 1.3\. [Matplotlib]( (_Matplotlib is optional, but recommended since we use it a lot in our tutorials_).
  1. Install all packages into their default locations. Python will be installed to C:/Python27/.

  2. After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.

  3. Download latest OpenCV release from sourceforge site and double-click to extract it.

  4. Goto opencv/build/python/2.7 folder.

  5. Copy cv2.pyd to C:/Python27/lib/site-packeges.

  6. Open Python IDLE and type following codes in Python terminal.

>>> import cv2
>>> print cv2.__version__

If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.

Building OpenCV from source

  1. Download and install Visual Studio and CMake.

    1.1. Visual Studio 2012

    1.2. CMake

  2. Download and install necessary Python packages to their default locations

    2.1. Python 2.7.x

    2.2. Numpy

    2.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials.)


In this case, we are using 32-bit binaries of Python packages. But if you want to use OpenCV for x64, 64-bit binaries of Python packages are to be installed. Problem is that, there is no official 64-bit binaries of Numpy. You have to build it on your own. For that, you have to use the same compiler used to build Python. When you start Python IDLE, it shows the compiler details. You can get more information here. So your system must have the same Visual Studio version and build Numpy from source.


Another method to have 64-bit Python packages is to use ready-made Python distributions from third-parties like Anaconda, Enthought etc. It will be bigger in size, but will have everything you need. Everything in a single shell. You can also download 32-bit versions also.

  1. Make sure Python and Numpy are working fine.

  2. Download OpenCV source. It can be from Sourceforge (for official release version) or from Github (for latest source).

  3. Extract it to a folder, <span class="pre">opencv</span> and create a new folder <span class="pre">build</span> in it.

  4. Open CMake-gui (Start > All Programs > CMake-gui)

  5. Fill the fields as follows (see the image below):

    7.1. Click on Browse Source... and locate the <span class="pre">opencv</span> folder.

    7.2. Click on Browse Build... and locate the <span class="pre">build</span> folder we created.

    7.3. Click on Configure.


    7.4. It will open a new window to select the compiler. Choose appropriate compiler (here, Visual Studio 11) and click Finish.


    7.5. Wait until analysis is finished.

  1. You will see all the fields are marked in red. Click on the WITH field to expand it. It decides what extra features you need. So mark appropriate fields. See the below image:


  2. Now click on BUILD field to expand it. First few fields configure the build method. See the below image:


  3. Remaining fields specify what modules are to be built. Since GPU modules are not yet supported by OpenCV-Python, you can completely avoid it to save time (But if you work with them, keep it there). See the image below:


  4. Now click on ENABLE field to expand it. Make sure ENABLE_SOLUTION_FOLDERS is unchecked (Solution folders are not supported by Visual Studio Express edition). See the image below:


  5. Also make sure that in the PYTHON field, everything is filled. (Ignore PYTHON_DEBUG_LIBRARY). See image below:


  6. Finally click the Generate button.

  7. Now go to our opencv/build folder. There you will find OpenCV.sln file. Open it with Visual Studio.

  8. Check build mode as Release instead of Debug.

  9. In the solution explorer, right-click on the Solution (or ALL_BUILD) and build it. It will take some time to finish.

  10. Again, right-click on INSTALL and build it. Now OpenCV-Python will be installed.


  11. Open Python IDLE and enter import cv2. If no error, it is installed correctly.


We have installed with no other support like TBB, Eigen, Qt, Documentation etc. It would be difficult to explain it here. A more detailed video will be added soon or you can just hack around.

Install OpenCV-Python in Fedora


In this tutorial

  • We will learn to setup OpenCV-Python in your Fedora system. Below steps are tested for Fedora 18 (64-bit) and Fedora 19 (32-bit).


OpenCV-Python can be installed in Fedora in two ways, 1) Install from pre-built binaries available in fedora repositories, 2) Compile from the source. In this section, we will see both.

Another important thing is the additional libraries required. OpenCV-Python requires only Numpy (in addition to other dependencies, which we will see later). But in this tutorials, we also use Matplotlib for some easy and nice plotting purposes (which I feel much better compared to OpenCV). Matplotlib is optional, but highly recommended. Similarly we will also see IPython, an Interactive Python Terminal, which is also highly recommended.

Installing OpenCV-Python from Pre-built Binaries

Install all packages with following command in terminal as root.

$ yum install numpy opencv*

Open Python IDLE (or IPython) and type following codes in Python terminal.

>>> import cv2
>>> print cv2.__version__

If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.

It is quite easy. But there is a problem with this. Yum repositories may not contain the latest version of OpenCV always. For example, at the time of writing this tutorial, yum repository contains 2.4.5 while latest OpenCV version is 2.4.6. With respect to Python API, latest version will always contain much better support. Also, there may be chance of problems with camera support, video playback etc depending upon the drivers, ffmpeg, gstreamer packages present etc.

So my personnel preference is next method, i.e. compiling from source. Also at some point of time, if you want to contribute to OpenCV, you will need this.

Installing OpenCV from source

Compiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing complicated.

First we will install some dependencies. Some are compulsory, some are optional. Optional dependencies, you can leave if you don’t want.

Compulsory Dependencies

We need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for creating Python extensions etc.

yum install cmake
yum install python-devel numpy
yum install gcc gcc-c++

Next we need GTK support for GUI features, Camera support (libdc1394, libv4l), Media Support (ffmpeg, gstreamer) etc.

yum install gtk2-devel
yum install libdc1394-devel
yum install libv4l-devel
yum install ffmpeg-devel
yum install gstreamer-plugins-base-devel

Optional Dependencies

Above dependencies are sufficient to install OpenCV in your fedora machine. But depending upon your requirements, you may need some extra dependencies. A list of such optional dependencies are given below. You can either leave it or install it, your call :)

OpenCV comes with supporting files for image formats like PNG, JPEG, JPEG2000, TIFF, WebP etc. But it may be a little old. If you want to get latest libraries, you can install development files for these formats.

yum install libpng-devel
yum install libjpeg-turbo-devel
yum install jasper-devel
yum install openexr-devel
yum install libtiff-devel
yum install libwebp-devel

Several OpenCV functions are parallelized with Intel’s Threading Building Blocks (TBB). But if you want to enable it, you need to install TBB first. ( Also while configuring installation with CMake, don’t forget to pass <span class="pre">-D</span> <span class="pre">WITH_TBB=ON</span>. More details below.)

yum install tbb-devel

OpenCV uses another library Eigen for optimized mathematical operations. So if you have Eigen installed in your system, you can exploit it. ( Also while configuring installation with CMake, don’t forget to pass <span class="pre">-D</span> <span class="pre">WITH_EIGEN=ON</span>. More details below.)

yum install eigen3-devel

If you want to build documentation ( Yes, you can create offline version of OpenCV’s complete official documentation in your system in HTML with full search facility so that you need not access internet always if any question, and it is quite FAST!!! ), you need to install Sphinx (a documentation generation tool) and pdflatex (if you want to create a PDF version of it). ( Also while configuring installation with CMake, don’t forget to pass <span class="pre">-D</span> <span class="pre">BUILD_DOCS=ON</span>. More details below.)

yum install python-sphinx
yum install texlive

Downloading OpenCV

Next we have to download OpenCV. You can download the latest release of OpenCV from sourceforge site. Then extract the folder.

Or you can download latest source from OpenCV’s github repo. (If you want to contribute to OpenCV, choose this. It always keeps your OpenCV up-to-date). For that, you need to install Git first.

yum install git
git clone

It will create a folder OpenCV in home directory (or the directory you specify). The cloning may take some time depending upon your internet connection.

Now open a terminal window and navigate to the downloaded OpenCV folder. Create a new build folder and navigate to it.

mkdir build
cd build

Configuring and Installing

Now we have installed all the required dependencies, let’s install OpenCV. Installation has to be configured with CMake. It specifies which modules are to be installed, installation path, which additional libraries to be used, whether documentation and examples to be compiled etc. Below command is normally used for configuration (executed from build folder).


It specifies that build type is “Release Mode” and installation path is <span class="pre">/usr/local</span>. Observe the <span class="pre">-D</span> before each option and <span class="pre">..</span> at the end. In short, this is the format:

cmake [-D <flag>] [-D <flag>] ..

You can specify as many flags you want, but each flag should be preceded by -D.

So in this tutorial, we are installing OpenCV with TBB and Eigen support. We also build the documentation, but we exclude Performance tests and building samples. We also disable GPU related modules (since we use OpenCV-Python, we don’t need GPU related modules. It saves us some time).

(All the below commands can be done in a single cmake statement, but it is split here for better understanding.)

  • Enable TBB and Eigen support:

    cmake -D WITH_TBB=ON -D WITH_EIGEN=ON ..
  • Enable documentation and disable tests and samples

  • Disable all GPU related modules.

    cmake -D WITH_OPENCL=OFF -D WITH_CUDA=OFF -D BUILD_opencv_gpu=OFF -D BUILD_opencv_gpuarithm=OFF -D BUILD_opencv_gpubgsegm=OFF -D BUILD_opencv_gpucodec=OFF -D BUILD_opencv_gpufeatures2d=OFF -D BUILD_opencv_gpufilters=OFF -D BUILD_opencv_gpuimgproc=OFF -D BUILD_opencv_gpulegacy=OFF -D BUILD_opencv_gpuoptflow=OFF -D BUILD_opencv_gpustereo=OFF -D BUILD_opencv_gpuwarping=OFF ..
  • Set installation path and build type


Each time you enter cmake statement, it prints out the resulting configuration setup. In the final setup you got, make sure that following fields are filled (below is the some important parts of configuration I got). These fields should be filled appropriately in your system also. Otherwise some problem has happened. So check if you have correctly performed above steps.

--   GUI:
--     GTK+ 2.x:                    YES (ver 2.24.19)
--     GThread :                    YES (ver 2.36.3)

--   Video I/O:
--     DC1394 2.x:                  YES (ver 2.2.0)
--     FFMPEG:                      YES
--       codec:                     YES (ver 54.92.100)
--       format:                    YES (ver 54.63.104)
--       util:                      YES (ver 52.18.100)
--       swscale:                   YES (ver 2.2.100)
--       gentoo-style:              YES
--     GStreamer:
--       base:                      YES (ver 0.10.36)
--       video:                     YES (ver 0.10.36)
--       app:                       YES (ver 0.10.36)
--       riff:                      YES (ver 0.10.36)
--       pbutils:                   YES (ver 0.10.36)

--     V4L/V4L2:                    Using libv4l (ver 1.0.0)

--   Other third-party libraries:
--     Use Eigen:                   YES (ver 3.1.4)
--     Use TBB:                     YES (ver 4.0 interface 6004)

--   Python:
--     Interpreter:                 /usr/bin/python2 (ver 2.7.5)
--     Libraries:                   /lib/ (ver 2.7.5)
--     numpy:                       /usr/lib/python2.7/site-packages/numpy/core/include (ver 1.7.1)
--     packages path:               lib/python2.7/site-packages

--   Documentation:
--     Build Documentation:         YES
--     Sphinx:                      /usr/bin/sphinx-build (ver 1.1.3)
--     PdfLaTeX compiler:           /usr/bin/pdflatex
--   Tests and samples:
--     Tests:                       NO
--     Performance tests:           NO
--     C/C++ Examples:              NO

Many other flags and settings are there. It is left for you for further exploration.

Now you build the files using make command and install it using make install command. make install should be executed as root.

make install

Installation is over. All files are installed in <span class="pre">/usr/local/</span> folder. But to use it, your Python should be able to find OpenCV module. You have two options for that.

  1. Move the module to any folder in Python Path : Python path can be found out by entering import sys;print sys.path in Python terminal. It will print out many locations. Move /usr/local/lib/python2.7/site-packages/ to any of this folder. For example,
    su mv /usr/local/lib/python2.7/site-packages/ /usr/lib/python2.7/site-packages

But you will have to do this every time you install OpenCV.

  1. Add /usr/local/lib/python2.7/site-packages to the PYTHON_PATH: It is to be done only once. Just open ~/.bashrc and add following line to it, then log out and come back.
    export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages

Thus OpenCV installation is finished. Open a terminal and try import cv2.

To build the documentation, just enter following commands:

make docs
make html_docs

Then open opencv/build/doc/_html/index.html and bookmark it in the browser.

opencv python machine-learning

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How To Plot A Decision Boundary For Machine Learning Algorithms in Python

How To Plot A Decision Boundary For Machine Learning Algorithms in Python, you will discover how to plot a decision surface for a classification machine learning algorithm.

How To Get Started With Machine Learning With The Right Mindset

You got intrigued by the machine learning world and wanted to get started as soon as possible, read all the articles, watched all the videos, but still isn’t sure about where to start, welcome to the club.

What is Supervised Machine Learning

What is neuron analysis of a machine? Learn machine learning by designing Robotics algorithm. Click here for best machine learning course models with AI

Python For Machine Learning | Machine Learning With Python

Python For Machine Learning | Machine Learning With Python, you will be working on an end-to-end case study to understand different stages in the Machine Learning (ML) life cycle. This will deal with 'data manipulation' with pandas and 'data visualization' with seaborn. After this an ML model will be built on the dataset to get predictions. You will learn about the basics of scikit-learn library to implement the machine learning algorithm.

Python for Machine Learning | Machine Learning with Python

Python for Machine Learning | Machine Learning with Python, you'll be working on an end-to-end case study to understand different stages in the ML life cycle. This will deal with 'data manipulation' with pandas and 'data visualization' with seaborn. After this, an ML model will be built on the dataset to get predictions. You will learn about the basics of the sci-kit-learn library to implement the machine learning algorithm.