• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

Learn OpenCV

OpenCV examples and tutorials ( C++ / Python )

  • Home
  • About
  • Resources
  • AI Consulting
  • Courses

Install OpenCV 4 on Ubuntu 16.04 (C++ and Python)

September 17, 2018 By Vishwesh Shrimali 28 Comments

Install OpenCV on Ubuntu 16.04

OpenCV released OpenCV-3.4.4 and OpenCV-4.0.0 on 20th November. There have been a lot of bug fixes and other changes in these versions. The release highlights are as follows:

  • OpenCV is now C++11 library and requires C++11-compliant compiler. Minimum required CMake version has been raised to 3.5.1.
  • A lot of C API from OpenCV 1.x has been removed.
  • Persistence (storing and loading structured data to/from XML, YAML or JSON) in the core module has been completely reimplemented in C++ and lost the C API as well.
  • New module G-API has been added, it acts as an engine for very efficient graph-based image procesing pipelines.
  • dnn module now includes experimental Vulkan backend and supports networks in ONNX format.
  • The popular Kinect Fusion algorithm has been implemented and optimized for CPU and GPU (OpenCL)
    QR code detector and decoder have been added to the objdetect module.
  • Very efficient and yet high-quality DIS dense optical flow algorithm has been moved from opencv_contrib to the video module.

In this post, we will provide a bash script for installing OpenCV-4.0 (C++ and Python 3.5) on Ubuntu 16.04. We will also briefly study the script to understand what’s going in it. Note that this script will install OpenCV in a local directory and not on the entire system.

Looking for installation script for Ubuntu 18.04? Have a look at this blog.

1. Install OpenCV 4.0

Step 0: Select OpenCV version to install

echo "OpenCV installation by learnOpenCV.com"

# Define OpenCV version to install
cvVersion="master"

We are also going to clean build directories and create installation directory.

# Clean build directories
rm -rf opencv/build
rm -rf opencv_contrib/build
# Create directory for installation
mkdir installation
mkdir installation/OpenCV-"$cvVersion"

Finally, we will be storing the current working directory in cwd variable. We are also going to refer to this directory as OpenCV_Home_Dir throughout this blog.

# Save current working directory
cwd=$(pwd)

Step 1: Update Packages

sudo apt -y update
sudo apt -y upgrade
If you are still not able to install OpenCV on your system, but want to get started with it, we suggest using our docker images with pre-installed OpenCV, Dlib, miniconda and jupyter notebooks along with other dependencies as described in this blog.

Step 2: Install OS Libraries

sudo apt -y remove x264 libx264-dev

## Install dependencies
sudo apt -y install build-essential checkinstall cmake pkg-config yasm
sudo apt -y install git gfortran
sudo apt -y install libjpeg8-dev libjasper-dev libpng12-dev

sudo apt -y install libtiff5-dev

sudo apt -y install libtiff-dev

sudo apt -y install libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev
sudo apt -y install libxine2-dev libv4l-dev
cd /usr/include/linux
sudo ln -s -f ../libv4l1-videodev.h videodev.h
cd $cwd

sudo apt -y install libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev
sudo apt -y install libgtk2.0-dev libtbb-dev qt5-default
sudo apt -y install libatlas-base-dev
sudo apt -y install libfaac-dev libmp3lame-dev libtheora-dev
sudo apt -y install libvorbis-dev libxvidcore-dev
sudo apt -y install libopencore-amrnb-dev libopencore-amrwb-dev
sudo apt -y install libavresample-dev
sudo apt -y install x264 v4l-utils

# Optional dependencies
sudo apt -y install libprotobuf-dev protobuf-compiler
sudo apt -y install libgoogle-glog-dev libgflags-dev
sudo apt -y install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen
Looking for installation script for OpenCV 3.4.4 on Ubuntu 16.04? Have a look at this blog.

Step 3: Install Python Libraries

sudo apt -y install python3-dev python3-pip
sudo -H pip3 install -U pip numpy
sudo apt -y install python3-testresources

We are also going to install virtualenv and virtualenvwrapper modules to create Python virtual environments.

cd $cwd
############ For Python 3 ############
# create virtual environment
python3 -m venv OpenCV-"$cvVersion"-py3
echo "# Virtual Environment Wrapper" >> ~/.bashrc
echo "alias workoncv-$cvVersion=\"source $cwd/OpenCV-$cvVersion-py3/bin/activate\"" >> ~/.bashrc
source "$cwd"/OpenCV-"$cvVersion"-py3/bin/activate

