Repository navigation
Expand file tree
/
Copy pathbase_data.py
More file actions
329 lines (284 loc) · 13.3 KB
/
Copy pathbase_data.py
File metadata and controls
329 lines (284 loc) · 13.3 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import cv2
import mediapipe as mp
import numpy as np
import time
from screeninfo import get_monitors
from enum import Enum
from collections import deque
from math import acos
from numpy import dot, linalg, clip, arccos, degrees, pi, sqrt
from numba import jit
from copy import deepcopy
import keyword
from 捕获四角并拉伸 import *
from 本地软件打开图片 import *
import glob
import os
import pyperclip
double_eye=0#是否双目(否则是一个RGB一个IR红外)
init_take_photo_all_white=0
need_top=True#不需要顶部,只要正面
need_dpt = 0 # 是否使用深度(包括双目计算出来的深度,如果不要,就失去单指点击功能)
need_action = 1 # 是否要正式执行order,可以只识别不改变鼠标等状态
show_dpt_pic = 1 # 显示深度窗口
show_pic = 1 # 显示深度窗口
click_time = 0.4 # 单次点击所需的时间
smooth_landmark=0.95#对新坐标的信任程度
histroy_time = 3 # 多少连续帧认为是真的切换了
if double_eye:
dpt_w, dpt_h = 640, 400 # 深度图的分辨率#单眼
baseline_mm = 65 # 双目相机的基线
else:
dpt_w, dpt_h = 640, 480 # 深度图的分辨率
baseline_mm = 25 # 双目相机的基线
# 深度相机相关(双目是另一种)
mean_dpt = 630 # 623 # 桌面的平均深度mm,初始化的时候校准获取,用来计算深度图平移距离
dpt_gate = -30 # 600 # 大于这个深度,代表食指按下
dpt_gate_per = 0.3 # 按下的深度点占检测方框的比例
dpt_read_range = 50 # 识别半径
hand_thick = 13 # 整个手的厚度,用来检测手按在桌面后的深度(手会微微隆起,,不可能一直按在桌面上)
hand_point_num = 21 # 单手有几个点
allow_cross_window_order = ['grasp', 'mouse'] # 允许跨页的命令有哪些()
four_xy_mode=['photo','resize']#4个坐标,需要reshape的模式名字
icon_width = 150 # 工具箱图标宽度
all_pic_name=['ruler','pan','eraser','keyboard','single_pan','single_eraser','reco_fun']#加载的图标名字(png)
########################################################
########################################################
########################################################
########################################################
with np.load(f'kxmxkymy.npz', allow_pickle=True) as data:
kxmxkymy = data['matrix']
M_stretch = np.load('M_stretch.npy')
src_pts = np.load('src_pts.npy')
dst_pts = np.load('dst_pts.npy')
##########################################################
##########################################################
##########################################################
##########################################################
##########################################################
##########################################################
##########################################################
##########################################################
##########################################################
if need_dpt:
if not double_eye:
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))#腐蚀膨胀去噪的卷积核大小
kernel = np.ones((10, 10), np.uint8) # 腐蚀膨胀去噪的卷积核大小
else:
"""加载标定结果并显示使用示例"""
# 查找最新的标定文件
npz_files = glob.glob("stereo_calibration_*.npz") # 直接读取标定好的矩阵,前缀是stereo_calibration_就行,后面任意匹配日期
latest_file = max(npz_files, key=os.path.getctime)
print(f"加载标定文件: {latest_file}")
data = np.load(latest_file, allow_pickle=True)
print("\n加载的参数:")
print("=" * 40)
# 显示关键参数
print(f"左相机内参矩阵 K1:")
print(data['K1'])
print(f"\n左相机畸变系数 D1:")
print(data['D1'])
print(f"\n右相机内参矩阵 K2:")
print(data['K2'])
print(f"\n右相机畸变系数 D2:")
print(data['D2'])
print(f"\n旋转矩阵 R:")
print(data['R'])
print(f"\n平移向量 T:")
# load_and_use_calibration()
# 左相机内参
# left_camera_matrix = np.array([[416.841180253704, 0.0, 338.485167779639],
# [0., 416.465934495134, 230.419201769346],
# [0., 0., 1.]])
left_camera_matrix = data['K1']
# 左相机畸变系数:[k1, k2, p1, p2, k3]
# left_distortion = np.array([[-0.0170280933781798, 0.0643596519467521, -0.00161785356900972, -0.00330684695473645, 0]])
left_distortion = data['D1']
# 右相机内参
# right_camera_matrix = np.array([[417.765094485395, 0.0, 315.061245379892],
# [0., 417.845058291483, 238.181766936442],
# [0., 0., 1.]])
right_camera_matrix = data['K2']
# 右相机畸变系数:[k1, k2, p1, p2, k3]
# right_distortion = np.array([[-0.0394089328586398, 0.131112076868352, -0.00133793245429668, -0.00188957913931929, 0]])
right_distortion = data['D2']
# 旋转矩阵
# R = np.array([[0.999962872853149, 0.00187779299260463, -0.00840992323112715],
# [ -0.0018408858041373, 0.999988651353238, 0.00439412154902114],
# [ 0.00841807904053251, -0.00437847669953504, 0.999954981430194]])
R = data['R']
# 平移向量
# T = np.array([[-120.326603502087], [0.199732192805711], [-0.203594457929446]])
T = data['T']
# 图像尺寸
size = tuple(data['image_size'])
imageWidth = size[0] # 640
imageHeight = size[1] # 400
# 立体校正
R1, R2, P1, P2, Q, validPixROI1, validPixROI2 = cv2.stereoRectify(left_camera_matrix, left_distortion,
right_camera_matrix, right_distortion, size,
R, T)
# 校正查找映射表
left_map1, left_map2 = cv2.initUndistortRectifyMap(left_camera_matrix, left_distortion, R1, P1, size,
cv2.CV_16SC2)
right_map1, right_map2 = cv2.initUndistortRectifyMap(right_camera_matrix, right_distortion, R2, P2, size,
cv2.CV_16SC2)
blockSize = 8
img_channels = 3
stereo = cv2.StereoSGBM_create(minDisparity=1,
numDisparities=64,
blockSize=blockSize,
P1=8 * img_channels * blockSize * blockSize,
P2=32 * img_channels * blockSize * blockSize,
disp12MaxDiff=-1,
preFilterCap=140,
uniquenessRatio=1,
speckleWindowSize=100,
speckleRange=100,
mode=cv2.STEREO_SGBM_MODE_HH)
def get_monitor_layout():
"""获取显示器布局,确定主副屏关系"""
monitors = get_monitors()
# 主屏是坐标原点 (0, 0) 的显示器
primary = None
secondary = None
for monitor in monitors:
if monitor.x == 0 and monitor.y == 0:
primary = monitor
else:
secondary = monitor
if primary is None and len(monitors) > 0:
primary = monitors[0]
return primary, secondary
def get_monitor_info():
"""自动获取显示器信息"""
monitors = get_monitors()
print("检测到的显示器:")
for i, monitor in enumerate(monitors):
print(f" 显示器 {i + 1}: {monitor.width}x{monitor.height} "
f"位置: ({monitor.x}, {monitor.y})")
return monitors
get_monitor_info()
#获取主副屏
primary, secondary = get_monitor_layout()
if primary:
print(f"\n主屏: {primary.width}x{primary.height}")
if secondary:
print(f"副屏: {secondary.width}x{secondary.height} 偏移: ({secondary.x}, {secondary.y})")
side_table_w, side_table_h = secondary.width, secondary.height # 桌面分辨率
# side_table_w, side_table_h = 2880, 1620 # 桌面分辨率
# side_table_w, side_table_h = 2560, 1600 # 桌面分辨率
main_table_w, main_table_h = primary.width, primary.height # 桌面分辨率
pianyi=np.array([-side_table_w, 0])
if need_top:
now_cam = 'top' # 开始使用的相机
else:
now_cam = 'front' # 开始使用的相机
# if need_front:
cap_f = cv2.VideoCapture(0) # 前置摄像头
cap_f.set(cv2.CAP_PROP_FRAME_WIDTH, dpt_w)
cap_f.set(cv2.CAP_PROP_FRAME_HEIGHT, dpt_h)
ret, frame = cap_f.read()
if need_top:
cap = cv2.VideoCapture(1) # 俯视角
cap.set(cv2.CAP_PROP_FRAME_WIDTH, dpt_w)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, dpt_w*2)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, dpt_h)
cap.set(cv2.CAP_PROP_FPS, 25)
# cap.set(cv2.CAP_PROP_BRIGHTNESS, 130) # 亮度 130
# cap.set(cv2.CAP_PROP_CONTRAST, 32) # 对比度 32
cap.set(cv2.CAP_PROP_SATURATION, 64) # 饱和度 64
# cap.set(cv2.CAP_PROP_HUE, 0) # 色调 0
cap.set(cv2.CAP_PROP_BRIGHTNESS, 0.5)
cap.set(cv2.CAP_PROP_CONTRAST, 0.8)
# cap.set(cv2.CAP_PROP_AUTO_WB, 100)
# cap.set(cv2.CAP_PROP_AUTO_WB, 60)
# 自动曝光设置为“手动模式”或关闭,具体值因驱动而异
# cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.033) # 通常0.25表示手动模式,1.0表示自动模式
cap.set(cv2.CAP_PROP_EXPOSURE, 3) # 曝光 -4
# cap.set(cv2.CAP_PROP_EXPOSURE, 0.001)
# cap.set(cv2.CAP_PROP_FPS, 30)
print('FPS', cap.get(cv2.CAP_PROP_FPS))
# 然后尝试设置一个具体的曝光值,这个值需要不断试验
# 较小的值 = 曝光时间短,画面暗;较大的值 = 曝光时间长,画面亮
# cap.set(cv2.CAP_PROP_EXPOSURE, 10) # 这个值没有标准,从-10到10都试试
# cap.set(cv2.CAP_PROP_BRIGHTNESS, 0.5)
ret, frame = cap.read()
discard_area = np.array([[side_table_w - 300, side_table_h - 200], [side_table_w, side_table_h]]) # 垃圾桶区域,抓取状态下到达这个区域弹出垃圾桶
tool_out_gate = dpt_w // 2 # 水平移动多远才允许呼出收回工具箱
tool_kit_pos = {
'ruler': [icon_width, side_table_h - 200],
'pan': [3*icon_width, side_table_h - 200],
'eraser': [5 * icon_width, side_table_h - 200],
'keyboard': [7 * icon_width, side_table_h - 200],
'reco_fun': [9 * icon_width, side_table_h - 200],
} # 工具栏图标的位置
cam_h, cam_w = frame.shape[:2]
cam_size = np.array([cam_w, cam_h])
dpt_size = np.array([dpt_w, dpt_h])
side_table_size = np.array([side_table_w, side_table_h])
main_table_size = np.array([main_table_w, main_table_h])
print('相机分辨率', frame.shape)
print('深度相机分辨率', dpt_size)
print('丢弃区域大小', discard_area)
mode_type = {
'mode': 'NO_HAND',
'wrist_xy': np.array([100, side_table_h+100]),
'table_xy': np.array([100, side_table_h+100]),
'thumb_xy': np.array([100, side_table_h+100]),
'enable': False,
}
if need_dpt and not double_eye:
hand_dpt_gate = mean_dpt - hand_thick
class HandGesture(Enum):
"""定义手势类型"""
UNKNOWN = 0 # 有手,但是不知道什么手势
PISTOL = 1 # 手枪手势(最难识别)
PISTOL_OVER = 2 # 手枪激发姿势(大拇指扣在食指上)
TWO_FINGERS = 3 # 食指中指并拢(较难)
TWO_FINGERS_SPLIT = 4 # 食指中指分开(较难)
HAND_CLOSED = 5 # 合拢成拳(中等)
HAND_OPEN = 6 # 五指张开(中等)
GOOD = 7 # 大拇指横向划动
POINT_DOWN = 8 # 食指点击(较易)
POINT_UP = 9 # 抬起
PINCHR = 10 # 中指点击(较易)
PINCHR_OUT = 11 # 右键抬起
PINCH = 12 # 食指大拇指捏起(易)
PINCH_OUT = 13 # 食指大拇指放下(易)
NO_HAND = 14 # 无手
THAND=15#T型手势,用来暂停执行(不影响识别)
if 0:
pixel_size = 0.003 # mm
focal_length_px = 280 * pixel_size * mean_dpt / A4_w # 595 # focal_length_px = (物理焦距_f_mm * 图像宽度_px) / 传感器宽度_mm 或者focal_length_px = 物理焦距_f_mm / 像素尺寸_mm_per_pixel
print('focal_length_px', focal_length_px)
disparity_px = focal_length_px * baseline_mm / mean_dpt # 平移距离
print('平移距离', disparity_px)
M_move = np.float32([
[1, 0, disparity_px], # 水平平移
[0, 1, 0] # 垂直不变
])
else:
# M_move = np.float32([
# [1, 0, 20], # 水平平移
# [0, 1, 3] # 垂直不变
# ])
M_move = np.float32([
[1, 0, 50], # 水平平移
[0, 1, -30] # 垂直不变
])
def load_dict(json_name='config_table.json'):
with open(json_name, "r", encoding="utf-8") as f:
data_dict = json.load(f) # 读取前200个字符
print(data_dict, type(data_dict))
return data_dict
data_dict=load_dict('config_table.json')
mean_dpt=data_dict['mean_dpt']
# dpt_gate = mean_dpt-30
# if __name__ == "__main__":
# if need_dpt:
# from 深度图读取 import *
# from 边缘获取中心位置 import *
# init_dpt_and_A4()
# data_dict=load_dict('config_table.json')
# mean_dpt=data_dict['mean_dpt']