baoshiwei
2024-03-04 e595c312581496403ac182f12f3d4939d3d00998
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import cv2
import time
 
# 摄像头索引号,通常为0表示第一个摄像头
camera_index = 0
 
# 打开摄像头
cap = cv2.VideoCapture(camera_index)
 
# 检查摄像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
 
# 图片保存路径
save_path = "captured_images/"
 
# 检查保存路径是否存在,如果不存在则创建
import os
 
if not os.path.exists(save_path):
    os.makedirs(save_path)
 
# 目标图像尺寸
target_width = 640
target_height = 480
 
# 计时器
start_time = time.time()
 
# 循环读取摄像头画面
while True:
    ret, frame = cap.read()
 
    if not ret:
        print("无法读取摄像头画面")
        break
 
    # 调整图像尺寸
    resized_frame = cv2.resize(frame, (target_width, target_height))
 
    # 获取当前时间
    current_time = time.time()
 
    # 如果距离上一次保存已经过去1秒,则保存当前画面
    if current_time - start_time >= 1.0:
        # 生成保存文件名,以当前时间命名
        save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
        # 保存调整尺寸后的图片
        cv2.imwrite(save_path + save_name, resized_frame)
        print("保存图片:", save_name)
        # 重置计时器
        start_time = time.time()
 
    # 显示画面
    cv2.imshow("Camera", resized_frame)
 
    # 检测按键,如果按下q键则退出循环
    if cv2.waitKey(1000) & 0xFF == ord('q'):
        break
 
# 关闭摄像头
cap.release()
 
# 关闭所有窗口
cv2.destroyAllWindows()