杰瑞科技汇

如何在Linux上用Python配置OpenCV?

Of course! Here is a comprehensive guide to getting started with OpenCV in Python on a Linux system. This guide covers everything from installation to a simple "Hello, World!" example and troubleshooting common issues.

如何在Linux上用Python配置OpenCV?-图1
(图片来源网络,侵删)

Table of Contents

  1. Prerequisites: What you need before you start.
  2. Installation Methods: The recommended way and alternative methods.
  3. Verification: How to confirm OpenCV is installed correctly.
  4. Your First OpenCV Program: A simple image display script.
  5. Common Issues & Solutions: Troubleshooting problems like libGL.so errors.
  6. Next Steps: What to learn after the basics.

Prerequisites

Before you install OpenCV, make sure you have the following:

  • A Linux Distribution: This guide works for Ubuntu, Debian, Fedora, CentOS, Arch, and other popular distributions.
  • Python 3: OpenCV 4.x requires Python 3. You can check your Python version with:
    python3 --version
  • pip (Python Package Installer): This is the standard tool for installing Python packages. If you don't have it, you can install it easily.
    • On Debian/Ubuntu: sudo apt update && sudo apt install python3-pip
    • On Fedora/CentOS: sudo dnf install python3-pip
  • Build Essentials: Compiling OpenCV from source requires build tools. If you use the pre-built opencv-python wheel, you might not need all of these, but it's good to have them.
    • On Debian/Ubuntu: sudo apt install build-essential cmake git
    • On Fedora/CentOS: sudo dnf install cmake gcc-c++ git

Installation Methods

There are two primary ways to install OpenCV. For 99% of users, the first method is highly recommended.

Method 1: Using pip (Recommended - The Easy Way)

This method installs a pre-compiled "wheel" (*.whl), which is the fastest and simplest way. It handles all the dependencies for you.

The main package is opencv-python. However, it does not include non-free or patented algorithms (like SIFT, SURF). If you need these, you should install opencv-contrib-python instead.

如何在Linux上用Python配置OpenCV?-图2
(图片来源网络,侵删)

Step 1: Create a Virtual Environment (Best Practice)

It's highly recommended to use a virtual environment to keep your project dependencies isolated.

# Create a directory for your project
mkdir opencv_project
cd opencv_project
# Create a virtual environment named 'venv'
python3 -m venv venv
# Activate the virtual environment
source venv/bin/activate
# Your terminal prompt should now change to show (venv)

Step 2: Install OpenCV

Now, inside your activated virtual environment, install the package.

如何在Linux上用Python配置OpenCV?-图3
(图片来源网络,侵删)
# Install the core OpenCV package
pip install opencv-python
# --- OR ---
# Install OpenCV with extra modules (contrib) if you need SIFT, SURF, etc.
pip install opencv-contrib-python

Why choose one over the other?

  • opencv-python: Smaller download, faster install. Good for basic tasks.
  • opencv-contrib-python: Larger download, includes all algorithms. Use this if you plan on doing advanced computer vision.

Method 2: From Source (Advanced - For Customization)

You should only compile from source if you need specific features that are not in the pre-built wheels (e.g., custom video I/O backends, specific CPU optimizations, or a custom build without certain modules). It is complex and time-consuming.

# 1. Install all dependencies
# This is a comprehensive list for Ubuntu/Debian
sudo apt update
sudo apt install -y build-essential cmake git pkg-config libjpeg-dev libtiff5-dev libjasper-dev libpng-dev libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libgtk-3-dev libatlas-base-dev gfortran python3-dev
# 2. Clone the OpenCV repository
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
# 3. Create a build directory
cd opencv
mkdir build && cd build
# 4. Run CMake to configure the build
# You can add flags like -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
    -D BUILD_EXAMPLES=ON ..
# 5. Compile the code (this will take a long time, 30 mins to several hours)
# Use -j to specify the number of cores (e.g., -j4 for a 4-core CPU)
make -j4
# 6. Install the compiled libraries
sudo make install

Verification

After installation, the best way to verify is to run a simple Python script that imports the library.

  1. Make sure your virtual environment is still active (source venv/bin/activate).
  2. Open a Python interpreter or create a script file.
# In a Python shell or a .py file
import cv2
# Print the OpenCV version
print(f"OpenCV Version: {cv2.__version__}")

Run this script from your terminal:

python3 verify_opencv.py

If you see the OpenCV version printed (e.g., 8.1.78), congratulations! Your installation was successful.


Your First OpenCV Program: Display an Image

Let's create a simple script to read an image from your disk and display it in a window.

Step 1: Get a Sample Image Download any image and save it in your project directory. For this example, let's assume you save it as sample.jpg.

Step 2: Create the Python Script Create a file named display_image.py and add the following code:

import cv2
import sys
# Check if an image path was provided
if len(sys.argv) > 1:
    image_path = sys.argv[1]
else:
    # Default to sample.jpg if no argument is given
    image_path = "sample.jpg"
# Read the image from the file
# The function returns a NumPy array representing the image
image = cv2.imread(image_path)
# Check if the image was loaded successfully
if image is None:
    print(f"Error: Could not read the image from {image_path}")
    sys.exit(1)
# Create a window to display the image
# The 'cv2.WINDOW_AUTOSIZE' flag creates a window that fits the image size
cv2.namedWindow('Image Display', cv2.WINDOW_AUTOSIZE)
# Display the image in the created window
cv2.imshow('Image Display', image)
# Wait for a key press
# The '0' means it will wait indefinitely for any key to be pressed
cv2.waitKey(0)
# Close all OpenCV windows
cv2.destroyAllWindows()
print("Image display finished.")

Step 3: Run the Script Make sure you have an image in your directory (e.g., sample.jpg).

# Run the script, passing the image path as an argument
python3 display_image.py sample.jpg

A window should pop up showing your image. Press any key to close it and end the script.


Common Issues & Solutions

Issue: libGL.so.1: cannot open shared object file

This is a very common error, especially on headless servers (without a graphical display) or in Docker containers. It happens because OpenCV tries to use GUI functions by default.

Solution 1: Install Missing Libraries (If you have a display)

sudo apt-get update
sudo apt-get install -y libgl1-mesa-glx libglib2.0-0

Solution 2: Run in a Headless Environment (Recommended for servers) You can tell OpenCV to use a "headless" backend that doesn't require a display. Set an environment variable before running your Python script.

# For Bash/Zsh
export DISPLAY=:0
# Or use a non-GUI backend
export OPENCV_HEADLESS=1
# Now run your script
python3 display_image.py sample.jpg

Alternatively, you can modify your script to use the headless backend if you know it will run on a server:

import os
os.environ['OPENCV_HEADLESS'] = '1'
import cv2
# ... rest of your code

Issue: ModuleNotFoundError: No module named 'cv2'

This usually means the installation failed or you are trying to run the script outside of the virtual environment where you installed it.

Solution:

  1. Make sure your virtual environment is activated. Your terminal prompt should show (venv).
  2. Double-check that the installation command ran without errors. Try reinstalling:
    pip uninstall opencv-python
    pip install opencv-python

Next Steps

Now that you have a working OpenCV environment, here's what you can explore next:

  • Read Video Files/Webcams: Use cv2.VideoCapture() to process video streams.
  • Image Processing: Learn about basic operations like color conversion (cv2.cvtColor()), resizing (cv2.resize()), and blurring (cv2.GaussianBlur()).
  • Feature Detection: Try out corner detection (Harris, Shi-Tomasi), edge detection (Canny), and feature descriptors (SIFT, ORB).
  • Object Detection: Use pre-trained models like Haar Cascades or deep learning models (e.g., YOLO) for detecting objects in images and videos.
  • Camera Calibration: Learn to calibrate your camera to remove lens distortion.
  • OpenCV Documentation: The official OpenCV-Python Tutorials are an excellent free resource.
分享:
扫描分享到社交APP
上一篇
下一篇