跳至內容
測試伺服器
開發伺服器

Python程式設計指南#

本主題提供有關 BaslerStereo mini 相機的特定資訊。其目的並非要對 Basler pylon 的官方 Python 語言綁定提供全面的概述。

Basler pylon 的官方 Python 語言綁定是pypylon專案。pypylon 是一個託管於 GitHub 的開源專案。若要使用 BaslerStereo mini 相機,您需要 26.04 版或更高版本。

如果您是初次接觸 pypylon,Basler 建議您先閱讀pypylon 文件,以熟悉 pypylon API。

先決條件#

  • Python 3.9 或更高版本
  • pypylon函式庫
  • NumPy函式庫
  • OpenCV函式庫
  • Open3D函式庫(可選,用於視覺化)

安裝與設定#

安裝 pypylon#

若要透過 Python 使用Stereo mini 上的相機,請安裝 pypylon 套件:

pip install pypylon

此套件為 pylon SDK 提供 Python 綁定函式。

針對提供的範例集,請在每個範例資料夾中安裝相關依賴項:

  • SimpleGrab/requirements.txt
  • ShowPointCloud/requirements.txt
  • LeftAndRightIntensity/requirements.txt

快速入門#

執行範例程式#

適用於Stereo mini 的 pylon 補充套件包含一些 Python 程式設計範例,用以說明如何透過 Python 和 pypylon 存取Stereo mini 相機。

The Python samples are located in the C:\Program Files\Basler\pylon\Development\Samples\Stereo_mini\Python folder.

The Python samples are located in the /opt/pylon/share/pylon/Samples/Stereo_mini/Python folder.

The Python samples are located in the /opt/pylon/share/pylon/Samples/Stereo_mini/Python folder.

資訊

在建置範例之前,請將包含範例的資料夾複製到您自選且具備寫入權限的位置。

要執行 Python 範例程式,請導航至包含該範例程式的資料夾,並使用 Python 執行它。範例:

python SimpleGrab.py

若在執行範例時遇到問題,請參閱「疑難排解」一節。

範例清單#

  • SimpleGrab:示範如何從Stereo mini 攝影機擷取影像,並存取色彩與深度資料。
  • ShowPointCloud:說明如何使用 Open3D 從Stereo mini 相機擷取點雲並進行視覺化呈現。
  • LeftAndRightIntensity:說明如何使用 OpenCV 顯示來自Stereo mini 攝影機的左右亮度流。

更多詳細資訊,請參閱Python範例目錄中的範例程式碼。

如何在Stereo mini 相機上使用 pypylon#

匯入所需的模組#

from pypylon import pylon

import numpy as np

連接至相機#

以下範例示範如何使用 pypylon 開啟第一個可用的Stereo mini 攝影機:

# Create Stereo mini filter to avoid opening a non-Stereo-mini device
di = pylon.DeviceInfo()
di.SetDeviceClass("BaslerGTC/Basler/Stereo_mini")

camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice(di))

print(f"Using camera: {camera.GetDeviceInfo().GetFriendlyName()}")

camera.Open()

若要開啟特定的Stereo mini 攝影機,請在建立攝影機之前設定其序號或自訂名稱:

# Open a specific Stereo mini camera by serial number
di.SetSerialNumber("12345678")

# Open a specific Stereo mini camera by user-defined name
di.SetUserDefinedName("MyStereoMini")

存取相機參數#

您可以透過 camera 物件,例如:

# Example parameter access
camera.ExposureTime.Value = 5000  # microseconds
camera.Gain.Value = 5.0

print(f"ExposureTime: {camera.ExposureTime.Value}")
print(f"Gain: {camera.Gain.Value}")

擷取影像#

以下範例示範如何從Stereo mini 攝影機擷取影像:

camera.StartGrabbing()

grab_result = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

if grab_result.GrabSucceeded():
    data_container = grab_result.GetDataContainer()
    print(f"Components: {data_container.DataComponentCount}")

grab_result.Release()

存取深度資料#

Stereo mini 相機同時提供亮度與距離兩項參數。範例中使用:

  • Coord3D_C16 適用於 16 位元範圍的數值
  • Coord3D_ABC32f 適用於直接的 XYZ 點資料
# Configure range format
camera.ComponentSelector.Value = "Range"
camera.PixelFormat.Value = "Coord3D_C16"