前言

该程序为外接英特尔深度相机拍照测试和视频录制测试程序

一、拍照程序

  1. 按下s键表示保存图片
  2. 按下q键表示退出程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# coding:utf-8
import cv2

cap = cv2.VideoCapture(1, cv2.CAP_DSHOW)
flag = cap.isOpened()
index = 1
while (flag):
ret, frame = cap.read()
cv2.imshow("Capture_Paizhao", frame)
k = cv2.waitKey(1) & 0xFF
if k == ord('s'): # 按下s键,进入下面的保存图片操作
cv2.imwrite(r"D:\Desktop\calibration-images/" + str(index) + ".png", frame)
print("save" + str(index) + ".jpg successfuly!")
print("-------------------------")
index += 1
elif k == ord('q'): # 按下q键,程序退出
break
cap.release() # 释放摄像头
cv2.destroyAllWindows()# 释放并销毁窗口

二、录制视频程序

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
# coding:utf-8
import cv2
import os
import time

# 打开摄像头
cap = cv2.VideoCapture(1, cv2.CAP_DSHOW)
if not cap.isOpened():
print("Error: Unable to access the camera.")
exit()

# 视频保存设置
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 使用 mp4v 编解码器
fps = 20.0 # 设置帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # 获取摄像头宽度
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 获取摄像头高度

# 确保输出目录存在
output_dir = r"D:\Desktop\calibration-videos"
if not os.path.exists(output_dir):
print(f"Output directory does not exist: {output_dir}")
os.makedirs(output_dir)

# 使用时间戳生成唯一文件名
timestamp = time.strftime("%Y%m%d_%H%M%S")
output_file = os.path.join(output_dir, f"video_{timestamp}.mp4")

# 创建视频写入器
video_writer = cv2.VideoWriter(output_file, fourcc, fps, (width, height))

print(f"Recording started. The video will be saved as {output_file}. Press 'q' to quit.")

while True:
ret, frame = cap.read()
if not ret:
print("Error: Unable to read frame.")
break

# 显示捕获的图像
cv2.imshow("Capture_Paizhao", frame)

# 写入视频文件
video_writer.write(frame)

k = cv2.waitKey(1) & 0xFF
if k == ord('q'): # 按下q键退出程序
break

# 释放资源
cap.release()
video_writer.release()
cv2.destroyAllWindows()