You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改pypylon代码实现彩色图像采集?及参数疑问

解决方案

一、彩色图像采集的代码修改

要实现彩色采集,核心是调整相机的PixelFormat参数,让输出为彩色格式。以下是对原代码的小幅调整:

# minimal capture image and show on screen in PIL format
import pypylon.pylon as py
from PIL import Image
import numpy as np

tlf = py.TlFactory.GetInstance()
devices = tlf.EnumerateDevices()  # 补全设备枚举步骤,原代码遗漏此句会报错
camera = py.InstantCamera(tlf.CreateDevice(devices[0]))

camera.Open()
# 新增:设置相机输出彩色格式,RGB8可直接兼容PIL
camera.PixelFormat = "RGB8"

camera.StartGrabbing(1)
grab = camera.RetrieveResult(2000, py.TimeoutHandling_Return)
if grab.GrabSucceeded():
    img = grab.GetArray()  # 此时numpy数组形状为 (高度, 宽度, 3)
    print(f'Size of image: {img.shape}')
    image = Image.fromarray(img)
    image.show() 
camera.Close()

修改说明:

  • 补全devices = tlf.EnumerateDevices():原代码直接使用devices[0]但未定义,会导致运行报错。
  • 添加camera.PixelFormat = "RGB8":将相机输出格式设为RGB8(每个像素3字节,红、绿、蓝顺序),此格式可直接被Image.fromarray()识别转换为PIL图像。
  • 如果相机不支持RGB8,可尝试BGR8(多数工业相机默认彩色格式),此时需额外转换通道顺序:
    img = grab.GetArray()
    img = np.flip(img, axis=2)  # 将BGR转为RGB
    

二、RetrieveResult方法中2000参数的作用

RetrieveResult(2000, py.TimeoutHandling_Return)中的2000是超时时间,单位为毫秒:

  • 表示程序会等待最多2000毫秒来获取相机抓取的图像帧。
  • 如果在2000毫秒内成功获取到图像,就返回对应的抓取结果对象;如果超时,会按照第二个参数py.TimeoutHandling_Return的规则处理——直接返回一个抓取结果对象,需通过grab.GrabSucceeded()判断是否抓取成功。

内容的提问来源于stack exchange,提问作者Joymaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:35:17