杰瑞科技汇

Centos下Python OpenCV如何安装配置?

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.

Centos下Python OpenCV如何安装配置?-图1
(图片来源网络,侵删)

We'll focus on CentOS 7 and CentOS 8/Stream, as they are the most common versions.


Overview of the Process

  1. Prerequisites: Install essential development tools like Python, pip, and a C++ compiler.
  2. 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.
  3. Verify Installation: Run a simple Python script to confirm everything is working.
  4. Create a Sample Application: A basic "Hello, OpenCV!" script that loads an image and displays it.
  5. 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.

Centos下Python OpenCV如何安装配置?-图2
(图片来源网络,侵删)
# 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:

Centos下Python OpenCV如何安装配置?-图3
(图片来源网络,侵删)
  • 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 the opencv_contrib modules.
  • 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.

  1. 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.")
  2. 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 cv2 module. This is common if you have multiple Python versions or if the cv2.so library is not in the correct path.
  • Solutions:
    1. Ensure you are using python3, not python, which might point to an older Python 2.
    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.
    3. If you built from source, the cv2.so file is typically in /usr/local/lib/python3.x/site-packages/. Check that this path is in your PYTHONPATH or that you are using the correct python3 executable that has this path in its search list.

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:

    1. On a headless server, you don't need the GUI. You can disable it during the build. Re-run cmake with the flag -D WITH_OPENGL=OFF and make install again.

    2. 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 cmake command to remove any IPP-related flags and rebuild.
分享:
扫描分享到社交APP
上一篇
下一篇