使用Python OpenCV進行即時距離估計


Python 和 OpenCV 徹底改變了計算機視覺領域,使開發人員和研究人員能夠探索廣泛的應用。憑藉其簡潔性、多功能性和廣泛的庫支援,Python 已成為包括計算機視覺在內的各個領域的流行程式語言。作為 Python 功能的補充,OpenCV(開源計算機視覺庫)提供了一個強大的影像和影片處理工具包,使其成為實現計算機視覺演算法的首選。

在本文中,我們將指導您完成設定開發環境、捕獲即時影片饋送、校準攝像頭以及使用 OpenCV 實現目標檢測和跟蹤技術的流程。然後,我們將探索各種距離計算方法,包括三角測量,並展示如何無縫整合這些技術以即時估計物體之間的距離。在文章的下一部分,我們將介紹相機校準的基礎知識及其在距離估計中的意義。

使用Python OpenCV進行即時距離估計

首先,我們需要安裝 OpenCV 及其依賴項。

安裝 Python:如果您尚未安裝 Python,請訪問官方 Python 網站 (python.org) 並下載與您的作業系統相容的最新版本。

安裝 OpenCV:可以使用 pip 等包管理器安裝 OpenCV。開啟您的終端或命令提示符並執行以下命令:

pip install opencv-python

此命令將下載並安裝 Python 的 OpenCV 包。

安裝其他庫:除了 OpenCV 之外,我們還將為此專案使用其他 Python 庫。透過執行以下 pip 命令來安裝它們:

pip install numpy
pip install matplotlib

NumPy 是一個強大的數值計算庫,而 Matplotlib 可用於視覺化資料和顯示影像。

透過使用 OpenCV 訪問攝像頭饋送來捕獲即時影片

為了執行即時距離估計,我們首先需要使用 OpenCV 訪問攝像頭饋送。幸運的是,OpenCV 提供了直接的功能來完成此任務。在本教程中,我們將使用 `VideoCapture` 類,它允許我們從攝像頭捕獲影片幀。

這是一個演示如何訪問攝像頭饋送的程式碼片段示例:

import cv2

# Create a VideoCapture object
cap = cv2.VideoCapture(0)

# Check if the camera is opened successfully
if not cap.isOpened():
    print("Failed to open the camera")
    exit()

# Read and display frames from the camera
while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to read frame from the camera")
        break

    # Display the frame
    cv2.imshow("Camera Feed", frame)

    # Break the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the VideoCapture object and close the windows
cap.release()
cv2.destroyAllWindows()

在上面的程式碼中,我們已經訪問了影片攝像頭的饋送。現在讓我們瞭解如何跟蹤物體。

OpenCV 中的目標檢測和跟蹤

目標檢測是計算機視覺中的一項關鍵任務,它涉及定位和分類影像或影片流中的物體。OpenCV 提供了幾種目標檢測演算法,包括 Haar 級聯和定向梯度直方圖 (HOG)。

Haar 級聯:Haar 級聯是經過訓練的分類器,它們根據特定的視覺特徵(例如邊緣、角點和紋理模式)來檢測物體。這些分類器使用一系列用正負樣本訓練的弱分類器來逐步縮小目標物體的搜尋範圍。

HOG(定向梯度直方圖):HOG 是一種特徵描述符,它捕獲區域性物體的外觀和形狀資訊。它透過計算和分析影像中梯度方向的分佈來工作。

在本教程中,我們將重點介紹使用 OpenCV 的基於 Haar 級聯的目標檢測方法。這是一個演示影片流中目標檢測和跟蹤的程式碼片段示例:

import cv2

# Load the pre-trained Haar cascade classifier
cascade_path = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)

# Access the camera feed
cap = cv2.VideoCapture(0)

while True:
    # Read a frame from the camera
    ret, frame = cap.read()
    if not ret:
        print("Failed to read frame from the camera")
        break

    # Convert the frame to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the grayscale frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # Draw rectangles around the detected faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow("Object Detection", frame)

    # Break the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the VideoCapture object and close the windows
cap.release()
cv2.destroyAllWindows()

在上面的程式碼中,我們首先使用 OpenCV 提供的 `CascadeClassifier` 類載入用於人臉檢測的 Haar 級聯分類器。您可以嘗試使用不同的預訓練 Haar 級聯和引數來檢測其他物體或提高檢測精度。

