Python-> OpenCV->保存一张图片并结束程序

问题描述 投票:0回答:2

我有一个RaspberryPi,还有几个IP摄像机,我希望每5分钟从所有这些摄像机中获取一个新鲜的图像。我有以下脚本,它将打开RTSP提要,并始终抓取图像,每秒运行10-25秒钟。

是否有办法打开视频源仅拍摄一张图像?

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()
python opencv rtsp
2个回答
0
投票

这解决了我的问题。我删除了时间,因为我不需要这个。如果有人想玩这个,我将保留详细的代码

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)

0
投票
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()
© www.soinside.com 2019 - 2024. All rights reserved.