![]() |
VOOZH | about |
OpenCV (Open Source Computer Vision Library) is a powerful tool for image processing and computer vision tasks. Often, we may need to customize the OpenCV installation using CMake to include specific modules or optimizations. This guide will walk us through the process of building OpenCV from the source using CMake and installing it into the Python virtual environment.
First, create a virtual environment where we will install OpenCV.
python -m venv opencv-envActivate the virtual environment:
On Windows:
opencv-env\Scripts\activateOn macOS/Linux:
source opencv-env/bin/activateInstall the required dependencies for the building OpenCV.
On Ubuntu/Debian:
sudo apt update
sudo apt install -y build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
On macOS (using Homebrew):
brew install cmake pkg-config
brew install jpeg libpng libtiff openexr
brew install eigen tbb
Clone the OpenCV repositories from the GitHub.
git clone https://github.com/opencv/opencv
git clone https://github.com/opencv/opencv_contrib
Create a build directory and navigate into it:
mkdir -p opencv/build
cd opencv/build
Configure the build with CMake:
cmake -D CMAKE_BUILD_TYPE=Release \
-D CMAKE_INSTALL_PREFIX=$(python -c "import sys; print(sys.prefix)") \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
-D PYTHON_EXECUTABLE=$(which python) \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D BUILD_EXAMPLES=ON ..
This configuration specifies that OpenCV will be built in Release mode with the installation path set to the virtual environment's prefix. It also includes the extra modules from opencv_contrib repository.
Compile OpenCV using make. Adjust the -j flag according to the number of the CPU cores we want to use:
make -j$(nproc)After the build process completes install OpenCV:
make installTo verify that OpenCV is correctly installed in the virtual environment open a Python shell and import OpenCV:
import cv2
print(cv2.__version__)
we should see the version number of the installed OpenCV package.
By following these steps we have successfully built and installed OpenCV with the custom CMake options in the Python virtual environment. This setup allows to utilize the full power of the OpenCV with the specific modules and optimizations we need for the projects.