Of course! Here is a comprehensive guide on how to set up and use Python with OpenCV on a CentOS system. This guide covers everything from installation to creating your first application.

We'll focus on CentOS 7 and CentOS 8/Stream, as they are the most common versions.
Overview of the Process
- Prerequisites: Install essential development tools like Python,
pip, and a C++ compiler. - Install OpenCV: We'll cover two main methods:
- Method 1 (Recommended for Beginners): Install via
pip. This is the fastest and easiest way to get started. - Method 2 (Recommended for Production/Advanced Users): Build from source. This gives you full control over features and optimizations.
- Method 1 (Recommended for Beginners): Install via
- Verify Installation: Run a simple Python script to confirm everything is working.
- Create a Sample Application: A basic "Hello, OpenCV!" script that loads an image and displays it.
- Troubleshooting: Common issues and their solutions.
Step 1: Prerequisites (Essential for Both Methods)
First, you need to ensure your system has the necessary development tools. OpenCV has many dependencies, and these tools are required to build and install them correctly.
For CentOS 7
Open a terminal and run the following commands:
# Update all packages sudo yum update -y # Install Development Tools (gcc, g++, make, etc.) sudo yum groupinstall "Development Tools" -y # Install Python 3, pip, and other development libraries sudo yum install python3 python3-pip python3-devel -y # Install image and video I/O libraries sudo yum install gtk2-devel libjpeg-turbo-devel libpng-devel libtiff-devel -y # Install video codec support (optional but highly recommended) sudo yum install ffmpeg ffmpeg-devel -y
For CentOS 8 / CentOS Stream
The commands are very similar, but yum has been replaced by dnf.

# Update all packages sudo dnf update -y # Install Development Tools sudo dnf groupinstall "Development Tools" -y # Install Python 3, pip, and other development libraries sudo dnf install python3 python3-pip python3-devel -y # Install image and video I/O libraries sudo dnf install gtk3-devel libjpeg-turbo-devel libpng-devel libtiff-devel -y # Install video codec support (optional but highly recommended) sudo dnf install ffmpeg ffmpeg-devel -y
Step 2: Install OpenCV
Choose the method that best fits your needs.
Method 1: Install via pip (Easiest)
This method downloads a pre-compiled binary wheel and is the fastest way to get a working OpenCV installation.
# It's good practice to upgrade pip first python3 -m pip install --upgrade pip # Install the main OpenCV package python3 -m pip install opencv-python # (Optional) Install additional contrib modules (contains extra algorithms) # This can significantly increase the installation size. python3 -m pip install opencv-contrib-python
Pros:
- Extremely fast and easy.
- Handles dependencies automatically.
Cons:

