0

I'm trying to use python to capture a photo from my ip cameras every 1 minute and save it as a file for later use. I'm still not good at python and I don't get why some of the times I get the right image and sometimes I get a corrupted gray image. I'm using hikvision api to get the rtsp stream and while the stream is working sometimes the images are still fully gray. Here is the code I wrote:

import cv2
import time

count = 0
while True:
    for x in range(1, 9):
        count = count +1
        RTSP_URL = f'rtsp://user:password@ip:port/ISAPI/Streaming/Channels/{x}01'
        cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG)
        result, image = cap.read()
        if result:
            cv2.imwrite(f"pictures/{x}{count}.png", image)
        time.sleep(60)

I would be happy to hear suggestions to find the best way to do this task.

9
  • Are you getting corrupted images if you remove time.sleep(60)? For testing, you may add cv2.imshow('image', image) and cv2.waitKey(1) for showing the video. Commented Aug 1, 2022 at 16:51
  • @Rotem thanks for commenting, after changing that it still shows the gray images and sometimes working images. what's interesting is that when I try to make it a substream(a lower quality option offered by the API) it works without corrupted images. Commented Aug 1, 2022 at 17:15
  • No I see... you are reading from 8 different streams. Try adding cap.release() after result, image = cap.read(). That way you are going to close and reopen the connection every minute. I don't think we can use new cap = cv2.VideoCapture without executing cap.release(). In case you want to hold 8 RTSP connections open, use a list of 8 cap objects. Open the 8 cap objects before the while True, and use cap[x-1].read(). Make sure that the CPU load is not too high. Commented Aug 1, 2022 at 20:03
  • @Rotem thanks again for helping me! After trying both ideas It looks like the situation doesn't change. Perhaps it's the problem with the API? Here is a link for the corrupted image I get imgur.com/pmZloii Commented Aug 2, 2022 at 8:49
  • try this github.com/Cacsjep/pyrtsputils/blob/main/snapshot_generator.py Commented Sep 13, 2022 at 11:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.