本教程将讲述如何获取左摄像头的图片,当获得50张图片时循环停止。
创建摄像头
创建并配置ZED摄像头,本教程将摄像头分辨率为H1080和帧速率30fps。
# Create a ZED camera object
zed = sl.Camera()
# Set configuration
parametersinit_params = sl.InitParameters()
init_params.camera_resolution = sl.RESOLUTION.HD1080 # Use HD1080 video mode
init_params.camera_fps = 30 # Set fps at 30
# Open the camera
err = zed.open(init_params)
if (err != sl.ERROR_CODE.SUCCESS) :
exit(-1)
获取摄像头数据
首先需要调用Camera.grab()函数,这个函数也需要一些参数,在本教程中使用默认的参数。如果想要获得并处理一张图片,就必须调用这个函数。这个函数的返回值是状态信息,可以通过该函数知道是否摄像头有新的帧或者发生了故障。
# Grab an image
if (zed.grab() == sl.ERROR_CODE.SUCCESS) :
# A new image is available
if grab() returns SUCCESS
接下来需要用到Camera.retrieve_image()
和 Camera.get_timestamp()
这两个函数来获取图片和获取图片的时间。
zed.retrieve_image(image,sl.VIEW.LEFT) # Get the left
imagetimestamp = zed.get_current_timestamp(sl.TIME_REFERENCE.IMAGE) # Get the timestamp of the image
print("Image resolution: ", image.get_width(), " x ", image.get_height()," || Image timestamp: ", timestamp.get_milliseconds())
retrieve_image()函数需要sl.Mat作为一个参数,同时也需要VIEW选项作为一个参数。在循环之前我们需要创建Mat类型。创建Mat类型时并不会分配内存,只有在调用retrieve_image()函数时才会分配内存。
# Capture 50 frames and stop
i = 0image = sl.Mat()
while (i < 50) :
# Grab an image
if (zed.grab() == sl.ERROR_CODE.SUCCESS) :
# A new image is available if grab() returns SUCCES
zed.retrieve_image(image, sl.VIEW.LEFT)
# Get the left image
timestamp = zed.get_timestamp(sl.TIME_REFERENCE.IMAGE)
# Get the timestamp at the time the image was captured
print("Image resolution: ", image.get_width(), " x ", image.get_height()," || Image timestamp: ", timestamp.get_milliseconds())
i = i+1
之后关闭摄像头即可。
# Close the camera
zed.close()return 0
示例代码
import pyzed.sl as sl
import cv2.cv2 as cv
def main():
zed = sl.Camera()
InitPara = sl.InitParameters()
InitPara.camera_fps = 30
InitPara.camera_resolution = sl.RESOLUTION.HD720
err = zed.open(InitPara)
if err != sl.ERROR_CODE.SUCCESS:
exit(-1)
left_img = sl.Mat()
runtimeParas = sl.RuntimeParameters()
while(True):
if zed.grab(runtimeParas) == sl.ERROR_CODE.SUCCESS:
zed.retrieve_image(left_img, view=sl.VIEW.LEFT)
time_stamp = zed.get_timestamp(sl.TIME_REFERENCE.CURRENT) print(time_stamp.get_milliseconds())
img = left_img.get_data()
cv.imshow("img", img)
cv.waitKey(5)
if __name__ == "__main__": main()