- You cannot customize the build (e.g., enable/disable specific modules like
DNN,G-API, etc.). - May not be optimized for your specific CPU.
Method 2: Build from Source (Recommended for Production)
This method gives you full control, allowing you to enable specific optimizations (like Intel's IPP or TBB) and modules. It's the standard for deploying applications in production.
Install Dependencies
You'll need more libraries to build OpenCV from source. The exact names can vary slightly.
For CentOS 7:
sudo yum install cmake gtk2-devel numpy python3-devel libjpeg-turbo-devel libpng-devel libtiff-devel libdc1394-devel tbb-devel eigen3-devel ffmpeg-devel -y
For CentOS 8 / CentOS Stream:
sudo dnf install cmake gtk3-devel numpy python3-devel libjpeg-turbo-devel libpng-devel libtiff-devel libdc1394-devel tbb-devel eigen3-devel ffmpeg-devel -y
Download OpenCV Source Code
We'll use the git command to clone the latest stable release (4.x) from the official repository.
# Install git if you don't have it sudo yum install git -y # For CentOS 7 sudo dnf install git -y # For CentOS 8/Stream # Create a directory for the source code mkdir ~/opencv_build cd ~/opencv_build # Clone the OpenCV repository git clone https://github.com/opencv/opencv.git git clone https://github.com/opencv/opencv_contrib.git # Let's say we want to build OpenCV 4.5.5 cd opencv git checkout 4.5.5 cd ../opencv_contrib git checkout 4.5.5 cd ../opencv
Create a Build Directory and Configure with CMake
It's a best practice to build in a separate directory to keep the source tree clean.
cd ~/opencv_build/opencv
# Create the build directory
mkdir build
cd build
# Run CMake to configure the build
# The -D flags enable/disable features
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-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 ..
Explanation of Key CMake Flags:
CMAKE_BUILD_TYPE=RELEASE: Builds an optimized version, not a debug one.CMAKE_INSTALL_PREFIX=/usr/local: Where OpenCV will be installed.OPENCV_EXTRA_MODULES_PATH: Crucial! This tells CMake where to find theopencv_contribmodules.WITH_TBB=ON: Enables Intel Threading Building Blocks for better parallelism.WITH_V4L=ON: Enables Video4Linux for capturing video from webcams.
Compile and Install
This step will take some time, from 15 minutes to over an hour, depending on your CPU speed.
# Use all available CPU cores to speed up compilation (replace -j8 with -j$(nproc)) # -j$(nproc) is a dynamic way to get the number of cores make -j$(nproc) # Install the compiled files sudo make install
Step 3: Verify the Installation
Now, let's check if Python can find and use the OpenCV library.
# Open a Python 3 interpreter python3
Inside the Python interpreter, run the following commands:
import cv2
# Print the OpenCV version
print("OpenCV Version:", cv2.__version__)
# This should print the path to the OpenCV module
# If you built from source, it will likely be in /usr/lib/python3.x/site-packages/
print("OpenCV Path:", cv2.__file__)
# Exit the interpreter
exit()
If you see the OpenCV version printed without any errors, your installation was successful!
Step 4: Create a Sample Application
Let's create a simple script to load and display an image.
-
Find an image or download one. Let's use a sample image from the internet. Save the following as
test_image.py:import cv2 import sys # Check if an image path was provided if len(sys.argv) > 1: image_path = sys.argv[1] else: # Download a sample image if none is provided import urllib.request image_url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/lena.jpg" image_path = "lena.jpg" print(f"Downloading sample image to {image_path}...") urllib.request.urlretrieve(image_url, image_path) print("Download complete.") # Read the image # cv2.IMREAD_COLOR loads the image in BGR format image = cv2.imread(image_path, cv2.IMREAD_COLOR) # Check if the image was loaded successfully if image is None: print(f"Error: Could not read image from {image_path}") sys.exit(1) # Display the image in a window cv2.imshow('Image Window', image) # Wait for a key press to close the window # The '0' means wait indefinitely for any key print("Press any key in the image window to exit...") cv2.waitKey(0) # Close all OpenCV windows cv2.destroyAllWindows() print("Program finished.") -
Run the script from your terminal:
# If you have an image named 'my_photo.jpg' in the same directory: # python3 test_image.py my_photo.jpg # If you don't have an image, it will download the 'lena.jpg' sample python3 test_image.py
A window should appear showing the image. Press any key to close it.
Step 5: Troubleshooting
Problem: ModuleNotFoundError: No module named 'cv2'
- Cause: The Python interpreter cannot find the
cv2module. This is common if you have multiple Python versions or if thecv2.solibrary is not in the correct path. - Solutions:
- Ensure you are using
python3, notpython, which might point to an older Python 2. - If you installed with
pip, the path should be correct. Try reinstalling:python3 -m pip uninstall opencv-python && python3 -m pip install opencv-python. - If you built from source, the
cv2.sofile is typically in/usr/local/lib/python3.x/site-packages/. Check that this path is in yourPYTHONPATHor that you are using the correctpython3executable that has this path in its search list.
- Ensure you are using
Problem: ImportError: libGL.so.1: cannot open shared file
-
Cause: A missing graphics library. This happens when you try to run a GUI application (like
cv2.imshow()) on a headless server (without a display) or if the necessary OpenGL libraries are not installed. -
Solutions:
-
On a headless server, you don't need the GUI. You can disable it during the build. Re-run
cmakewith the flag-D WITH_OPENGL=OFFandmake installagain. -
If you need it on a desktop, install the missing library:
# For CentOS 7 sudo yum install mesa-libGL # For CentOS 8 / Stream sudo dnf install mesa-libGL
-
Problem: ImportError: libippi.so.7.0: cannot open shared file
- Cause: A missing Intel Integrated Performance Primitives (IPP) library. This can happen if you built OpenCV with IPP support (
-D ENABLE_IPP=ON) but the IPP runtime libraries are not installed on the system. - Solution: This is complex. The easiest fix is often to rebuild OpenCV without IPP support. Modify your
cmakecommand to remove any IPP-related flags and rebuild.
