baoshiwei
2025-04-15 776a127b8db01cd4338f4db2a84ea567a65bff9f
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
67
68
69
70
71
72
73
import cv2
import time
 
# 摄像头索引号,通常为0表示第一个摄像头
camera_index = 0
 
# 打开摄像头
cap = cv2.VideoCapture(camera_index)
# 设置分辨率
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # 宽度
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # 高度
# 检查摄像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
 
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("摄像头分辨率:", width, "x", height)
# 图片保存路径
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
 
# 裁剪图像
#     cropped_frame = frame[750:1230, 1650:2290]
    # 调整图像尺寸
    resized_frame = cv2.resize(frame, (target_width, target_height))
 
    # 获取当前时间
    current_time = time.time()
 
    #如果距离上一次保存已经过去1秒,则保存当前画面
    # if current_time - start_time >= 3.0:
    #     # 生成保存文件名,以当前时间命名
    #     save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
    #     # 保存调整尺寸后的图片
    #     cv2.imwrite(save_path + save_name, frame)
    #     print("保存图片:", save_name)
    #     # 重置计时器
    #     start_time = time.time()
 
    # 显示画面
    cv2.imshow("Camera", frame)
 
    # 检测按键,如果按下q键则退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# 关闭摄像头
cap.release()
 
# 关闭所有窗口
cv2.destroyAllWindows()