Building OpenCV on Ubuntu – with pyenv

Installing the OpenCV on Ubuntu can be really straight forward. Especially if you don’t want the latest version of python. However, if you’re into the “moving on tech-edge” and if you value the efforts behind software updates, you have probably installed the latest python using a version manager like pyenv.

The bad news is, if you have done so, the easy apt-get-ish way will not work for you; but the bright side is you can build it from source like a piece of cake.

On my journey towards the following solution, I found this gist by pohmelie and then this much better solution by him again. The only problem was, they’re cloning the old branch and cloning opencv’s main git repo will not yield the stable version.

I changed his solution a bit so that it will download that release source instead of cloning a repository and here’s the result:

Supposing, you have already installed pyenv and its prerequisites and also have enabled the latest python version (which is 3.7.4 as of now), first of all, install build dependencies for OpenCV and some PyPI packages (sh) required to run the installer script and use Opencv

sudo apt-get update
sudo apt-get build-dep opencv
sudo apt-get upgrade
pip install sh numpy scipy

Then edit OPEN_CV_VERSION to the latest available release and run this python file:

import pathlib
import sys
import sh

OPEN_CV_VERSION="4.1.0"


def download_sources_if_not_exist(version=OPEN_CV_VERSION):
    if not pathlib.Path("opencv.{}.src.tar.gz".format(version)).exists():
        print("Downloading opencv release v{0} from https://github.com/opencv/opencv/archive/{0}.tar.gz".format(version))
        sh.curl("https://github.com/opencv/opencv/archive/{}.tar.gz".format(version), "-L", "--output", "opencv.{}.src.tar.gz".format(version))
    if not pathlib.Path("opencv_contrib.{}.src.tar.gz".format(version)).exists():
        print("Downloading opencv_contrib release v{0} from https://github.com/opencv/opencv_contrib/archive/{0}.tar.gz".format(version))
        sh.curl("https://github.com/opencv/opencv_contrib/archive/{}.tar.gz".format(version), "-L", "--output", "opencv_contrib.{}.src.tar.gz".format(version))
    pass

def extract_sources_clean(version=OPEN_CV_VERSION):
    print("Refreshing opencv...")
    sh.rm("-rf", "opencv")
    sh.mkdir("opencv")
    sh.tar("xzf", "opencv.{}.src.tar.gz".format(version), "-C" ,"opencv", "--strip-components=1")
    print("Refreshing opencv_contrib...")
    sh.rm("-rf", "opencv_contrib")
    sh.mkdir("opencv_contrib")
    sh.tar("xzf", "opencv_contrib.{}.src.tar.gz".format(version), "-C" ,"opencv_contrib", "--strip-components=1")
    pass

def build_opencv():
    sh.pip.install("numpy")
    download_sources_if_not_exist()
    extract_sources_clean()
    sh.rm("-rf", "opencv-build")
    sh.mkdir("opencv-build")
    sh.cd("opencv-build")
    python_path = pathlib.Path(sh.pyenv.which("python").stdout.decode()).parent.parent
    version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
    sh.cmake(
        "../opencv",
        "-DCMAKE_BUILD_TYPE=RELEASE",
        "-DCMAKE_INSTALL_PREFIX={}/usr/local".format(python_path),
        "-DWITH_CUDA=OFF",
        "-DWITH_FFMPEG=OFF",
        "-DINSTALL_C_EXAMPLES=OFF",
        "-DBUILD_opencv_legacy=OFF",
        "-DBUILD_NEW_PYTHON_SUPPORT=ON",
        "-DBUILD_opencv_python3=ON",
        "-DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules",
        "-DBUILD_EXAMPLES=ON",
        "-DPYTHON_EXECUTABLE={}/bin/python".format(python_path),
        "-DPYTHON3_LIBRARY={}/lib/libpython{}m.so".format(python_path, version),
        "-DPYTHON3_PACKAGES_PATH={}/lib/python{}/site-packages/".format(python_path, version),
        "-DPYTHON3_NUMPY_INCLUDE_DIRS={}/lib/python{}/site-packages/numpy/core/include".format(python_path, version),
        "-DPYTHON_INCLUDE_DIR={}/include/python{}m".format(python_path, version),
        _out=sys.stdout,
    )
    sh.make("-j4", _out=sys.stdout)
    sh.make.install(_out=sys.stdout)


if __name__ == "__main__":
    build_opencv()

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>