Does the zed camera always save a picture instead of a video when it opens the video and writes the video file?

When I use the following program to open the camera and read the program, the video stream cannot be saved, and the object saved is a picture. May I ask what the problem is, thank you

import cv2
import pyzed.sl as sl

zed = sl.Camera()
init_params = sl.InitParameters()
init_params.depth_mode = sl.DEPTH_MODE.PERFORMANCE
init_params.coordinate_units = sl.UNIT.METER
init_params.camera_resolution = sl.RESOLUTION.HD720
init_params.camera_fps = 30

# open camera
err = zed.open(init_params)
if err != sl.ERROR_CODE.SUCCESS:
    exit(1)

image = sl.Mat()

while True:
    zed.grab()
    zed.retrieve_image(image, sl.VIEW.LEFT)
    view = image.get_data()  # 从mat 转换成numpy数组了
    img0 = view[:, :, 0:3]
    cv2.imshow("hello", img0)
    cv2.waitKey(1)
    fps, w, h = 10, img0.shape[1], img0.shape[0]
    vid_writer = cv2.VideoWriter('outpy.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
    vid_writer.write(img0)

vid_writer.release()
cv2.destroyAllWindows()

Hi @zhangYQHBAU

I think you’re creating your video writer at each iteration of the loop. :wink:
Get the constructor out and just use vid_writer.write(img0).
Please let me know if it fixed it!

After the two structures are pulled out according to what you said, it is still not possible to save the video, and the result of saving is a picture

vid_writer = cv2.VideoWriter('outpy.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer.write(img0)

@zhangYQHBAU

The constructor is just the first of these two lines, the other (the method to write) should remain in the loop.
Something like this:

[...]

image = sl.Mat()
vid_writer = cv2.VideoWriter('outpy.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))

while True:
    zed.grab()
    zed.retrieve_image(image, sl.VIEW.LEFT)
    view = image.get_data()  # 从mat 转换成numpy数组了
    img0 = view[:, :, 0:3]
    cv2.imshow("hello", img0)
    cv2.waitKey(1)
    fps, w, h = 10, img0.shape[1], img0.shape[0]
    vid_writer.write(img0)

[...]

I have done just like you said, But it didn’t work

Hey @zhangYQHBAU

Did you get any error messages?
I managed to run your code with a few modifications.
I think what was happening is that you could not end the loop properly with the while True:, so you should either use a frame counter instead of looping forever, or use a key to finish the capture like this.

So:

  1. Initialize cv2.VideoWriter : vid_writer = cv2.VideoWriter('outpy.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  2. Either:
    a. loop with a counter : while frame_counter < desired_frames :
    b. loop with while True:, but at the end of the loop (inside the loop), listen to a key from the cv2 window to quit cleanly (q in this example).
    if k == ord('q'):
        break

Then you will arrive at vid_writer.release() properly and you should have a video.

If it still doesn’t work, please include error messages.