-
Notifications
You must be signed in to change notification settings - Fork 0
/
cvtools.py
1748 lines (1551 loc) · 72.9 KB
/
cvtools.py
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 13:39:13 2020
@author: tycoer
"""
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
import cv2.aruco as aruco
import tkinter as tk
from tkinter import filedialog
from scipy.spatial.transform import Rotation as rot
from scipy import signal,linalg
import open3d as o3d
import json
import socket
import h5py
from sklearn.cluster import MeanShift, estimate_bandwidth
class cvtools:
'''
根据ylb习惯, 对函数中变量名做出如下约定(cvtools下凡出现以下变量名,均遵循且仅遵循以下描述):
uv:像素坐标(u为横坐标,v为纵坐标)
xyz:世界坐标(待补充), 命名上:z = depth, 函数名中采用'depth', 参数采用'z'
HW:图像尺寸(H为高,W为宽)
hw:长度(h为高,w为宽)
vh,vw:为像素长度,宽度
xh,yw:点云长度,宽度
path: 附带文件名的路径 , 例'./data/test.txt'
dir:文件夹名,例 './data'
name: 文件名, 例 'test.txt'
img:单张图片
imgs:tuple或list形式存在的多张图片
函数名前缀说明:
aruco相关: aruco
手眼标定相关: handeye
算法相关:alg
相机标定相关: camcalib
点云相关:pc
测量相关:measure
其余未有前缀之函数, 原因为ylb未想好命名或功能不多-不足以形成前缀
tips:
1.numpy中对图像描述采用[v,u],即第一个值为列,第二个值为行
opencv中对图像描述采用[u,v],即第一个值为行,第二个值为列
故函数中经常出现 ::-1 的表达, 将[u,v]转成[v,u]
2.
'''
def aruco_createDict(self,dict_name):
'''
生成aruco字典, 对应的字典名将决定带有aruco前缀函数的作用
例: 若对该函数传入dict_name='4x4', 则对于一张图中存在同时4x4,6x6的图片,aruco_centroid函数将只识别4x4的marker
Parameters
----------
dict_name : str 字典名
DESCRIPTION.支持输入'4x4','5x5','6x6','7x7',默认字典长度为250的aruco字典
Returns
-------
aruco_dict : obj, 输出的字典
DESCRIPTION.
'''
if dict_name=='4x4':
aruco_dict=3
elif dict_name=='5x5':
aruco_dict=7
elif dict_name=='6x6':
aruco_dict=11
elif dict_name=='7x7':
aruco_dict=15
aruco_dict=aruco.Dictionary_get(aruco_dict)
return aruco_dict
def aruco_createBoard(self,aruco_dict,size=0.03,shape=(6,7),firstMarker=0,border=10):
'''
生成aruco板
Parameters
----------
aruco_dict :obj aruco字典, 参见函数aruco_createDict
DESCRIPTION.
size : float, optional, 每个aruco的实际边长,单位为m
DESCRIPTION. The default is 0.03.
shape : tuple, optional,板的行列数
DESCRIPTION. The default is (6,7).
firstMarker : 首个aruco序号, optional
DESCRIPTION. The default is 0. 例: firstMarker=7 则aruco板会从ids=7的marker开始生成,(这里单个aruco被称为marker)
border : int, 每个marker的边界的像素长度
DESCRIPTION. The default is 10.
Returns
-------
board : array(uint8),生成的板子
DESCRIPTION.
'''
border=int(border)
row,col,size_real=shape[0],shape[1],size*1000*3.74
board=aruco.GridBoard_create(row,col,size_real,border,aruco_dict,firstMarker)
row_px,col_px=int(size_real*row+border*(row+1)),int(size_real*col+border*(col+1))
board=board.draw((row_px,col_px),marginSize = border)
return board
def aruco_createMarker(self,aruco_dict,ids=0,size=0.05,shape=(1,1),border=5,save_dir='./marker'):
'''
生成单个aruco
Parameters
----------
aruco_dict : obj,参见函数aruco_createDict
DESCRIPTION.
ids : int, optional, marker的ids
DESCRIPTION. The default is 0.
size : float, optional, marker的实际边长,单位为m
DESCRIPTION. The default is 0.05.
shape : tuple, optional, marker板的行列数
DESCRIPTION. The default is (1,1). 生成具有相同ids的marker板
border : int, optional, 边界像素长度
DESCRIPTION. The default is 5.
Returns
-------
marker : array(uint8) 生成的marker
DESCRIPTION.
'''
# 生成一个marker, 必须用a4纸打印,用其他规格的纸计算结果会出错.
# 第三个参数为生成marker的像素尺寸单位为px,对于a4纸, 1mm=3.78px, 故若想在a4纸上打印实际50mm*50mm的marker, 则marker的像素长度为size*1000*3.78, 其中size的单位为m
border=int(border)
marker=aruco.drawMarker(aruco_dict,ids,int(size*1000*3.78)) # 生成单个
marker=cv2.copyMakeBorder(marker,border,border,border,border,cv2.BORDER_CONSTANT,value=255) # 填充边界
marker=np.tile(marker,shape) # 根据num生成多个
marker_size=aruco_dict.markerSize
if os.path.exists(save_dir)==False:
os.mkdir(save_dir)
name=str(ids)+'_'+str(marker_size)+'x'+str(marker_size)+'x'+str(size),'m'+'.jpg'
path=os.path.join(save_dir, name)
cv2.imwrite(path,marker)
return marker
def aruco_centroid(self,img,aruco_dict,draw=False):
'''
提取图片中所有marker的中心点
Parameters
----------
img : array(uint8), 输入图片
DESCRIPTION. 需为单张图片
aruco_dict : obj,参见函数aruco_createDict
DESCRIPTION.
draw : bool, optional,是否绘制marker
DESCRIPTION. The default is False. 直接绘制原图, 谨慎使用
Returns
-------
centroid : tuple, 中心点元组, 元组长度由图中的marker数量决定
DESCRIPTION.
ids : tuple, ids元组
DESCRIPTION.
'''
corners, ids, _ = aruco.detectMarkers(img, aruco_dict)
centroid=tuple([np.int32([sum(i[0][:,1])*0.25, sum(i[0][:,0])*0.25]) for i in corners])
if draw==True and ids is not None:
aruco.drawDetectedMarkers(img,corners,ids)
return centroid,ids
def aruco_pose(self,aruco_dict,img,cam_matrix,dist_coeff,size=0.05,draw=False):
'''
图片中marker的姿态
Parameters
----------
aruco_dict : obj,参见函数aruco_createDict
DESCRIPTION.
img : array, 输入图片
DESCRIPTION.
cam_matrix : array, 相机内参矩阵
DESCRIPTION.
dist_coeff : array, 相机畸变系数
DESCRIPTION.
size : float, optional, 实际marker的边长,单位为m
DESCRIPTION. The default is 0.05.
draw : bool, optional, 绘制marker的姿态
DESCRIPTION. The default is False. 直接绘制原图, 谨慎使用
Returns
-------
rvec : list, marker的旋转矢量
DESCRIPTION.
tvec : list, marker的平移矢量
DESCRIPTION.
ids : list, marker的ids
DESCRIPTION.
'''
corners, ids, _ = aruco.detectMarkers(img, aruco_dict)
#rvec 为旋转向量,不随markerlength变化,单位为rad,而非欧拉角.tvec为平移向量,随markerlength变化,单位为m.markerlength为实际纸上marker的边长,用尺量,单位为m
rvec, tvec,_= aruco.estimatePoseSingleMarkers(corners,size , cam_matrix, dist_coeff)
if draw==True and ids is not None:
#画出aruco姿态
aruco.drawDetectedMarkers(img, corners,ids)
#最后一个参数为绘制的轴的长度
aruco.drawAxis(img, cam_matrix, dist_coeff,rvec,tvec, 0.03)
return rvec,tvec,ids
def aruco_ids2Dict(self,ids,src):
'''
将具有相同ids的marker的信息, 归入一个ids字典下, 传参时ids与src的长度必须相等
例: 现有marker1,marker2,marker3, 三者对应中心点 centroid1, centroid2, centroid3, 但对应不同aruco
marker1: ids=1, centroid=np.array([0,0])
marker2: ids=0,centroid=np.array([10,10])
marker3: ids=1, centroid=np.array([55,55])
则,通过该函数,将得到字典: {'0':np.array([55,55]),
'1':np.array([0,0]),np.array([10,10])}
Parameters
----------
ids : tuple or list or array, marker的ids
DESCRIPTION.
src : tuple or list or array, 需要归类的src
DESCRIPTION.
Returns
-------
ids_dict : dict key=ids, value=src的字典
DESCRIPTION.
'''
src=np.array(src)
ids_dict={}
for i in np.unique(ids):
index=np.where(i==ids)[0]
ids_dict0={str(i):src[index]}
ids_dict.update(ids_dict0)
return ids_dict
def handeye_affineCalculation(self,cam_points,rob_points,eye_in_hand=True,th_1=0,th_2=0):
cam_points=np.float32(cam_points)
rob_points=np.float32(rob_points)
# hand_in_eye 下, 首先应保证机械臂移动点相对于一个中心点对称,即机械臂应按s型路线走"田", 如此便能保证所有机械臂点关于'田'中心点对称
# 这是因为由于相机的镜像关系,如果将机械臂点与相机点顺序成对(即rob_point1,cam_point1|rob_point2,cam_point2|...)送入公式进行仿射矩阵的计算, 如将新点带入会使机械臂向新点的镜像位置行进
# 该镜像错误有如下解决办法:
# 1.将机械臂点与相机点倒序成对带入(即rob_point1,cam_point9|rob_point2,cam_point8|...),直接可求出正确的仿射矩阵
# 2.将机械臂点与相机点顺序成对带入(即rob_point1,cam_point1|rob_point2,cam_point2|...), 但需对仿射矩阵作如下处理:
# R-旋转部分四个元素取负(即对affine_matrix[:,:2]取负,取负的几何意义为将矩阵旋转180度)
# T-平移部分tx'=2*cx-tx,ty'=2*cy-ty, 其中(cx,cy)为机械臂采样点里的中心点坐标, tx,ty分别为顺序成对代入求出的仿射矩阵的affine_matrix[0,2],affine_matrix[1,2]
# R:affine_matrix[:,:2]=-affine_matrix[:,:2]
# T:affine_matrix[0,2]=2*cx-affine_matrix[0,2],affine_matrix[1,2]=2*cy-affine_matrix[0,2]
# 此外, 每次工作,机械臂必须回到中心点拍照
# hand_to_eye下, 唯一的要求为:采样阶段应尽量保持机械臂末端贴近工作平面, 并保证同一平面上取9个点(位置任意,不需保证对称),工作时也无需回到某个固定点
if len(cam_points) == len(rob_points) and (len(cam_points) and len(rob_points)>=3):
if eye_in_hand==True:
cam_points_inverse=cam_points[::-1,:]
affine_matrix=cv2.estimateAffine2D(cam_points_inverse,rob_points)[0]
else:
affine_matrix=cv2.estimateAffine2D(cam_points,rob_points)[0]
affine_matrix[0,2]+=th_1
affine_matrix[1,2]+=th_2
else:
affine_matrix=None
if affine_matrix is not None:
affine_matrix[0,2]+=th_1
affine_matrix[1,2]+=th_2
return affine_matrix
def handeye_affineTransform(self,affine_matrix,cam_point):
cam_point,affine_matrix=np.float32(cam_point).reshape(-1,2),np.float32(affine_matrix)
if len(cam_point) > 2:
rob_point = np.vstack((affine_matrix[0,0]*cam_point[:,0]+affine_matrix[0,1]*cam_point[:,1]+affine_matrix[0,2],
affine_matrix[1,0]*cam_point[:,0]+affine_matrix[1,1]*cam_point[:,1]+affine_matrix[1,2])).T
else:
rob_point=None
return rob_point
def handeye_vuPredict(self,H,W,vu,z,z_calib):
'''
矫正由物体高度产生的像素坐标畸变, 需配合深度相机使用
Parameters
----------
H : int
DESCRIPTION.图像的宽
W : int
DESCRIPTION.图像的高
vu : array/tuple/list
DESCRIPTION.需矫正的的点像素坐标
z : float/int
DESCRIPTION.需矫正的点的深度
z_calib : float/int
DESCRIPTION.标定板所处平面深度
Returns
-------
array
DESCRIPTION.矫正后的像素坐标
'''
vu=np.int64(vu).flatten() # 统一格式
img_centroid=np.int64([H*0.5,W*0.5]) # 求图像中心点
h,w=vu[0]-img_centroid[0],vu[1]-img_centroid[1]
d = self.distance(vu,img_centroid)
d_predict=d*z/z_calib
u_predict=w*d_predict/d+img_centroid[1]
v_predict=h*d_predict/d+img_centroid[0]
return np.int64([v_predict,u_predict]).flatten()
def handeye_createRobPoints(self,c1,c2,t):
rob_points=np.array([[c1-t,c2+t],
[c1-t,c2 ],
[c1-t,c2-t],
[c1 ,c2-t],
[c1 ,c2 ],
[c1 ,c2+t],
[c1+t,c2+t],
[c1+t,c2 ],
[c1+t,c2-t]])
return rob_points
def handeye_getCamPoints(self,imgs,aruco_dict,show=False):
'''
提取多个图片中aruco的中心点像素坐标(仅识别单个aruco), 若单张图片中识别到多个aruco,或未识别到aruco
函数将打印'无效采样',单张图片存在单个aruco则为有效采样,函数不做任何反馈
该函数主要适用于手眼标定
依赖:aruco_centroid,labelPoint
Parameters
----------
imgs : 输入图片
DESCRIPTION.需以元组,列表的形式传入
aruco_dict : aruco字典
DESCRIPTION. 参考aruco_createDict
show : TYPE, 是否显示结果
DESCRIPTION. The default is False.
Returns
-------
cam_points : 元组,中心点
DESCRIPTION. 例: 若输入9中图片中有效采样数为8,则cam_point为长度为8的元组
valid : 元组,有效采样的索引
DESCRIPTION.
'''
centroids,valid=(),()
for i in range(len(imgs)):
centroid,ids=ct.aruco_centroid(imgs[i],aruco_dict)
if ids is not None and len(centroid)==1:
centroids+=(centroid[0],)
valid+=(i,)
if show==True:
for j in centroids:
self.labelPoint(imgs[i],j)
cv2.polylines(imgs[i],[np.int0(centroids)[:,::-1]],False,(0,255,255),thickness=2)
cv2.imshow('img',imgs[i])
cv2.waitKey(500)
else:
print(i,'无效采样')
cv2.destroyAllWindows()
print('有效采样共',len(valid),'个')
cam_points=np.array(centroids)
return cam_points,valid
def handeye_tsai(self,H_grid2cam,H_base2tool,eye_in_hand=True):
def skew(vector):
vector=vector.flatten()
return np.array([[0, -vector[2], vector[1]],
[vector[2], 0, -vector[0]],
[-vector[1], vector[0], 0]])
S,b,=(),()
A_tuple,B_tuple=(),()
I=np.eye(3)
# 计算R
for i in range(len(H_grid2cam)-1):
# 构造A,B 待解决, 顺序有错
if eye_in_hand==False:
A=np.linalg.inv(H_base2tool[i+1]).dot(H_base2tool[i])
B=H_grid2cam[i+1].dot(np.linalg.inv(H_grid2cam[i]))
else:
A=np.linalg.inv(H_base2tool[i+1]).dot(H_base2tool[i])
B=np.linalg.inv(H_grid2cam[i+1]).dot(H_grid2cam[i])
A_tuple+=(A,)
B_tuple+=(B,)
rgij,rcij=cv2.Rodrigues(A[:3,:3])[0],cv2.Rodrigues(B[:3,:3])[0]
theta_gij,theta_cij=np.linalg.norm(rgij),np.linalg.norm(rcij)
rngij,rncij = rgij/theta_gij,rcij/theta_cij
Pgij,Pcij= 2*np.sin(theta_gij/2)*rngij,2*np.sin(theta_cij/2)*rncij
S+=(skew((Pgij + Pcij)),)
b+=(Pcij - Pgij,)
S,b=np.vstack(S),np.vstack(b)
pcg_prime=np.linalg.pinv(S).dot(b)
pcg=2*pcg_prime/(np.sqrt(1+np.linalg.norm(pcg_prime)**2))
pcg0=np.linalg.norm(pcg)*np.linalg.norm(pcg)
R=(1-pcg0*0.5)*I+0.5*(pcg*pcg.T+np.sqrt(4-pcg0)*skew(pcg))
# 计算T
a0,b0=(),()
for a,b in zip(A_tuple,B_tuple):
RA=a[:3,:3]
TB=b[:3,3]
TA=a[:3,3]
a0+=(RA-I,)
b0+=((R.dot(TB))-TA,)
a0,b0=np.vstack(a0),np.hstack(b0)
T=np.linalg.pinv(a0).dot(b0)
H=np.eye(4)
H[:3,:3],H[:3,3]=R,T.reshape(3)
return H
def handeye_navy(self,H_grid2cam,H_base2tool,eye_to_hand=True):
def logMatrix(H):
R=H[:3,:3]
fi=np.arccos((R.trace()-1)/2)
w=fi/(2*np.sin(fi))*(R-R.T)
return np.array([[w[2,1],w[0,2],w[1,0]]]).reshape(3,1)
I=np.eye(3)
M=np.zeros((3,3))
Ra=()
Ta=()
Tb=()
# 求R
for i in range(len(H_grid2cam)-1):
if eye_to_hand==True:
A=np.linalg.inv(H_base2tool[i+1]).dot(H_base2tool[i])
B=H_grid2cam[i+1].dot(np.linalg.inv(H_grid2cam[i]))
else:
A=np.linalg.inv(H_base2tool[i+1]).dot(H_base2tool[i])
B=np.linalg.inv(H_grid2cam[i+1]).dot(H_grid2cam[i])
Ra+=(A[:3,:3],)
Ta+=(A[:3,3].reshape(3,1),)
Tb+=(B[:3,3].reshape(3,1),)
alpha,beta=logMatrix(A),logMatrix(B)
M=M+beta*alpha.T
R=np.linalg.inv(linalg.sqrtm(M.T.dot(M))).dot(M.T)
# 求T
C,d=(),()
for i in range(1,len(Ra)):
C+=(I-Ra[i],)
d+=(Ta[i]-R.dot(Tb[i]),)
C,d=np.vstack(C),np.vstack(d)
T=np.linalg.inv(C.T.dot(C)).dot(C.T.dot(d))
H=np.eye(4)
H[:3,:3],H[:3,3]=R,T.reshape(3)
return H
# 旋转相关函数
# 以下函数名中 各字母意义
# R:旋转矩阵(3x3)
# T:平移向量(3x1)
# E:欧拉角
# Q:四元数
def RT2H(self,R,T):
T=np.array(T)
H=np.eye(4)
H[:3,:3],H[:3,3]=R,T.reshape(3)
return H
def E2R(self,seq,E,degree=False):
r = rot.from_euler(seq, E, degrees=degree)
return r.as_matrix()
def Q2R(self,Q):
r=rot.from_quat(Q)
return r.as_matrix()
def R2E(self,seq,R,degree=False):
r=rot.from_matrix(R)
return r.as_euler(seq, degrees=degree)
def R2Q(self,R):
r=rot.from_matrix(R)
return r.as_quat()
def Q2E(self,Q,seq,degree=False):
r=rot.from_quat(Q)
return r.as_euler(seq,degree)
def circle_detection(self,img):
#该算法极度依赖调参, 不建议使用
#增加预处理
#增加圆数量判断
#增加中心点返回
if img.ndim==3:
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,2,100,param1=100,param2=50,minRadius=0,maxRadius=0)
#param2越小检测到的圆越多,反之越少
circles = np.uint16(np.around(circles))
print(len(circles[0,:]),'个圆被检测到')
img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
centroid=()
for i in circles[0,:]:
# draw the outer circle
cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
centroid+=(np.array([i[0],i[1]]),)
return img,centroid
def depth2Sensor(self,vu,z,H,W):
img_centroid=np.int64([H*0.5,W*0.5])
d=self.distance(vu,img_centroid)
z_sensor=np.sqrt((pow(d,2)+pow(z,2)))
return z_sensor
def alg_measure(self,vu1,vu2,depth_map,depth_cam_matrix,
depth_dist_coeff=np.zeros(5,dtype='float32'),
z1=None,z2=None,method=0,depth_scale=1000):
if method==0:
if z1==None:
z1=depth_map[vu1[0],vu1[1]]
if z2==None:
z2=depth_map[vu2[0],vu2[1]]
if z1==0 and z2==0:
real_distance=None
else:
vu = np.vstack((np.float64(vu1).reshape(1,2),
np.float64(vu2).reshape(1,2)))
vu_undistort=cv2.undistortPoints(vu,depth_cam_matrix,depth_dist_coeff).reshape(-1,2)
z1,z2=z1/depth_scale,z2/depth_scale
x1,y1=vu_undistort[0,:]*z1
x2,y2=vu_undistort[1,:]*z2
real_distance=np.sqrt(pow((x2-x1),2)+pow((y2-y1),2)+pow((z2-z1),2))
elif method==1:
xyz=self.pc_depth2xyz(depth_map,depth_cam_matrix,False,depth_scale)
xyz1,xyz2=xyz[vu1[0],vu1[1],:],xyz[vu2[0],vu2[1],:]
# 用户自定义z1,z2
if z1 is not None:
xyz1[2]=z1/depth_scale
if z2 is not None:
xyz2[2]=z2/depth_scale
# 判断深度是否为0
if xyz1[2]==0 or xyz2[2]==0:
real_distance =None
else:
real_distance=self.distance(xyz1,xyz2)
return real_distance
def cvMultiProcess(self):
cv2.setUseOptimized( True );
cv2.setNumThreads( 4 );
def socket_createServer(self,port,ip='host',connect_num=5):
ip =socket.gethostname() if ip=='host' else ip
server=socket.socket()
server.bind((ip, port))
server.listen(connect_num)
return server
def socket_createClient(self,port,ip='host'):
ip =socket.gethostname() if ip=='host' else ip
client=socket.socket()
client.connect((ip, port))
return client
def distance(self,point1,point2):
'''
计算两个2d点或两个3d点的距离
Parameters
----------
point1 : array/list/tuple
DESCRIPTION.
point2 : array/list/tuple
DESCRIPTION.
Returns
-------
distance : float
DESCRIPTION.
'''
point1,point2=np.float64(point1).flatten(),np.float64(point2).flatten()
assert len(point1)==len(point2)
if len(point1)==2 and len(point2)==2:
x1,x2,y1,y2=point1[0],point2[0],point1[1],point2[1]
distance=np.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
elif len(point1)==3 and len(point2)==3:
x1,x2,y1,y2,z1,z2=point1[0],point2[0],point1[1],point2[1],point1[2],point2[2]
distance=np.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1))
return distance
def hsvTuner(self,img,save=False,save_dir='./HSV'):
'''
hsv调色板, 若save=True, 则保存h_upper,h_lower,s_upper,s_lower,v_upper,v_lower
至save_dir下,需要用户输入文件名
Parameters
----------
img : array
DESCRIPTION.输入图片
save : bool, optional
DESCRIPTION. The default is True.
save_dir : str, optional
DESCRIPTION. The default is './HSV'.
Returns
-------
hsv_range : tuple
DESCRIPTION.按照h_upper,h_lower,s_upper,s_lower,v_upper,v_lower顺序保存为txt
'''
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
cv2.namedWindow('tuner', cv2.WINDOW_NORMAL)
def callback(para):
pass
cv2.createTrackbar('h_upper','tuner',180,180,callback)
cv2.createTrackbar('h_lower','tuner',0,180,callback)
cv2.createTrackbar('s_upper','tuner',255,255,callback)
cv2.createTrackbar('s_lower','tuner',0,255,callback)
cv2.createTrackbar('v_upper','tuner',255,255,callback)
cv2.createTrackbar('v_lower','tuner',0,255,callback)
while 1:
key=cv2.waitKey(1)&0xFF
if key==27:
break
h_upper=cv2.getTrackbarPos('h_upper','tuner')
h_lower=cv2.getTrackbarPos('h_lower','tuner')
if h_lower>h_upper:
cv2.setTrackbarPos('h_lower','tuner',h_upper)
s_upper=cv2.getTrackbarPos('s_upper','tuner')
s_lower=cv2.getTrackbarPos('s_lower','tuner')
if s_lower>s_upper:
cv2.setTrackbarPos('s_lower','tuner',s_upper)
v_upper=cv2.getTrackbarPos('v_upper','tuner')
v_lower=cv2.getTrackbarPos('v_lower','tuner')
if v_lower>v_upper:
cv2.setTrackbarPos('v_lower','tuner',v_upper)
mask=cv2.inRange(hsv,(h_lower,s_lower,v_lower),(h_upper,s_upper,v_upper))
img_mask=cv2.bitwise_and(img,img,mask=mask)
cv2.imshow('tuner',img_mask)
cv2.destroyAllWindows()
hsv_range=(h_upper,h_lower,s_upper,s_lower,v_upper,v_lower)
if save==True:
if os.path.exists(save_dir)==False:
os.mkdir(save_dir)
name=input('请输入文件名: ')
path=os.path.join(save_dir,name)
if path.endswith('.txt'):
np.savetxt(path,hsv_range)
else:
np.savetxt(path+'.txt',hsv_range)
return hsv_range, img_mask
def hsvConverter(self,img,hsv_range):
'''
hsv掩膜工具
Parameters
----------
img : array
DESCRIPTION.输入图片
hsv_range : tuple
DESCRIPTION.应按照(h_upper,h_lower,s_upper,s_lower,v_upper,v_lower)输入
Returns
-------
img_mask : array
DESCRIPTION.掩膜后的图片
'''
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
mask=cv2.inRange(hsv,(hsv_range[1],hsv_range[3],hsv_range[5]),
(hsv_range[0],hsv_range[2],hsv_range[4]))
img_mask=cv2.bitwise_and(img,img,mask=mask)
return img_mask
def poseEstimation(self,):
pass
def poseDraw(self,img,point_zero,xyz,thickness=2):
point_zero=np.array(point_zero).flatten()
xyz=np.array(xyz).reshape(3,2)
cv2.arrowedLine(img, tuple(point_zero),tuple(xyz[0]), (255,0,0), thickness)
cv2.putText(img,'x',tuple(xyz[0]),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),thickness)
cv2.arrowedLine(img, tuple(point_zero), tuple(xyz[1]), (0,255,0), thickness)
cv2.putText(img,'y',tuple(xyz[1]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),thickness)
cv2.arrowedLine(img, tuple(point_zero),tuple(xyz[2]), (0,0,255),thickness)
cv2.putText(img,'z',tuple(xyz[2]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),thickness)
def labelPoint(self,img,vu,size=10,color=(0,255,0),thickness=2):
# 标记vu
vu=np.int64(vu).flatten()
cv2.drawMarker(img,(vu[1],vu[0]),color,cv2.MARKER_CROSS,size,thickness)
def labelPointManully(self,img,draw_line=False,window_name='img'):
# 手动标记vu
# 按左键标记,按右键删除上一个点
if img.ndim==2:
img=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
p=[]
cv2.namedWindow(window_name,cv2.WINDOW_NORMAL)
cv2.imshow(window_name,img)
def draw_point(event, x, y, flags, param):
img_draw=img.copy()
if event==cv2.EVENT_LBUTTONUP:
p.append([x,y])
for u,v in np.array(p):
cv2.drawMarker(img_draw,(u,v),(0,255,0),cv2.MARKER_CROSS,10,2)
if draw_line==True:
cv2.polylines(img_draw,[np.array(p)],False,(0,255,255),thickness=2)
cv2.imshow(window_name,img_draw)
if event==cv2.EVENT_RBUTTONUP:
if len(p)!=0:
p.pop()
if draw_line==True:
if len(p)!=0:
cv2.polylines(img_draw,[np.array(p)],False,(0,255,255),thickness=2)
for u,v in np.array(p):
cv2.drawMarker(img_draw,(u,v),(0,255,0),cv2.MARKER_CROSS,10,2)
cv2.imshow(window_name,img_draw)
if event==cv2.EVENT_MOUSEMOVE:
cv2.setWindowTitle(window_name,str(y)+' , '+str(x))
cv2.setMouseCallback(window_name,draw_point)
cv2.waitKey()
cv2.destroyAllWindows()
p=np.array(p)[:,::-1] if len(p)!=0 else None # uv到vu
return p
def text(self,img,vu,text,delta_vu=(10,10),size=1,color=(255,0,0),thickness=1):
vu=np.int64(vu).flatten()+delta_vu
cv2.putText(img,str(text),(vu[1],vu[0]),cv2.FONT_ITALIC,size,color,thickness)
def getDepthRanges(self,depth_map,th = 1000, hist_show=False):
max_depth=int(depth_map.max())
hist = cv2.calcHist([depth_map],[0],None,[max_depth],[1,max_depth]).flatten()
hist[hist<th]=0
if hist_show==True:
plt.plot(hist,color="g", )
plt.show()
hist_nonzero=hist.nonzero()[0]
depth_ranges,depths=(),()
depth_range =[hist_nonzero[0]]
for i in range(len(hist_nonzero)-1): #前景
if hist_nonzero[i+1]-hist_nonzero[i]>2:
depth_range.append(hist_nonzero[i])
if depth_range[1]-depth_range[0]>=3:
depth_ranges+=(depth_range,)
depth_range=[hist_nonzero[i+1]]
if i==len(hist_nonzero)-2: # 背景
depth_range.append(hist_nonzero[i+1])
if depth_range[1]-depth_range[0]>=3:
depth_ranges+=(depth_range,)
depths=tuple(i[0]+np.argmax(hist[i[0]:i[1]]) for i in depth_ranges)
return depth_ranges,depths
def depthRange2Mask(self,depth_map,depth_range):
mask=cv2.inRange(depth_map,int(depth_range[0]),int(depth_range[1]))
return mask
def maskImg(self,img,mask):
img_mask=cv2.bitwise_and(img,img,mask=mask)
return img_mask
def sharp(self,img,method=0,iterations=1):
if method ==0:
kernel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]]) # lap5
elif method == 1:
kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) #lap9
elif method ==2:
kernel = np.array([[-1, -2, -1], [-2, 19, -2], [-1, -2, -1]])/7 #lap9
img_sharp = img.copy()
for i in range(iterations):
img_sharp = cv2.filter2D(img_sharp,cv2.CV_8U,kernel)
return img_sharp
def alg_depthMaskPeak(self,color_img,depth_map,lv=0,show_hist=False,distance=20,prominence=500,width=1,height=1,threshold=1):
# 待优化
# 该算法鲁棒性不高,建议使用getDephRange
max_value=int(depth_map.max())
hist = cv2.calcHist([depth_map],[0],None,[max_value],[1,max_value-1]).flatten()
#nonzero_index=hist.nonzero()[0]
#hist_nonzero=hist[nonzero_index]
# 寻找波峰
peaks, properties=signal.find_peaks(hist,
prominence=prominence,
distance=distance,
width=width,
height=height,
threshold=threshold)
if show_hist==True:
plt.plot(hist,color="g", )
plt.plot(peaks,hist[peaks],'*r')
plt.show()
# 计算每一个波峰的区间
border=()
border0=np.zeros(2,dtype='int')
for left, right in zip(properties['left_bases'], properties['right_bases']):
border0[0],border0[1]=left,right
border+=(border0,)
border0=np.zeros(2,dtype='int')
depth=[i[0]+np.argmax(hist[i[0]:i[1]]) for i in border]
mask=cv2.inRange(depth_map,int(border[lv][0]),int(border[lv][1]))
img_mask=cv2.bitwise_and(color_img,color_img,mask=mask)
return img_mask,depth[lv]
def alg_statisticThreshold(self,img):
if img.ndim==3:
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
kernelx,kernely=np.array([[-1,0,1]]),np.array([[-1,0,1]]).T
dx,dy = abs(cv2.filter2D(img, -1, kernelx)),abs(cv2.filter2D(img, -1, kernely))
dmax=np.maximum(dx,dy)
weight=np.sum(dmax)
total=np.sum(dmax*img)
threshold=int(total/weight)
img_bin=cv2.threshold(img,threshold,255,cv2.THRESH_BINARY)[1]
return img_bin
def alg_DerekBradleyThreshold(self,img,s=30,t=15):
if img.ndim==3:
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_bin=img.copy()
img_integral=cv2.integral(img_bin)[1:,1:]
kernel=np.zeros((s,s))
kernel[0,0],kernel[-1,-1],kernel[0,-1],kernel[-1,0]=1,1,-1,-1
img_conv=cv2.filter2D(img_integral,-1,kernel,borderType=1)
area=s*s
weight=img.astype('int64')*area
brightness=img_conv*((100-t)/100)
img_bin[weight<=brightness],img_bin[weight>brightness]=0,255
return img_bin
def meanShift(self,ps):
# 该函数主要应用于特征点聚类,以用于确定特征点位置
bandwidth = estimate_bandwidth(ps, quantile=0.1, n_samples=500)
ms = MeanShift(bandwidth=bandwidth, bin_seeding=True, cluster_all=True)
ms.fit(ps)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
return labels,cluster_centers
def getNearestNonzero(self,img,vu):
# 搜索最近的非零像素点, img-输入图像,必须为单通道, vu目标点
# vu_value-长度为3的array 前两个值为 最近非零点的像素坐标, 第三个值为该坐标的至
uv_nonzero = cv2.findNonZero(img)
if uv_nonzero is not None:
vu_nonzero=uv_nonzero.reshape(-1,2)[:,::-1] # uv转vu
distances = np.sqrt((vu_nonzero[:,0]-vu[0])**2+(vu_nonzero[:,1]-vu[1])**2)
vu_nearest=vu_nonzero[np.argmin(distances)]
value=img[vu_nearest[0],vu_nearest[1]]
vu_value=np.hstack((vu_nearest,value))
else:
vu_value=None
return vu_value
def FOV2Area(self,FOV,height):
H,V,D=FOV
area_W = np.tan(V*np.pi/180) * height
area_H = np.tan(H*np.pi/180) * height
return area_W, area_H
def cnt_getChildParent(self,cnts,hierarchy):
cnts_child,cnts_parent=(),()
for i in range(len(cnts)):
if hierarchy[0,i,3] == -1:
cnts_parent+=(cnts[i],)
else:
cnts_child +=(cnts[i],)
return cnts_child,cnts_parent
def cnt_getBBox(self,cnt):
rect = cv2.minAreaRect(cnt)
bbox_uv = np.int0(cv2.boxPoints(rect))
angle = rect[2]
return bbox_uv, angle
def cnt_getBBoxSize(self,bbox):
d1=self.distance(bbox[0],bbox[1])
d2=self.distance(bbox[1],bbox[2])
if d1>d2:
w,h = d1, d2
else:
w,h = d2, d1
return w,h
def cnt_getBBoxCentre(self,bbox_uv):
centre = np.array([sum(bbox_uv[:,0])*0.25,sum(bbox_uv[:,1])*0.25])
return centre
def feature_match(self,img_source,img_target,detector,matcher,count=10,show=False):
# kps : keypoints, dps: descriptors
# s: source , t: target
# 封装过度
kps_s,dps_s = detector.detectAndCompute(img_source,None)
kps_t,dps_t = detector.detectAndCompute(img_target,None)
matched_kps = matcher.match(dps_s,dps_t)
matched_kps_optimized=sorted(matched_kps,key=lambda x:x.distance)[:count]
matched_kps_s,matched_kps_t=(),()
for i in matched_kps_optimized:
matched_kps_s+=(kps_s[i.queryIdx].pt,)
matched_kps_t+=(kps_t[i.trainIdx].pt,)
matched_kps_s=np.float32(matched_kps_s)
matched_kps_t=np.float32(matched_kps_t)
if show==True:
img_draw=cv2.drawMatches(img_source,kps_s,
img_target,kps_t,
matched_kps_optimized,
None,
matchColor=(0,255,0),
flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT)
self.show(img_draw)
return matched_kps_s,matched_kps_t
def feature_optimization(self,matched_kps_s, matched_kps_t):
M, mask = cv2.findHomography(matched_kps_s, matched_kps_t, cv2.RANSAC, 5.0)
return M,mask
def feature_kps2Numpy(self,kps):
kps_numpy = tuple(i.pt for i in kps)
return kps_numpy
def feature_labelKpsDps(self,kps,dps,labels):
kps_labels,dps_labels=(),()
label_count=labels.max()+1
for i in range(label_count):
label=np.where(labels==i)[0]
kps_label= tuple(kps[j] for j in label)
kps_labels+=(kps_label,)
dps_labels+=(dps[label],)
return kps_labels,dps_labels
def perspectImg(self,img,ps_s_uv):
p1,p2,p3=ps_s_uv[0],ps_s_uv[1],ps_s_uv[2]
d1,d2=self.distance(p1,p2),self.distance(p2,p3)
if d1>d2:
w,h=d1,d2
else:
w,h=d2,d1
ps_t=np.float32([[0,0],[0,w],[h,w],[h,0]])
M=cv2.getPerspectiveTransform(np.float32(ps_s_uv),ps_t)
img_out=cv2.warpPerspective(img,M,(int(h),int(w)))
return img_out,M,ps_t
# def perspectImgReverse(self)
def perspectPs(self,ps_s,M):
ps_t = cv2.perspectiveTransform(ps_s.reshape(-1,1,2),M)
return ps_t
def matchKFeatures():
pass
def roiShotCut(self,img,save_dir='./data/roi'):
# 依赖cv_roi2img
print('按任意键输入名称,按esc键退出')
if os.path.exists(save_dir)==False:
os.mkdir(save_dir)
img_dict={}
while 1:
roi,key=self.roiSelect(img)
if key == 27:
break
else:
img_roi=self.roi2img(img,roi)
if roi.all()!=0:
name=input('请输入文件名(仅支持英文输入): ')
if len(name)!=0:
img_dict.update({name:img_roi})
path=os.path.join(save_dir,name) \
if name.endswith('.jpg') else os.path.join(save_dir,name+'.jpg')
print(path)
cv2.imwrite(path,img_roi)
print('已保存图片至',path)
else:
continue
else:
continue
return img_dict
def roiSelect(self,img,window_name='img',thickness=2,bgr=(0,0,255)):
# 选取矩形roi,返回(4,)向量,分别为(v1,u1,v2,u2)
# v1,u1为矩形左上角点, v2,u2为矩形右下角点
def draw_rect(event, x, y, flags, param):
if event==cv2.EVENT_LBUTTONDOWN:
roi[0]=y,x # 框的左上角点 x=u,y=v