使用三角測量進行距離計算

三角測量是一種廣泛使用的基於幾何和透視原理的距離估計方法。三角測量涉及使用視差和已知的幾何關係來計算距離。

OpenCV 提供了輕鬆實現三角測量演算法的功能和工具。這是一個演示使用 OpenCV 進行立體三角測量的程式碼片段示例:

import cv2
import numpy as np

# Load the camera calibration parameters
camera_matrix_1 = np.load("camera_matrix_1.npy")
dist_coeff_1 = np.load("dist_coeff_1.npy")
camera_matrix_2 = np.load("camera_matrix_2.npy")
dist_coeff_2 = np.load("dist_coeff_2.npy")
R = np.load("rotation_matrix.npy")
T = np.load("translation_vector.npy")

# Load the corresponding image points in each view
image_points_1 = np.load("image_points_1.npy")
image_points_2 = np.load("image_points_2.npy")

# Perform stereo triangulation
points_4d = cv2.triangulatePoints(camera_matrix_1, camera_matrix_2, image_points_1, image_points_2)

# Convert 4D homogeneous coordinates to 3D Cartesian coordinates
points_3d = cv2.convertPointsFromHomogeneous(points_4d.T)

# Extract the X, Y, and Z coordinates
x = points_3d[:, 0, 0]
y = points_3d[:, 0, 1]
z = points_3d[:, 0, 2]

# Calculate the distances
distances = np.sqrt(x**2 + y**2 + z**2)

# Print the calculated distances
for i, distance in enumerate(distances):
    print(f"Point {i+1} distance: {distance}")

在上面的程式碼中,我們已經實現了用於距離計算的三角測量演算法。透過使用 OpenCV 實現這些三角測量演算法,我們可以準確地估計即時應用中的距離。

即時距離估計

現在我們已經介紹了目標檢測、相機校準和距離計算的各個組成部分,是時候將所有內容整合在一起,建立一個完整的即時距離估計系統了。

我們的即時距離估計應用程式的程式碼實現將如下所示:

import cv2
import numpy as np

# Load the camera calibration parameters
camera_matrix_1 = np.load("camera_matrix_1.npy")
dist_coeff_1 = np.load("dist_coeff_1.npy")
camera_matrix_2 = np.load("camera_matrix_2.npy")
dist_coeff_2 = np.load("dist_coeff_2.npy")
R = np.load("rotation_matrix.npy")
T = np.load("translation_vector.npy")

# Load the pre-trained Haar cascade classifier
cascade_path = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)

# Access the camera feed
cap = cv2.VideoCapture(0)

while True:
    # Read a frame from the camera
    ret, frame = cap.read()
    if not ret:
        print("Failed to read frame from the camera")
        break

    # Convert the frame to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the grayscale frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    for (x, y, w, h) in faces:
        # Calculate the 2D image points for triangulation
        image_points_1 = np.array([[x, y+h/2]], dtype=np.float32)
        image_points_2 = np.array([[x+w, y+h/2]], dtype=np.float32)

        # Perform stereo triangulation
        points_4d = cv2.triangulatePoints(camera_matrix_1, camera_matrix_2, image_points_1, image_points_2)

        # Convert 4D homogeneous coordinates to 3D Cartesian coordinates
        points_3d = cv2.convertPointsFromHomogeneous(points_4d.T)

        # Extract the X, Y, and Z coordinates
        x = points_3d[0, 0, 0]
        y = points_3d[0, 0, 1]
        z = points_3d[0, 0, 2]

        # Calculate the distance
        distance = np.sqrt(x**2 + y**2 + z**2)

        # Draw a bounding box and display the distance on the frame
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame, f"Distance: {distance:.2f} units", (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow("Real-time Distance Estimation", frame)

    # Break the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the capture and close the windows
cap.release()
cv2.destroyAllWindows()

在上面的程式碼中,我們已經成功地使用 Python 和 OpenCV 實現了一個即時距離估計應用程式。

結論

在本教程中,我們學習瞭如何使用 Python 和 OpenCV 執行即時距離估計。透過結合目標檢測、跟蹤和三角測量技術,我們建立了一個完整的系統,用於即時估計物體之間的距離。使用提供的程式碼示例,您現在可以探索機器人技術、增強現實和安全系統等各個領域的應用。享受探索計算機視覺的激動人心的可能性!

更新於: 2023年7月25日

2K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告