# now install python libraries within this virtual environment
pip install wheel numpy scipy matplotlib scikit-image scikit-learn ipython dlib
 
# quit virtual environment
deactivate
Download Installation Script
To easily follow along this tutorial, please download installation script by clicking on the button below. It’s FREE!

Download Installation Script

Step 4: Download opencv and opencv_contrib

git clone https://github.com/opencv/opencv.git
cd opencv
git checkout $cvVersion
cd ..

git clone https://github.com/opencv/opencv_contrib.git
cd opencv_contrib
git checkout $cvVersion
cd ..

Step 5: Compile and install OpenCV with contrib modules

First we navigate to the build directory.

cd opencv
mkdir build
cd build

Next, we start the compilation and installation process.

cmake -D CMAKE_BUILD_TYPE=RELEASE \
            -D CMAKE_INSTALL_PREFIX=$cwd/installation/OpenCV-"$cvVersion" \
            -D INSTALL_C_EXAMPLES=ON \
            -D INSTALL_PYTHON_EXAMPLES=ON \
            -D WITH_TBB=ON \
            -D WITH_V4L=ON \
            -D OPENCV_PYTHON3_INSTALL_PATH=$cwd/OpenCV-$cvVersion-py3/lib/python3.5/site-packages \
        -D WITH_QT=ON \
        -D WITH_OPENGL=ON \
        -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
        -D BUILD_EXAMPLES=ON ..
For system wide installation of OpenCV, change CMAKE_INSTALL_PREFIX to CMAKE_INSTALL_PREFIX=/usr/local \.
make -j4
make install

2. How to use OpenCV in C++

Using CMakeLists.txt
The basic structure of your CMakeLists.txt will be as follows:

cmake_minimum_required(VERSION 3.1)
# Enable C++11
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)

You will have to set OpenCV_DIR as shown below.

SET(OpenCV_DIR <OpenCV_Home_Dir>/installation/OpenCV-master/lib/cmake/opencv4)

Make sure that you replace OpenCV_Home_Dir with correct path. For example, in my case:

SET(OpenCV_DIR /home/hp/OpenCV_installation/installation/OpenCV-master/lib/cmake/opencv4)

Once you have made your CMakeLists.txt, follow the steps given below.

mkdir build && cd build
cmake ..
cmake --build . --config Release

This will generate your executable file in build directory.

3. How to use OpenCV in Python

To use the OpenCV version installed using Python script, first we activate the correct Python Virtual Environment.

For OpenCV-4 : Python 3

workon OpenCV-master-py3

Once you have activated the virtual environment, you can enter Python shell and test OpenCV version.

ipython
import cv2
print(cv2.__version__)

Hope this script proves to be useful for you :). Stay tuned for more interesting stuff. In case of any queries, feel free to comment below and we will get back to you as soon as possible.

Subscribe & Download Code

If you liked this article and would like to download code (C++ and Python) and example images used in this post, please subscribe to our newsletter. You will also receive a free Computer Vision Resource Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.

Subscribe Now

Filed Under: Install, OpenCV 4 Tagged With: Install, OpenCV4, ubuntu

