Python独習!

習得したPython知識をペイフォワード

PythonでBASLERカメラのエミュレーターを設定する

basler-python-pypylon
Source of photo: https://github.com/basler/pypylon As of Sep 22, 2021

概要

システム環境変数に"PYLON_CAMEMU=1"と設定してあげると、カメラエミュレーションが有効になり、実際にカメラがPCに接続されていなくてもpypylonで作ったスクリプトを動かくすことができる。
Camera Emulation | Basler Product Documentation

しかし、システム環境変数をその都度書き換えるのは面倒だし、誤って他の変数を書き換えてしまう恐れもある。もっと手軽にカメラエミュレーションを有効にする方法がある。
その方法は、次の1行をスクリプトに入れるだけ。

os.environ["PYLON_CAMEMU"] = "1"

※実際にOSのシステム環境変数を書き換えるわけではなく、このスクリプトの中でだけ効果がある、らしい

サンプルプログラム

結果

エミュレーションが有効になっていると、おなじみの縞々が表示される。
basler-python-pypylon

ソースコード

1行目と8行目以外は、GitHubから引用している。
Source of script: https://github.com/basler/pypylon/blob/master/samples/guiimagewindow.py As of Sep 22, 2021

import os
import time

from pypylon import pylon
from pypylon import genicam


os.environ["PYLON_CAMEMU"] = "1"

try:
    imageWindow = pylon.PylonImageWindow()
    imageWindow.Create(1)

    # Create an instant camera object with the camera device found first.
    camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())

    # Print the model name of the camera.
    print("Using device ", camera.GetDeviceInfo().GetModelName())

    # Start the grabbing of c_countOfImagesToGrab images.
    # The camera device is parameterized with a default configuration which
    # sets up free-running continuous acquisition.
    camera.StartGrabbingMax(10000, pylon.GrabStrategy_LatestImageOnly)

    while camera.IsGrabbing():
        # Wait for an image and then retrieve it. A timeout of 5000 ms is used.
        grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

        # Image grabbed successfully?
        if grabResult.GrabSucceeded():
            imageWindow.SetImage(grabResult)
            imageWindow.Show()
        else:
            print("Error: ",
                  grabResult.ErrorCode)  # grabResult.ErrorDescription does not work properly in python could throw UnicodeDecodeError
        grabResult.Release()
        time.sleep(0.05)

        if not imageWindow.IsVisible():
            camera.StopGrabbing()

    # camera has to be closed manually
    camera.Close()
    # imageWindow has to be closed manually
    imageWindow.Close()

except genicam.GenericException as e:
    # Error handling.
    print("An exception occurred.")
    print(e.GetDescription())
/* -----codeの行番号----- */