使用 python 写一个程序,调用电脑摄像头每隔 5 秒拍照一次存储到本地

import cv2
import time
import os
import datetime
print("start")
# 设置摄像头编号,一般为0或1
camera_id = 0
# 设置保存图片的路径
save_path = "capture/"
if not os.path.exists(save_path):
    os.mkdir(save_path)
# 创建VideoCapture对象
cap = cv2.VideoCapture(camera_id)
print(cap)

# 检查摄像头是否打开
if not cap.isOpened():
    print("Unable to open camera")
    exit(1)

# 设置循环抓拍
while True:
    # 捕获一帧图像
    ret, frame = cap.read()

    # 如果图像捕获失败,退出循环
    if not ret:
        print("Unable to capture frame")
        break

    # 生成文件名
    # timestamp = int(time.time())
    date = datetime.datetime.today().strftime("%Y%m%d")
    date_path = save_path + date + "/"
    if not os.path.exists(date_path):
        os.mkdir(date_path)

    date_time = datetime.datetime.today().strftime("%H%M%S")
    filename = date_path + str(date_time) + ".jpg"

    print(filename)
    # 保存图像到本地
    cv2.imwrite(filename, frame)

    # 等待10秒
    time.sleep(5)

# 释放资源
cap.release()

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注