AgoraLive
AgoraLive

Reputation: 89

Python -> OpenCV -> save one image and end program

I have a RaspberryPi, a few IP camera's and I would like to get a fresh image from all these camera's every 5 minutes. I have the following script, which open the RTSP feed af grabs images ALL THE TIME, talking 10-25 every second it runs.

Is there a way to open the videofeed an take only 1 image?

import cv2
import time
cap = cv2.VideoCapture('rtsp://192.168.86.81:554/11') # it can be rtsp or http $

ret, frame = cap.read()
while ret:
    cv2.imwrite('images/{}.jpg'.format(time.time()), frame)
    ret, frame = cap.read()

Upvotes: 0

Views: 3493

Answers (2)

user13214870
user13214870

Reputation: 21

import cv2
import time
from datetime import datetime
import getpass

#imagesFolder = "C:/Users/<user>/documents"

# https://stackoverflow.com/questions/842059/is-there-a-portable-way-to-get-the-current-username-in-python
imagesFolder = "C:/Users/" + getpass.getuser() + "/documents"

#cap = cv2.VideoCapture("rtsp://192.168.86.81:554/11")

# Use public RTSP Streaming for testing, but I am getting black frames!
cap = cv2.VideoCapture("rtsp://192.168.86.81:554/11")
frameRate = cap.get(5) #frame rate
count = 0


while cap.isOpened():
    start_time = time.time()

    frameId = cap.get(1)  # current frame number
    ret, frame = cap.read()

    if (ret != True):
        break

    filename = imagesFolder + "/image_" + str(datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p"))  + ".jpg"
    cv2.imwrite(filename, frame)

    # Show frame for testing
    cv2.imshow('frame', frame)
    cv2.waitKey(1)

    count += 1

    #Break loop after 5*60 minus
    if count > 5*60:
        break

    elapsed_time = time.time() - start_time

    # Wait for 60 seconds (subtract elapsed_time in order to be accurate).
    time.sleep(60 - elapsed_time)


cap.release()
print ("Done!")

cv2.destroyAllWindows()

Upvotes: 0

AgoraLive
AgoraLive

Reputation: 89

This solved my problem. I removed time as I do not need this. I will let the aboce code stand in case anybody would want to play around with this

import cv2
cap = cv2.VideoCapture('rtsp://192.168.86.81:554/11') # it can be rtsp or http stream

ret, frame = cap.read()

if cap.isOpened():
    _,frame = cap.read()
    cap.release() #releasing camera immediately after capturing picture
    if _ and frame is not None:
        cv2.imwrite('images/latest.jpg', frame)

Upvotes: 0

Related Questions