Python 与相机入门指南
使用 Python 以及 C、C++ 和 C#,您可以完成所有必要的操作:
-
显示影像串流
-
采集单张图像,包含手动与自动模式
-
采集视频文件
-
设置所有相机属性
Windows:
安装方式:python3 -m pip install imagingcontrol4
驱动程序:适用于您 The Imaging Source 相机的 GenTL Producer,可从以下路径获取:https://www.theimagingsource.com/en-us/support/download/
说明文件: IC Imaging Control 4 Python Library
示例: https://github.com/TheImagingSource/ic4-examples/tree/master/python
单张图像抓取示例:
import imagingcontrol4 as ic4
ic4.Library.init()
# Create a Grabber object
grabber = ic4.Grabber()
# Open the first available video capture device
first_device_info = ic4.DeviceEnum.devices()[0]
grabber.device_open(first_device_info)
# Set the resolution to 640x480
grabber.device_property_map.set_value(ic4.PropId.WIDTH, 640)
grabber.device_property_map.set_value(ic4.PropId.HEIGHT, 480)
# Create a SnapSink. A SnapSink allows grabbing single images (or image sequences) out of a data stream.
sink = ic4.SnapSink()
# Setup data stream from the video capture device to the sink and start image acquisition.
grabber.stream_setup(sink, setup_option=ic4.StreamSetupOption.ACQUISITION_START)
try:
# Grab a single image out of the data stream.
image = sink.snap_single(1000)
# Print image information.
print(f"Received an image. ImageType: {image.image_type}")
# Save the image.
image.save_as_bmp("test.bmp")
except ic4.IC4Exception as ex:
print(ex.message)
# Stop the data stream.
grabber.stream_stop()
Linux:
安装方式:请前往 https://www.theimagingsource.com/en-us/support/download/ 的"SDKs"章节,下载适用于您 Linux 平台的
驱动程序:无需安装。
说明文件: tiscamera
示例: https://github.com/TheImagingSource/tiscamera/tree/master/examples/python 和 https://github.com/TheImagingSource/Linux-tiscamera-Programming-Samples/tree/master/python
单张图像抓取示例:
import time
import sys
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
def main():
Gst.init(sys.argv) # init gstreamer
serial = None
pipeline = Gst.parse_launch("tcambin name=bin "
" ! videoconvert"
" ! ximagesink sync=false")
# retrieve the bin element from the pipeline
camera = pipeline.get_by_name("bin")
# serial is defined, thus make the source open that device
if serial is not None:
camera.set_property("serial", serial)
pipeline.set_state(Gst.State.PLAYING)
print("Press Ctrl-C to stop.")
# We wait with this thread until a
# KeyboardInterrupt in the form of a Ctrl-C
# arrives. This will cause the pipline
# to be set to state NULL
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
pipeline.set_state(Gst.State.NULL)
if __name__ == "__main__":
main()
针对 Raspberry Pi 5 的补充信息(可能也适用于 Raspberry Pi 4):需安装的软件包:
sudo apt install python3-gi python3-gst-1.0
此外,也可以安装 OpenCV
sudo apt install python3-opencv
这显示了如何通过 apt 进行安装。使用 pip3 的操作方式也类似。不过,将 apt 和 pip3 的安装方式混用并非一个好主意。
如有进一步疑问,请使用我们的 contact form。