Comments

  1. Douglas Jones says

    September 17, 2018 at 9:45 am

    Satya,
    I have been looking for something like this! I will modify it as I compile all the Cuda in and I don’t need python 2.7.
    For a student working here I have been building OpenCV 3.4.1 with out Cuda or Python bindings, she is used to finding a opencv_world341d.dll (.lib) file and I do not get one. What am I missing>
    Thanks,
    Doug

    Reply
    • vishwesh shrimali says

      September 17, 2018 at 1:25 pm

      Hi Douglas! Thanks for the reply. In Windows systems, you have to make sure that OpenCV_DIR environment variable has been setup. Can you make sure that’s the case?

      Reply
      • Douglas Jones says

        September 18, 2018 at 6:20 am

        Hi Vishwesh,
        It wasn’t the environment variable, I just need to click the option to build the opencv_world3XX.dll file.

        Reply
        • vishwesh shrimali says

          September 18, 2018 at 6:22 am

          Hi Douglas!
          Does it work fine now?

          Reply
          • Douglas Jones says

            September 18, 2018 at 9:37 am

            I have opencvXXX_world.dll’s not so yes it is working.

  2. César Martínez says

    September 17, 2018 at 10:39 am

    Excellent! I tried the 3.4.1 version and installed OK! I’ll try now the Master version.
    Just a question: after completing the installation, I have this tree:
    /installOpenCV.sh
    installation
    opencv
    opencv_contrib

    Can I delete the ‘opencv’ folder? It occupies almost 8 Gb and don’t know if it is necessary.

    Many thanks, Satya

    Reply
    • vishwesh shrimali says

      September 17, 2018 at 1:27 pm

      Thank you Cesar! It’s great to see that the script was useful. Sure you can remove the opencv and opencv_contrib folders.

      Reply
  3. César Martínez says

    September 17, 2018 at 11:28 am

    Hi Satya, just an issue in the script: I’d like to have both OpenCV-3.4.1 and OpenCV-4 installed, as you say at the beginning, but the script deleted the ‘installation’ directory (line 9) when I ran the script for second time to install OpenCV 4. Then I managed to change the script a bit to have both versions installed.
    Bests,
    Cesar

    Reply
    • vishwesh shrimali says

      September 17, 2018 at 1:28 pm

      Hi Cesar! Thank you for pointing it out. I will make the corresponding change in the script.

      Update: I have removed the “rm -rf installation” line from the post as well as the script on github. Thanks!

      Reply
  4. Walid Aly says

    September 17, 2018 at 11:53 am

    Thanks. I executed the bash script and got the following errors

    make[2]: *** No rule to make target ‘/home/indusai/anaconda3/lib/libQt5Widgets.so.5.6.0’, needed by ‘lib/libopencv_cvv.so.4.0.0’. Stop.
    CMakeFiles/Makefile2:13459: recipe for target ‘modules/cvv/CMakeFiles/opencv_cvv.dir/all’ failed
    make[1]: *** [modules/cvv/CMakeFiles/opencv_cvv.dir/all] Error 2
    Makefile:160: recipe for target ‘all’ failed
    make: *** [all] Error 2

    I still find I have 3.3
    >>> import cv2
    >>> cv2.__version__
    ‘3.3.0’

    Can you please help?

    Walid

    Reply
    • vishwesh shrimali says

      September 17, 2018 at 1:22 pm

      Hi Walid! Can you please post the complete error? Also, try to run commands one by one from your command line directly as has been described in the post. That will help us in finding the error.

      Reply
  5. Masque du Furet says

    September 18, 2018 at 12:11 am

    There is something I do not understand:
    I compared the scripts with Adrian Rosebrook script https://www.pyimagesearch.com/2018/08/15/how-to-install-opencv-4-on-ubuntu/
    to install opencv-4 for python and noticed two things:

    a) your script is more complete, as it is meant to wotk with both c++ and python (which is a great idea: your publishing in both languages teaches/taught me a lot)
    b) pyimagesearch uses a very cryptic way (an hexa key) to select opencv4; you use a very simple keyword (“master”)
    And this is the later point (b) I do not understand. I guess pyimagesearch choses a given version of cv4, and you use the latest and {greatest|buggiest|debugged} one… But, as I use git as a black box, this is only a guess…

    Reply
    • vishwesh shrimali says

      September 18, 2018 at 1:41 am

      Hi Masque!

      The reason we are going with master is that it keeps on updating as and when the bugs are resolved or some new features are being added. Now, this also means that it is the least bugged but it also means that it can be highly unstable. Thankfully, the second one is not the case right now. As soon as OpenCV officially announces the OpenCV 4, we will revise the script to use that particular branch or commit.

      I am really glad to know that you appreciate the installation script.

      Happy hacking!
      Vishwesh

      Reply
      • Kaisar Khatak says

        October 14, 2018 at 6:21 pm

        pip install opencv-contrib-python==3.4.3 should also work though, right???

        Reply
        • Vikas Gupta says

          October 14, 2018 at 7:54 pm

          For the python-version – Yes! But there too, you cannot use the latest ( master ) branch. It will install the latest Release only.

          Moreover, these instructions are for those who want to
          1. install from source with their own modifications and
          2. For running both C++ and python code

          Reply
  6. Douglas Jones says

    September 24, 2018 at 2:35 pm

    In an effort to figure out why things are not working I am running line by line. I want to load OpenCV 3.4.3 and 4.0. i also do not use Python 2 so that section has been commented out. Since I already have virtualenv installed I have commented out that section.

    So in running line by line, when I execute line:
    sudo apt-get -y install libjpeg8-dev libjasper-dev libpng12-dev I get the following error:

    Reading package lists… Done
    Building dependency tree
    Reading state information… Done
    Package libpng12-dev is not available, but is referred to by another package.
    This may mean that the package is missing, has been obsoleted, or
    is only available from another source
    However the following packages replace it:
    libpng12-0

    E: Unable to locate package libjasper-dev
    E: Package ‘libpng12-dev’ has no installation candidate

    This is on Ubuntu 18.04 which I believe you used for you script.

    Suggestions?

    Thanks,
    Doug

    Reply
    • vishwesh shrimali says

      September 28, 2018 at 8:04 pm

      Hi Doug!

      You are right. You can checkout the blog for Ubuntu 18.04 installation for the same.

      https://www.learnopencv.com/install-opencv-4-on-ubuntu-18-04/

      Thanks

      Reply
  7. Rogers_mm says

    September 28, 2018 at 5:20 pm

    Thanks a lot for this tutorial. I follow all the instrutions, without any problem, but when applying workon … command, I get an error : ERROR: Environment ‘OpenCV-3.4.1-py3’ does not exist. Create it with ‘mkvirtualenv OpenCV-3.4.1-py3’.

    PLease, do you know how I can solve it?

    Thanks in advance for your response.

    Reply
    • vishwesh shrimali says

      September 28, 2018 at 8:03 pm

      Hi @Rogers_mm

      Can you provide the output of :

      lsvirtualenv -l

      Thanks

      Reply
  8. Jovann Pérez says

    October 6, 2018 at 12:45 pm

    Vishwesh,
    If I wanna install only for c++ and without the script, it would be done by only omitting python sections and following the post?

    Reply
    • vishwesh shrimali says

      October 6, 2018 at 2:23 pm

      Hi Jovann!
      Yes. Also make sure that you modify the cmake command:

      cmake -D CMAKE_BUILD_TYPE=RELEASE
      -D CMAKE_INSTALL_PREFIX=$cwd/installation/OpenCV-“$cvVersion”
      -D INSTALL_C_EXAMPLES=ON
      -D WITH_TBB=ON
      -D WITH_V4L=ON
      -D WITH_QT=ON
      -D WITH_OPENGL=ON
      -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules
      -D BUILD_EXAMPLES=ON ..

      There’s no need to create any environment or install any python module separately for only C++ installation.

      Reply
  9. Ritesh says

    November 2, 2018 at 9:55 pm

    thanks for script its works with opencv4 but when i install tensorflow on same virtual environment
    with pip install tensorflow installation is successful but when i call module it show error
    Illegal instruction (core dumped)
    can you help me with this?

    Reply
    • Ritesh says

      November 3, 2018 at 12:09 am

      hi i solved the issue i need to downgrade the my tensorflow 1.11 to tensorflow 1.5 and it works. for ubuntu 16.04

      Reply
  10. Konstantin says

    November 26, 2018 at 10:51 am

    Hello community,
    I installed everything following the guide but I have the problem that it cannot import cv2, as there is ‘no such module’. I tried in workon, that happened, I tried outside workon – it again happened. Weirdly enough iPython loads inside workon. It was compiling open-cv for around 40 minutes now and I am pretty sure it is successfully compiled on my computer but to some reason it just cannot be found. Can you help me to fix that because I am a bit to new to linking and cmaking etc.
    Besides that, can I use CUDA optimizations or TBB on opencv 4? Do they work with the Python version, if so, how can I activate them? Need to recompile again?

    Reply
    • Douglas R Jones says

      November 26, 2018 at 12:06 pm

      Konstantin,

      I use 18.04 but it should not make that much difference. If you want to use OpenCV 4 in Python then you must link the cv2*.so file into the virtual environment that you are using. You do not say what Python you are using or if you are using the installation folder that is called out in the article. So I will use my set up as an example.

      On my machine I have two hard drives. I mount my development drive, i.e. where I do all my coding, at /devel under that is a software folder that I use to hold any 3rd party software I use. I do use the installation folder that the scripts use but I do not run the scripts as I was bitten badly once upon a time. If you ran the make install command then you should find in the installation folder an OpenCV-4.0.0 folder. If you navigate to /installation/OpenCV-4.0.0/python/cv2/python-3.6 you will find the file cv2.cpython-36m-x86_64-linux-gnu.so (this assumes a Intel architecture). If this is all there then you can go to your virtual environment and link the file in. For me that is at ~/.virtualenvs/cv/lib/python3.6/site-packages. Then link the file using ln -f -s /devel/installation/OpenCV-4.0.0/python/python-3.6/cv2*.so cv2.so

      From there you should do a cd ~/

      workon cv

      python

      import cv2

      And everything should work.

      You can indeed compile for TBB and Cuda. Here is the cmake line I use:

      cmake -D CMAKE_BUILD_TYPE=Release
      -D CMAKE_INSTALL_PREFIX=$cwd/installation/OpenCV-“$cvVersion”
      -D INSTALL_C_EXAMPLES=OFF
      -D INSTALL_PYTHON_EXAMPLES=ON
      -D WITH_TBB=ON
      -D WITH_V4L=OFF
      -D WITH_QT=ON
      -D WITH_OPENGL=ON
      -D WITH_CUDA=ON
      -D BUILD_opencv_cudacodec=OFF
      -D OPENCV_EXTRA_MODULES_PATH=/devel/software/opencv_contrib/modules
      -D BUILD_EXAMPLES=OFF ..

      I hope this helps.

      Doug

      Reply
      • Konstantin says

        November 26, 2018 at 1:15 pm

        Doug,
        Thank you very much! Seconds ago I arrived to exactly the same solution! And it works. I am just really new to cmake and linking this way, I just get confused which file goes where while installation, which is linked, which not, where is the virtual environment, that kind of thing. In my case was exactly how you described it, I had python 3.6 and the sample was with python 3.5, so I just had to link the cython to the virtual environment.
        In order for me to compile opencv 4 with TBB and Cuda, do I have to uninstall it completely or it will just rewrite whatever I’ve currently?
        Another, last question I have is, can the python opencv 4 use these optimisations or it’s just for the c++? I am mainly interested whether I can use the Dense optical flow with Dense Inverse Search in python and wheather I will get anything out of TBB or it is exclusive to the C++ version of the library.
        OpenCV should really make a normal installer one day apart. Thank you so much for the extremely exhaustive answer, it was my case, I am sure you will help other people after me too with it!

        Reply
        • Douglas R Jones says

          November 26, 2018 at 2:33 pm

          Hi Konstantin,
          You are quite welcome! I am glad I could help. When ever I compile OpenCV, I always do a rm -rf * in the build folder. Then I know everything is “clean”. Form there the cmake then make.

          In general, Python does not use the Cuda optimizations in OpenCV, you will need to use C++ for that.

          As for a normal installer for OpenCV, not sure that will ever happen considering how many platforms the code is run on and ported to. I agree it would be nice but that would be a bunch of work.

          Dougf

          Reply
          • Konstantin says

            November 26, 2018 at 4:20 pm

            Thank you so much! Actually, the installed opencv comes with tbb. I don’t know if python uses it or not but from the first go I obtained 25-28fps compared to 15fps before running the same code. I may as well consider switching to C++ and recompiling with CUDA to see what further I can get out of it but even that for now is a miracle. Will give a go to the DIS as well! Thank you again Douglas!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Join Course

Computer Vision for Faces

Resources

Download Code (C++ / Python)

Disclaimer

This site is not affiliated with OpenCV.org

I am an entrepreneur with a love for Computer Vision and Machine Learning with a dozen years of experience (and a Ph.D.) in the field.

In 2007, right after finishing my Ph.D., I co-founded TAAZ Inc. with my advisor Dr. David Kriegman and Kevin Barnes. The scalability, and robustness of our computer vision and machine learning algorithms have been put to rigorous test by more than 100M users who have tried our products. Read More…

Recent Posts

  • Gender & Age Classification using OpenCV Deep Learning ( C++/Python )
  • Invisibility Cloak using Color Detection and Segmentation with OpenCV
  • Fast Image Downloader for Open Images V4
  • Deep Learning based Text Detection Using OpenCV (C++/Python)
  • Video Stabilization Using Point Feature Matching in OpenCV

Copyright © 2019 · Big Vision LLC