-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessing.py
More file actions
1632 lines (1344 loc) · 55.3 KB
/
Copy pathprocessing.py
File metadata and controls
1632 lines (1344 loc) · 55.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
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
# processing.py
import cv2 as cv
from tkinter.messagebox import showinfo, showerror, showwarning
from tract_point import *
import numpy as np
import math
from utils import dcut
from kmeans import k_means
import matplotlib.pyplot as plt
"""debug global property"""
from control import pstatus
from utils import Stdout_progressbar
SHOW_TIME = 100 # 默认的展示间隔时间,默认为0.1s,单位:ms
MAX_VALUE_THRESH = 1000
OUTER_BORDER = 50
class BGRimg:
'''
3 channels for [b, g, r] in range (0, 255)
'''
class Grayimg:
'''
one channel gray img
'''
# def my_show(frame, ratio=1, center_point=(-1,-1), _time=0):
def my_show(frame, ratio=1, _time=0):
"""
frame: 要展示的帧
ratio: 缩放比例
_time: 显示时间
"""
# print(center_point)
h = frame.shape[0]
w = frame.shape[1]
if ratio == 0:
frame = cv.resize(frame, (1200, 800))
else:
frame = cv.resize(frame, (int(w*ratio), int(h*ratio)))
cv.imshow("window", frame)
key = cv.waitKey(_time)
if key == ord('q'):
return 1
elif key == 32: # 空格键暂停
if _time>0:
return my_show(frame, ratio, _time=0)
else:
pass
return 0
""""""
def restrict_to_boundary(domain, h, w, start_y=0, start_x=0):
"""
domain: `y,y,x,x`
"""
return (
max(domain[0], start_y),
min(domain[1], h - 1),
max(domain[2], start_x),
min(domain[3], w - 1)
)
def in_boundary(point, h, w):
"""
point: (y, x)
"""
return point[0] >= 0 and point[0] < h and point[1] >= 0 and point[1] < w
def printb(s, OutWindow, p=False): # 打印到output board上
s = str(s)
if OutWindow is not None and OutWindow.display:
OutWindow.textboxprocess.insert("0.0",s+'\n')
if p:
print(s)
def expand(frame, mutiple=1):
# print('执行了这个函数')
height, width, channel = frame.shape
return cv.resize(frame,(round(width*mutiple), round(height*mutiple)))
def dist(A, B):
return math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
def rect_cover1(frame, thres_value=0, edge=0): # 在指定的图像中用一个矩形覆盖所有值大于thres_value的点
upper = (frame.shape[0],frame.shape[1])
lower = (-1,-1)
left = (frame.shape[0],frame.shape[1])
right = (-1,-1)
for i in range(frame.shape[0]):
for j in range(frame.shape[1]):
if frame[i][j] > thres_value:
if i > lower[0]:
lower = (i,j)
if i < upper[0]:
upper = (i,j)
if j > right[1]:
right = (i,j)
if j < left[1]:
left = (i,j)
return ((upper[0]-edge,lower[0]+edge,left[1]-edge,right[1]+edge),
(tuple(reversed(upper)), tuple(reversed(lower)), tuple(reversed(left)), tuple(reversed(right)))) # 上,下,左,右,先y后x
def count_points(frame,thres=1): # 灰度图
points = []
for i in range(frame.shape[0]):
for j in range(frame.shape[1]):
if frame[i][j]>=thres:
points.append((j,i))
return points
def cleanout(points, domain):
X = [x[0] for x in points]
Y = [x[1] for x in points]
# 中位数过滤
X = list(sorted(X))
Y = list(sorted(Y))
xmid = X[len(X)//2] if len(X)%2 == 1 else (X[len(X)//2-1] + X[len(X)//2]) / 2
ymid = Y[len(Y)//2] if len(Y)%2 == 1 else (Y[len(Y)//2-1] + Y[len(Y)//2]) / 2
cleaned_points = []
for p in points:
if abs(p[0]-xmid) > domain[0] or abs(p[1]-ymid) > domain[1]:
continue
cleaned_points.append(p)
return cleaned_points
def print_mid_point(rect: list|tuple, sep=','):
"""in:yyxx or xy
Args:
rect (list | tuple): yyxx or xy
sep (str, optional): _description_. Defaults to ','.
Raises:
Exception: _description_
Returns:
str: midpoint: xy
"""
if len(rect) == 4:
x = (rect[2]+rect[3])/2
y = (rect[0]+rect[1])/2
return str(round(x,2))+sep+str(round(y,2))
elif len(rect) == 2:
return str(round(rect[0],2))+sep+str(round(rect[1],2))
else:
raise Exception('rect的长度错误,应为2或4')
'''def extract_features_from_mask(mask, pre_point, thresh_dist):
# 寻找所有为True的点的坐标
points = np.argwhere(mask)
# 计算每个点与前置点的距离
distances = np.linalg.norm(points - pre_point, axis=1)
# 找到距离小于等于阈值的点的索引
valid_indices = np.where(distances <= thresh_dist)[0]
# 提取符合条件的点的中心位置
valid_points = points[valid_indices]
center_positions = valid_points.mean(axis=0)
return center_positions'''
def color_deal(frame,midval:tuple,dis:int,pre_state,thresh_dist,OutWindow=None):
"""
用颜色过滤
frame: 截取过后的处理帧
midval: 颜色
dis: 颜色的范围
pre_state: 上一帧的状态,是否为black
thresh_dist: 阈值
OutWindow: 展示窗
return value:
center_point: (y, x)
"""
# low_bound=tuple(map(lambda x: int(x-dis),midval))
# high_bound=tuple(map(lambda x: int(x+dis),midval))
low_bound = np.array(midval) - dis
high_bound = np.array(midval) + dis
mask = cv.inRange(frame,low_bound,high_bound)
points = np.argwhere(mask)
# least_points = 20
if len(points) < 20:
return 0, 0 # 0, 0表示没有在范围内的点(或者符合要求的点太少)
# 如果前一帧为black,需要重写找点
if pre_state == -1: # 第一帧或者前一帧为black
'''用kmeans算法进行聚类,选择包含点最多的类的中心位置作为center'''
# kmeans = KMeans(n_clusters=3, n_init='auto') # 聚类的数量为3
# kmeans.fit(points)
clusters, center_positions = k_means(points, 3, 0.1, 10)
center_positions = np.array(center_positions)
# 获取每个点所属的类别
# labels = kmeans.labels_
# 可视化聚类结果
# img_show = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
'''img_show = frame.copy()
for i, each in enumerate(points):
if labels[i] == 0:
cv2.circle(img_show, (each[1], each[0]), 2, (0, 0, 255), -1)
elif labels[i] == 1:
cv2.circle(img_show, (each[1], each[0]), 2, (0, 255, 0), -1)
else:
cv2.circle(img_show, (each[1], each[0]), 2, (255, 0, 0), -1)
for center in kmeans.cluster_centers_:
cv2.circle(img_show, (int(center[1]), int(center[0])), 2, (255, 255, 255), -1)'''
# cv2.imshow("img_show",img_show)
# cv2.waitKey(0)
# 如果中心点的距离小于阈值,则认为是同一个点
# center_positions = kmeans.cluster_centers_
# 计算每个中心点到其他中心点的距离
distances = np.linalg.norm(center_positions - center_positions[:, np.newaxis], axis=2)
linked = distances < thresh_dist
''' linked相当于所有中心点形成的无向图的邻接矩阵,下面需要计算每个强连通分量(团?)的中心点
用kasaraju算法计算强连通分量'''
# 计算邻接矩阵的转置
linked_transpose = linked.T
# 从任意一个点开始进行深度优先搜索,得到搜索的顺序
visited = np.zeros(linked.shape[0], dtype=bool)
point_color = np.zeros(linked.shape[0], dtype=np.int32)
order = []
sccCnt = [0] # 为了在函数中可以修改外部变量
def dfs(i):
visited[i] = True
for j in range(linked.shape[0]):
if linked[i, j] and not visited[j]:
dfs(j)
order.append(i)
def dfs_transpose(i):
point_color[i] = sccCnt[0]
for j in range(linked.shape[0]):
if linked_transpose[i, j] and point_color[j] == 0:
dfs_transpose(j)
def kasaraju():
for i in range(linked.shape[0]):
if not visited[i]:
dfs(i)
# visited[:] = False
for i in reversed(order):
if point_color[i] == 0:
sccCnt[0] = sccCnt[0] + 1
dfs_transpose(i)
# 计算强连通分量
kasaraju()
# 统计出scc
group_id = np.unique(point_color)
scc = np.zeros((len(group_id),), dtype=np.object_)
for i, each in enumerate(group_id):
scc[i] = np.where(point_color == each)[0]
print('cluster scc',scc)
# 计算每个scc包含点的个数
numbers = np.array([len(x) for x in clusters.values()])
scc_numbers = [numbers[each].sum() for each in scc]
print('scc_numbers', scc_numbers)
'''# 根据强连通分量合并聚类
for each in scc:
center_positions[each] = center_positions[each].mean(axis=0)
# 把每一类的label统一为这个类中最小的label、
for each in scc:
idx = [i for i, label in enumerate(labels) if label in each]
labels[idx] = each.min()
# 统计每个类别中的点的数量
unique_labels, counts = np.unique(labels, return_counts=True)
print('label and counts',unique_labels, counts)'''
# 找到包含点最多的类的类别号
max_count_cls = np.argmax(scc_numbers)
# 获取包含点最多的类的所有中心的平均位置
center_point = center_positions[scc[max_count_cls]].mean(axis=0)
center_point = center_point.astype(int)[::-1]
else:
'''到前置点的距离小于阈值的点的中心位置作为center'''
'''# 计算每个点与前置点的距离
distances = np.linalg.norm(points - pre_point, axis=1)
# 找到距离小于等于阈值的点的索引
valid_indices = np.where(distances <= thresh_dist)[0]
# 提取符合条件的点的中心位置(平均/外接矩形中心)
valid_points = points[valid_indices]
# 如果valid_points为空,则在下一步计算时会出错,故需要特判
if valid_points.size == 0:
return 0, 0'''
# 因为所有的点已经是有在domain之内这个限制了
# 所以不需要再进行筛选。
# 因此border的设定就很关键了,因为这限制了目标物的移动速度不能大于border*fps px/s
# 因此border的设定应该与跳帧系数skip_n有关,与fps有关
valid_points = points
center_point = valid_points.mean(axis=0).astype(int)[::-1]
'''center_point: (x, y)'''
# print(center_point)
border = 20
x_left = center_point[0] - border
x_right = center_point[0] + border
y_up = center_point[1] - border
y_down = center_point[1] + border
''' # all_rect, points = rect_cover1(mask,0,10)
X = count_points(mask)
X_final = cleanout(X,(200,200))
if len(X_final)<10:
return 0,0
x_left=min([x[0] for x in X_final])
x_right=max([x[0] for x in X_final])
y_up=min([y[1] for y in X_final])
y_down=max([y[1] for y in X_final])
midpoint=((x_left+x_right)//2 , (y_up+y_down)//2)'''
if OutWindow and OutWindow.display:
'''注:在这里画完了,函数外面一样可以用'''
cv.circle(frame,center_point,1,color=(0,0,255))
# cv.rectangle(frame,(x_left, y_up),(x_right,y_down),(0,0,255),1)
# if my_show(frame_show1, ratio=1, _time=0):
# return 'q',0
pass
return 'OK', center_point[::-1] # center_point: (y, x)
"""颜色识别的主函数"""
def main_color(cap,kind,root,OutWindow,progressBar,pm=1,skip_n=1): # 颜色提取
# main_color识别的border默认为20.
# 是否超过border,即超出domain的范围,现在需要手动判断
border = 20
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
ret, frame0 = cap.read()
if not ret:
showerror(message='读入错误')
return 'error'
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
num = int(cap.get(7))
Trc = Tractor()
Trc.set("mutiple",pm)
midval = np.zeros((3,))
if kind == 'front':
showinfo('','请提取前点颜色')
midval_f = Trc.tract_color(frame0)
if midval_f[0] == -1:
return 'stop'
if OutWindow and OutWindow.display:
OutWindow.textboxprocess.delete('0.0','end')
OutWindow.textboxprocess.insert('0.0','前点颜色(BGR)'+str(midval_f))
OutWindow.textboxprocess.insert('0.0',"帧序号:[中心点坐标]\n")
file = None
else:
file = open('out-color-1.txt','w')
# showinfo(message='前点颜色(BGR)'+str(midval_f)+' ...请等待')
midval = midval_f
else:
showinfo('','请提取后点颜色')
midval_b = Trc.tract_color(frame0)
if midval_b[0] == -1:
return 'stop'
if OutWindow and OutWindow.display:
OutWindow.textboxprocess.delete('0.0','end')
OutWindow.textboxprocess.insert('0.0','后点颜色(BGR)'+str(midval_b))
OutWindow.textboxprocess.insert('0.0',"帧序号:[中心点坐标]\n")
file = None
else:
file = open('out-color-2.txt','w')
midval = midval_b
cap.set(cv.CAP_PROP_POS_FRAMES, 0) # 重置为第一帧
domain = (0,frame0.shape[0],0,frame0.shape[1]) # 上下左右
domain = [int(x*pm) for x in domain]
success = 1
stdoutpb = Stdout_progressbar(num)
cnt = 0
pre_state = -1 # 初始设为前一帧为black
progressBar['maximum'] = num
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
stdoutpb.reset(skip_n)
while success:
success, frame = cap.read()
if not success:
break
cnt += 1
frame = expand(frame,pm)
if skip_n > 1 and cnt % skip_n != 1:
continue
progressBar['value'] = cnt
root.update()
rtn, center = color_deal(frame[domain[0]:domain[1]+1,domain[2]:domain[3]+1],midval, 15, pre_state, np.linalg.norm(size) // 10, OutWindow)
# thresh_dist = np.linalg.norm(size) // 10
if rtn==0:
pre_state = -1
domain = (0,size[1] - 1,0,size[0] - 1)
if OutWindow and OutWindow.display:
printb(str(cnt)+': '+'black', OutWindow)
else:
file.write(f'{cnt} 0,0\n')
elif rtn=='q':
printb('用户退出', OutWindow)
cv.destroyAllWindows()
break
else:
center_0 = (center[0]+domain[0], center[1]+domain[2])
frame_show = frame.copy()
domain = (domain[0]+center[0]-border,domain[0]+center[0]+border, domain[2]+center[1]-border,domain[2]+center[1]+border)
# restrict to boundary
domain = restrict_to_boundary(domain, size[1], size[0])
if OutWindow and OutWindow.display:
'''中心点的圆点是在deal_color()中画的'''
cv.rectangle(frame_show, (domain[2],domain[0]), (domain[3],domain[1]), (0,0,255), 1)
domain_show = (domain[0]-border, domain[1]+border, domain[2]-border, domain[3]+border)
domain_show = restrict_to_boundary(domain_show, size[1],size[0])
if my_show(dcut(frame_show, domain_show),ratio=4, _time=100):
cv.destroyAllWindows()
break
printb(str(cnt)+': '+print_mid_point(center_0), OutWindow)
else:
file.write(f'{cnt} {print_mid_point(center_0)}\n') # standard format
pre_state = 1
stdoutpb.update(cnt)
# while
stdoutpb.update(-1) # 标志结束
if OutWindow and OutWindow.display:
cv.destroyAllWindows()
pass
else:
file.close()
showinfo(message='检测完成!')
return 'ok'
"""meanshift方法识别主函数"""
def meanshift(cap,kind,root=None,OutWindow=None,progressBar=None,pm=1, skip_n=1):
# 输入进度条所在窗口,输出窗口,进度条和处理缩放比率
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
num = cap.get(7)
Trc = Tractor()
Trc.set('mutiple',pm)
r, h, c, w = Trc.select_rect(frame)
if r == None:
return 'stop'
track_window = (c, r, w, h)
# print(track_window)
frame = expand(frame,pm)
roi = frame[r:r+h, c:c+w]
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
# 3.3 计算直方图
roi_hist = cv.calcHist([hsv_roi], [0], None, [180], [0, 180])
# 3.4 归一化
cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX)
# 4. 目标追踪
# 4.1 设置窗口搜索终止条件:最大迭代次数,窗口中心漂移最小值
term_crit = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 1, 1)
cap.set(cv.CAP_PROP_POS_FRAMES, 0) # 重置为第一帧
stdoutpb = Stdout_progressbar(num)
cnt = 0
progressBar['maximum'] = num
if OutWindow and OutWindow.display:
OutWindow.lift()
# OutWindow.WindowsLift()
# OutWindow.textboxprocess.delete('0.0','end')
OutWindow.textboxprocess.insert('0.0',"帧序号:[中心点坐标]\n")
else:
file = open('out-meanshift-1.txt','w') if kind == 'front' else open('out-meanshift-2.txt','w')
stdoutpb.reset(skip_n)
while(True):
# 4.2 获取每一帧图像
ret, frame = cap.read()
if ret == True:
cnt += 1
if skip_n > 1 and cnt % skip_n != 1:
continue
progressBar['value'] = cnt
root.update()
frame = expand(frame,pm)
x, y, w, h = track_window
if OutWindow and OutWindow.display:
OutWindow.textboxprocess.insert("0.0",str(cnt) + ': [' + print_mid_point((y, y+h, x, x+w)) + ']\n')
else:
file.write(f'{cnt} {print_mid_point((y, y+h, x, x+w))}\n') # standard format
# file.write(print_mid_point((y, y+h, x, x+w)) + '\n')
# 4.3 计算直方图的反向投影
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
# 4.4 进行meanshift追踪
ret, track_window = cv.meanShift(dst, track_window, term_crit)
# ret, track_window = cv2.CamShift(dst, track_window, term_crit)
# center, size, angle = ret # 解包
# 4.5 将追踪的位置绘制在视频上,并进行显示
if OutWindow and OutWindow.display:
x, y, w, h = track_window
img2 = cv.rectangle(frame, (x, y), (x + w, y + h), 255, 2)
rtn = my_show(img2,OutWindow.ratio, 60)
if rtn == 1:
return 'stop'
stdoutpb.update(cnt)
else:
break
stdoutpb.update(-1) # 标志结束
if OutWindow and OutWindow.display:
return 'OK'
file.close()
showinfo(message='检测完成!')
return 'OK'
def midPoint(A,B):
x1,y1 = A
x2,y2 = B
return ((x1+x2)/2 , (y1+y2)/2)
def middle_point(rect:list):
x = (rect[2]+rect[3])//2
y = (rect[0]+rect[1])//2
return (y,x)
def Magnify(cap, root):
"""get the magnify ratio in processing
Args:
cap (cv.CAP): the video
root (tk.Tk): root window
Returns:
float, float, (int, int): body_length(px), real_length(cm), middle_point
"""
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
ret, frame0 = cap.read()
Trc = Tractor()
showinfo(message='请点击目标物前端')
Trc.tractPoint(frame0, "please click the very front of the object, enter to confirm, q to quit, space to redo")
point_f = Trc.gbPoint
showinfo(message='请点击目标物后端')
Trc.tractPoint(frame0, "please click the very back of the object, enter to confirm, q to quit, space to redo")
point_b = Trc.gbPoint
length = dist(point_f, point_b)
Trc.inputbox(root=root,show_text='请输入目标物的实际长度,单位:厘米')
body_length = eval(Trc.gbInput)
# my_show(frame0, 50*body_length/length, midPoint(point_b,point_f))
return body_length, length, midPoint(point_b,point_f)
'''之前写的旋转函数,现在用cv2的函数实现'''
def rotate(img, angle, center=None, scale=1.0):
"""
@param:
img: the img to be rotated
angle: the angle to rotate the img (in degree)
center: the center of the img
scale: the scale of the img
"""
# Determine the center of the img
(h, w) = img.shape[:2]
if center is None:
center = (w/2, h/2)
# Define the rotation matrix
M = cv.getRotationMatrix2D(center, angle, scale)
# Apply the rotation to the img
rotated = cv.warpAffine(img, M, (w, h))
return rotated
"""计算一个点绕另一个点旋转后的坐标"""
def rotate_point(point, center, deg):
"""
deg > 0: 逆时针旋转
"""
rad = deg * math.pi / 180
rows = center[1]*2
cols = center[0]*2
x,y = point
y1 = int((y - rows/2) * math.cos(rad) - (x - cols/2) * math.sin(rad) + rows/2)
x1 = int((y - rows/2) * math.sin(rad) + (x - cols/2) * math.cos(rad) + cols/2)
if not in_boundary((y1, x1), rows, cols):
return -1, -1
return x1, y1
'''卷积操作结果,用cv2的函数实现'''
def conv2d_res(frame, kernal, pos, angle=0):
# 将图片逆时针旋转angle角度
rows, cols = frame.shape
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
rotated = cv2.warpAffine(frame, M, (cols, rows))
frame = rotated
# 对应的点也转过angle角度
pos = rotate_point(pos, (cols/2, rows/2), angle)
return cv.filter2D(frame, cv.CV_16S, kernal)[pos[0]][pos[1]] # cv.CV_16S代表输出的数据类型为16位整数
"""手动实现"""
'''h,w = kernal.shape
x,y = pos
res = 0
for i in range(h):
for j in range(w):
res += frame[x+i][y+j]*kernal[i][j]
print(res)
return res'''
def max_conv2d(frame, domain, kernal, angle, display):
"""
frame: 原图像
domain: 卷积作用域
kernal: 卷积核
angle: 旋转角度
display: 是否显示结果
return value:
max_pos_ori: (y, x)
"""
# 转为弧度
rad = angle * math.pi / 180
# 旋转图像(逆时针旋转)
rows, cols = frame.shape
M = cv.getRotationMatrix2D((cols/2, rows/2), angle, 1)
rotated = cv.warpAffine(frame, M, (cols, rows))
frame = rotated
conv_res = cv.filter2D(frame, cv.CV_16S, kernal) # 整个图只卷积一次
h = domain[1] - domain[0]
w = domain[3] - domain[2]
max_value = -1e7
max_pos = (-1,-1)
for y in range(domain[0],domain[1]+1):
for x in range(domain[2],domain[3]+1):
# 旋转对应点: 根据整个frame的中心旋转
# anti-clockwise rotation(positive value)
y1 = int((y - rows/2) * math.cos(rad) - (x - cols/2) * math.sin(rad) + rows/2)
x1 = int((y - rows/2) * math.sin(rad) + (x - cols/2) * math.cos(rad) + cols/2)
# 旋转之后有可能超出范围
if not in_boundary((y1, x1), rows, cols):
continue
# 计算卷积
res = conv_res[y1, x1]
# frame[y1][x1] = numpy.sum(frame[y-domain[2]:y+domain[3]+1, x-domain[0]:x+domain[1]+1] * kernal)
# 更新最大值
if res > max_value:
max_value = res
max_pos = (y, x)
# 计算最大值对应的中心点
max_pos_center = max_pos_ori = max_pos
# h, w = kernal.shape
# max_pos_center = (max_pos[0] + h//2, max_pos[1] + w//2)
# if display:
# print('max_value: ' + str(max_value))
# print('max_pos: ' + str(max_pos))
return max_pos, max_value # 回传中心点
def max_template(frame, domain, template, angle, method=cv2.TM_CCORR_NORMED, display=False):
'''
method in ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
'cv.TM_CCORR_NORMED']
'''
rad = angle * 3.1416 / 180
th, tw = template.shape
frame = frame[domain[0]:domain[1]+th, domain[2]:domain[3]+tw]
if display:
frame_show = frame.copy()
h, w = frame_show.shape
cv.imshow("frame", cv.resize(frame_show, (600, int(600/w*h))))
if cv.waitKey(1) == ord('q'):
exit(0)
fh, fw = frame.shape
M = cv.getRotationMatrix2D((fw/2, fh/2), angle, 1)
rotated = cv.warpAffine(frame, M, (fw, fh))
corr = cv2.matchTemplate(rotated, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(corr)
"""display"""
# corr = (corr - min_val) / (max_val-min_val) # [0,1]
corr = corr ** 5 # 类似gamma校正
# 显示响应图
'''plt.figure(0)
plt.imshow(corr, cmap='gray')
plt.title('Normalized Correlation Response Map')
plt.colorbar()
plt.scatter(*max_loc, c='r')
max_loc_0 = rotate_point(max_loc, (fw/2, fh/2), -angle)
plt.scatter(*max_loc_0, c='b')
plt.show()'''
# 显示大图和小图和框的位置
'''plt.figure(1)
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(rotated, cv2.COLOR_BGR2RGB))
plt.title('Large Image')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(template, cv2.COLOR_BGR2RGB))
plt.title('Small Image')
plt.show()'''
# 得到最值点
if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
raise Exception('not implemented')
# 将最值点旋转回去
# max_loc: yx
max_loc_0 = rotate_point(max_loc, (fw/2, fh/2), -angle)
max_loc_1 = (max_loc_0[0] + domain[2], max_loc_0[1] + domain[0])
# 返回max_loc, max_value
return max_loc_1, max_val
def get_frame(number):
cap.set(cv.CAP_PROP_POS_FRAMES, 0)
while number:
rtn, frame = cap.read()
number-=1
my_show(frame)
cv.imwrite("C:\\Users\\LENOVO\\Desktop\\obj_frame.jpg",frame)
def rect_cover(frame, thres_value=0): # 在指定的图像中用一个矩形覆盖所有值大于thres_value的点
upper = (frame.shape[0],frame.shape[1])
lower = (-1,-1)
left = (frame.shape[0],frame.shape[1])
right = (-1,-1)
for i in range(frame.shape[0]):
for j in range(frame.shape[1]):
if frame[i][j] > thres_value:
if i > lower[0]:
lower = (i,j)
if i < upper[0]:
upper = (i,j)
if j > right[1]:
right = (i,j)
if j < left[1]:
left = (i,j)
return ((upper[0],lower[0],left[1],right[1]),
(tuple(reversed(upper)), tuple(reversed(lower)), tuple(reversed(left)), tuple(reversed(right)))) # 上,下,左,右,先y后x
def rect_points(points):
X = [x[0] for x in points]
Y = [y[1] for y in points]
return (min(Y), max(Y), min(X), max(X))
"""特征提取的主函数-用模版匹配"""
def feature_template(cap,kind='front',OutWindow=None,progressBar=None,root=None, skip_n=1, turn_start=1, turn_end=0):
"""
return: OK | stop
"""
thresh_value = 0.9
initial_offset = 10
detect_offset = 60
cap.set(cv.CAP_PROP_POS_FRAMES, turn_start - 1)
num = cap.get(7) # 获取视频总帧数
ret, frame0 = cap.read() # 读取第一帧
size = frame0.shape[:2][::-1]
# frame0 = cv2.GaussianBlur(frame0, (3,3), 0)
Trc = Tractor()
showinfo(message='请选择初始矩形框')
r, h, c, w = Trc.select_rect(frame0)
if r is None:
printb('用户取消', OutWindow)
return 'stop'
template = cv.cvtColor(frame0[r:r+h, c:c+w], cv.COLOR_BGR2GRAY)
th, tw = template.shape
if OutWindow and OutWindow.display:
printb('start:', OutWindow)
else:
file = open('out-feature-1.txt','w') if kind == 'front' else open('out-feature-2.txt','w')
cap.set(cv.CAP_PROP_POS_FRAMES, turn_start - 1)
pre_angle = 0 # 初始化为0
pre_state = 0 # init
domain = (r - initial_offset,r + initial_offset,c - initial_offset,c+ initial_offset)
stdoutpb = Stdout_progressbar(num)
progressBar['maximum'] = num
cnt = turn_start - 1
stdoutpb.reset(skip_n)
while True:
ret, frame = cap.read()
if not ret:
break
frame_show = frame.copy()
cnt += 1
if turn_end > 0 and cnt > turn_end:
break
if skip_n > 1 and cnt % skip_n != 1:
continue
progressBar['value'] = cnt
root.update()
if OutWindow and OutWindow.display:
print(f'\n{cnt} {"===" * 10} {cnt}')
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
if pre_state in [0, 1]:
angles = list(range(pre_angle-3, pre_angle+3+1)) # 循环7次
# angles = [0,20]
else: # 上一帧未找到
angles = [-90, -60, -30, 0, 30, 60, 90] # 循环7次
max_val = 0
max_loc = [-1, -1]
for angle in angles:
loc, val = max_template(frame, domain, template, angle, display=False)
if val > max_val:
max_val = val
max_loc = loc
max_angle = angle
if np.sum(max_loc) < 0:
cv.destroyAllWindows()
raise Exception("error")
if max_val < thresh_value: # [0,1]
# pre_angle = 0
pre_state = 2 # black
if OutWindow and OutWindow.display:
if my_show(frame_show, ratio=1, _time=100):
return 'stop'
printb('max_value: ' + str(max_val), OutWindow, True)
printb('black', OutWindow)
else:
file.write(f'{cnt} black\n')
file.write(f'{cnt} relocate...\n')
print('!!! black !!!\nrelocate...')
ob = OUTER_BORDER # int
domain = (ob, size[1]-ob, ob, size[0]-ob)
else:
pre_angle = max_angle
pre_state = 1
if OutWindow and OutWindow.display:
# 显示匹配框
x0, y0 = max_loc
points = [[x0, y0 ],
[x0+tw,y0 ],
[x0+tw,y0+th],
[x0, y0+th]]
points = [rotate_point(each, max_loc, -max_angle) for each in points]
cv.polylines(frame_show, [np.array(points).astype(np.int32)], True, (0, 0, 255), 2)
# cv.rectangle(frame, *max_loc, (max_loc[0] + th, max_loc[1] + tw), (0,0,255), 2)
if my_show(frame_show, _time=100):
return 'stop'
printb('max_value: ' + str(max_val), OutWindow, True)
printb('now_angle: ' + str(max_angle), OutWindow, True)
printb('now_loc: ' + str(max_loc), OutWindow, True)
else:
# 写入文件
file.write(f'{cnt} {max_loc[1]}, {max_loc[0]}\n') # 中心点
file.write(f'{cnt} angle {max_angle}\n') # 辅助角度变化
pass
domain = (max_loc[1]-detect_offset,max_loc[1]+detect_offset, max_loc[0]-detect_offset,max_loc[0]+detect_offset) # 更新domain
domain = restrict_to_boundary(domain, size[1]-th, size[0]-tw)
# print('domain:',domain)
# print(size, tw)
if OutWindow and OutWindow.display:
printb(f'{cnt} {"===" * 10} {cnt}', OutWindow)
stdoutpb.update(cnt)
stdoutpb.update(-1)
showinfo(message='检测完成!')
if OutWindow and OutWindow.display:
cv.destroyAllWindows()
else:
file.close()
return 'OK'
"""特征提取的主函数"""
def feature(cap,kind='front',OutWindow=None,progressBar=None,root=None, skip_n=1, turn_start=1, turn_end=0, use_origin=False) -> 0|1:
"""
return: OK | stop
"""
if not use_origin:
return feature_template(cap,kind,OutWindow,progressBar,root,skip_n,turn_start,turn_end=turn_end)
initial_offset = 10
detect_offset = 60
cap.set(cv.CAP_PROP_POS_FRAMES, turn_start - 1)
frame_num = cap.get(7) # 获取视频总帧数
ret, frame0 = cap.read() # 读取第一帧
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))) # 获取视频尺寸
# size的格式:(x, y)
Idf = Identifier()
showinfo(message='请选择初始矩形框')
rtn_ = Idf.select_window(frame0)
(x,y,w,h), minis = rtn_ # minis未启用
if x < 0:
printb('用户取消', OutWindow)
return 'stop'
# 如果是展示模式,输出到窗口,否则打开文件句柄
if OutWindow and OutWindow.display:
printb("0 :", OutWindow)
else:
file = open('out-feature-1.txt','w') if kind == 'front' else open('out-feature-2.txt','w')
# domain = (y + h//2 - initial_offset,y + h//2 + initial_offset,x + w//2 - initial_offset,x + w//2 + initial_offset)
domain = (y - initial_offset, y + initial_offset, x - initial_offset, x + initial_offset)
max_angle = 0 # 初始的angle必须是0
# 初始化参数
stdoutpb = Stdout_progressbar(frame_num)
progressBar['maximum'] = frame_num
success = 1
# cnt = 0
cnt = turn_start - 1
cap.set(cv.CAP_PROP_POS_FRAMES, turn_start - 1)
pre_angle = 0
pre_state = 0 # init
max_value_thresh = MAX_VALUE_THRESH
# 或者为第一帧max_value的一半
# frame0 = cv2.GaussianBlur(frame0, (3,3), 0)
max_value = max_conv2d(cv.cvtColor(frame0, cv.COLOR_BGR2GRAY),domain,Idf.K, 0, OutWindow and OutWindow.display)[1]
# max_value_thresh = max_value//2
stdoutpb.reset(skip_n=skip_n)
while success: