-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrcs.py
2680 lines (1978 loc) · 111 KB
/
rcs.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
"""
This file supercedes all older versions of homography and coordinate system. It defines an
object for performing image to state plane conversions via homography and state plane
to roadway coordinate system conversions via spline curvilinear coordinate system conversion.
This object implements only initialization and conversion functions - tests and utils are in other scripts
"""
import os
import _pickle as pickle
import pandas as pd
import numpy as np
import torch
import glob
import cv2
import time
import string
import re
import copy
import sys
import csv
import matplotlib.pyplot as plt
import json
from scipy import interpolate
try:
import pyproj
from pyproj import Proj, transform
except ModuleNotFoundError:
print("Warning: no pyproj package detected, GPS conversion not enabled")
class I24_RCS:
#%% Utility functions
def line_to_point(line,point):
"""
Given a line defined by two points, finds the distance from that line to the third point
line - (x0,y0,x1,y1) as floats
point - (x,y) as floats
Returns
-------
distance - float >= 0
"""
numerator = np.abs((line[2]-line[0])*(line[1]-point[1]) - (line[3]-line[1])*(line[0]-point[0]))
denominator = np.sqrt((line[2]-line[0])**2 +(line[3]-line[1])**2)
return numerator / (denominator + 1e-08)
def safe_name(func):
"""
Wrapper function, catches camera names that aren't capitalized
"""
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except KeyError:
#print(args,kwargs)
if type(kwargs["name"]) == list:
kwargs["name"] = [item.upper() for item in kwargs["name"]]
elif type(kwargs["name"]) == str:
kwargs["name"] = kwargs["name"].upper()
return func(*args, **kwargs)
return new_func
#%% Initialization and Setup Functions
"""
3 coordinate systems are utilized in Curvilinear_Homography:
- image coordinates
- space coordinates (state plane coordinates) in feet
- roadway coordianates / curvilinear coordinates in feet
After fitting, each value of self.correspondence contains:
H - np array of size [3,3] used for image to space perspective transform
H_inv - used for space to image perspective transform on ground plane
P - np array of size [3,4] used for space to image transform
corr_pts - list of [x,y] points in image space that are fit for transform
space_pts - corresponding list of [x,y] points in space (state plane coordinates in feet)
state_plane_pts - same as space_pts but [x,y,id] (name is included)
vps - z vanishing point [x,y] in image coordinates
extents - xmin,xmax,ymin,ymax in roadway coordinates
extents_space - list of array of [x,y] points defining boundary in state plane coordinates
"""
def __init__(self,
save_path,
aerial_ref_dir = None,
im_ref_dir = None,
downsample = 1,
default = "dynamic"):
"""
Initializes homography object.
aerial_ref_dir -None or str - path to directory with csv files of attributes labeled in space coordinates
im_ref_dir - None or str - path to directory with cpkl files of attributes labeled in image coordinates
save_path - None or str - if str, specifies full_path to cached homography object, and no other files are required
default - str static or dynamic or reference
downsample
space_dir -
im_dir
"""
# intialize correspondence
self.downsample = downsample
self.polarity = 1
self.MM_offset = 0
self.save_file = save_path
self.default = default
self.hg_start_time = 0
self.hg_sec = 10
self.correspondence = {}
if save_path is not None and os.path.exists(save_path):
try:
with open(save_path,"rb") as f:
# everything in correspondence is pickleable without object definitions to allow compatibility after class definitions change
self.correspondence,self.median_tck,self.median_u,self.guess_tck,self.guess_tck2,self.MM_offset,self.all_splines,self.yellow_offsets,self.hg_sec,self.hg_start_time = pickle.load(f)
except:
with open(save_path,"rb") as f:
# everything in correspondence is pickleable without object definitions to allow compatibility after class definitions change
self.correspondence,self.median_tck,self.median_u,self.guess_tck,self.guess_tck2,self.MM_offset,self.all_splines,self.yellow_offsets = pickle.load(f)
# reload parameters of curvilinear axis spline
# rather than the spline itself for better pickle reloading compatibility
elif aerial_ref_dir is None:
raise IOError("aerial_im_dir must be specified unless save_path is given")
else:
# fit roadway coordinate spline
self.median_tck = None
self.median_u = None
self.guess_tck = None
self.guess_tck2 = None
self.all_splines = None
self.yellow_offsets = None
self._fit_spline(aerial_ref_dir)
self.save(save_path)
if im_ref_dir is not None:
try:
self.load_correspondences(im_ref_dir)
except:
aerial_file = os.path.join(aerial_ref_dir,"stateplane_all_points.cpkl")
for file in os.listdir(im_ref_dir):
if ".cpkl" not in file: continue
path = os.path.join(im_ref_dir,file)
self.generate_reference(aerial_file, path)
# object class info doesn't really belong in homography but it's unclear
# where else it should go, and this avoids having to pass it around
# for use in height estimation
if True:
self.class_dims = {
"sedan":[16,6,4],
"midsize":[18,6.5,5],
"van":[20,6,6.5],
"pickup":[20,6,5],
"semi":[55,9,14],
"truck (other)":[25,9,14],
"truck": [25,9,14],
"motorcycle":[7,3,4],
"trailer":[16,7,3],
"other":[18,6.5,5]
}
self.class_heights = dict([(key,self.class_dims[key][2]) for key in self.class_dims.keys()])
self.class_dict = { "sedan":0,
"midsize":1,
"van":2,
"pickup":3,
"semi":4,
"truck (other)":5,
"truck": 5,
"motorcycle":6,
"trailer":7,
0:"sedan",
1:"midsize",
2:"van",
3:"pickup",
4:"semi",
5:"truck (other)",
6:"motorcycle",
7:"trailer"
}
def save(self,save_file):
with open(save_file,"wb") as f:
pickle.dump([self.correspondence,self.median_tck,self.median_u,self.guess_tck,self.guess_tck2,self.MM_offset,self.all_splines,self.yellow_offsets,self.hg_sec,self.hg_start_time],f)
# def load_correspondence_old(self,im_ref_dir):
# """
# im_ref_dir - directory of directories of pickle files, each pickle file is a dictionary corresponding to and is loaded into self.correspondence
# """
# # dirs = os.listdir(im_ref_dir)
# # for subdir in dirs:
# # if not os.path.isdir(os.path.join(im_ref_dir,subdir)):
# # continue
# files = glob.glob(os.path.join(im_ref_dir, '*.cpkl'),recursive = True)
# for file in files:
# # match full name (group(x) gives you the parts inside the parentheses )
# camera_name = re.match('.*/(P\d\dC\d\d)\.cpkl', file).group(1)
# fp = os.path.join(im_ref_dir,file)
# # parse out relevant data from EB and WB sides
# with open(fp,"rb") as f:
# data = pickle.load(f)
# for side in ["EB","WB"]:
# side_data = data[side]
# corr = {}
# corr["P_reference"] = torch.from_numpy(side_data["P"])
# corr["H_reference"] = torch.from_numpy(side_data["H"])
# corr["FOV"] = side_data["FOV"]
# corr["mask"] = side_data["mask"]
# corr_name = "{}_{}".format(camera_name,side)
# self.correspondence[corr_name] = corr
# self.hg_sec = 1
# self.hg_start_time = 0
# if False: #temporary passthrough
# self.load_correspondences_WACV(im_ref_dir)
def load_correspondences(self,im_ref_dir):
"""
im_ref_dir - directory of directories of pickle files, each pickle file is a dictionary corresponding to and is loaded into self.correspondence
"""
# dirs = os.listdir(im_ref_dir)
# for subdir in dirs:
# if not os.path.isdir(os.path.join(im_ref_dir,subdir)):
# continue
files = glob.glob(os.path.join(im_ref_dir, 'hg_*.cpkl'),recursive = True)
for file in files:
# match full name (group(x) gives you the parts inside the parentheses )
camera_name = re.match('.*/hg_(P\d\dC\d\d)\.cpkl', file).group(1)
fp = os.path.join(im_ref_dir,file)
# parse out relevant data from EB and WB sides
with open(fp,"rb") as f:
data = pickle.load(f)
for side in ["EB","WB"]:
side_data = data[side]
if np.isnan(side_data["HR"].sum()):
continue
else:
corr = {}
corr["P_static"] = torch.from_numpy(side_data["PA"])
corr["H_static"] = torch.from_numpy(side_data["HA"])
corr["P_reference"] = torch.from_numpy(side_data["PR"])
corr["H_reference"] = torch.from_numpy(side_data["HR"])
corr["P_dynamic"] = torch.from_numpy(side_data["P"])
corr["H_dynamic"] = torch.from_numpy(side_data["H"])
corr["FOV"] = side_data["FOV"]
corr["mask"] = side_data["mask"]
corr["time"] = side_data["time"]
corr_name = "{}_{}".format(camera_name,side)
self.correspondence[corr_name] = corr
self.hg_sec = side_data["time"][1] - side_data["time"][0]
self.hg_start_time = side_data["time"][0]
if False: #temporary passthrough
self.load_correspondences_WACV(im_ref_dir)
def load_correspondences_WACV(self,im_ref_dir):
"""
For now, we'll load up the data from the WACV 1 hour save pickle and add the dynamic and static homographies to it
Then, generate a time method for indexing
"""
save_path = "/home/worklab/Documents/i24/fast-trajectory-annotator/final_dataset_preparation/CIRCLES_20_Wednesday_1hour.cpkl"
with open(save_path,"rb") as f:
# everything in correspondence is pickleable without object definitions to allow compatibility after class definitions change
self.correspondence,self.median_tck,self.median_u,self.guess_tck,self.guess_tck2,self.MM_offset,self.all_splines,self.yellow_offsets = pickle.load(f)
removals = []
# get all files in
for corr in self.correspondence:
print(corr)
if "old" in corr:
removals.append(corr)
continue
# remove old data
self.correspondence[corr].pop("P",None)
self.correspondence[corr].pop("H",None)
self.correspondence[corr].pop("H_inv",None)
# load static P and H
P_path = os.path.join(im_ref_dir,"static","P_{}.npy".format(corr))
P = torch.from_numpy(np.load(P_path))
H_path = os.path.join(im_ref_dir,"static","H_{}.npy".format(corr))
H = torch.from_numpy(np.load(H_path))
#P[:,2] *= -1
self.correspondence[corr]["P_static"] = P
self.correspondence[corr]["H_static"] = H
if torch.isnan(P.sum() + H.sum()):
print("No static hg for {}".format(corr))
# load reference P and H
P_path = os.path.join(im_ref_dir,"reference","P_{}.npy".format(corr))
P = torch.from_numpy(np.load(P_path))
H_path = os.path.join(im_ref_dir,"reference","H_{}.npy".format(corr))
H = torch.from_numpy(np.load(H_path))
#P[:,2] *= -1
self.correspondence[corr]["P_reference"] = P
self.correspondence[corr]["H_reference"] = H
if torch.isnan(P.sum() + H.sum()):
print("No reference hg for {}".format(corr))
removals.append(corr)
# load dynamic P and H
P_path = os.path.join(im_ref_dir,"dynamic","P_{}.npy".format(corr))
P = torch.from_numpy(np.load(P_path))
H_path = os.path.join(im_ref_dir,"dynamic","H_{}.npy".format(corr))
H = torch.from_numpy(np.load(H_path))
#P[:,2] *= -1
self.correspondence[corr]["P_dynamic"] = P
self.correspondence[corr]["H_dynamic"] = H
if torch.isnan(P.sum() + H.sum()):
print("No dynamic hg for {}".format(corr))
self.correspondence[corr] = copy.deepcopy(self.correspondence[corr])
# hg sec is the seconds between dynamic homographies and hg_start time is the timestamp for the 0th homography
self.hg_start_time = 0
self.hg_sec = 10
for removal in removals:
self.correspondence.pop(removal,None)
def generate_reference(self,aerial_file,cam_file):
camera = cam_file.split(".cpkl")[0].split("/")[-1]
# load aerial points
with open(aerial_file,"rb") as f:
aer_data = pickle.load(f)
# load cam points
with open(cam_file,"rb") as f:
cam_data = pickle.load(f)
for direction in ["EB","WB"]:
try:
im_pts = []
aer_pts = []
names = []
# get matching set of points
for point in cam_data[direction]["points"]:
key = point[2]
if key in aer_data.keys():
im_pts.append(point[0:2])
aer_pts.append(aer_data[key])
names.append(key)
# stack pts
im_pts = np.stack(im_pts)
aer_pts = np.stack(aer_pts)
# compute homography
cor = {}
cor["H"],_ = cv2.findHomography(im_pts,aer_pts)
cor["H_inv"],_ = cv2.findHomography(aer_pts,im_pts)
vp = cam_data[direction]["z_vp"]
# P is a [3,4] matrix
# column 0 - vanishing point for space x-axis (axis 0) in image coordinates (im_x,im_y,im_scale_factor)
# column 1 - vanishing point for space y-axis (axis 1) in image coordinates (im_x,im_y,im_scale_factor)
# column 2 - vanishing point for space z-axis (axis 2) in image coordinates (im_x,im_y,im_scale_factor)
# column 3 - space origin in image coordinates (im_x,im_y,scale_factor)
# columns 0,1 and 3 are identical to the columns of H,
# We simply insert the z-axis column (im_x,im_y,1) as the new column 2
P = np.zeros([3,4])
P[:,0] = cor["H_inv"][:,0]
P[:,1] = cor["H_inv"][:,1]
P[:,3] = cor["H_inv"][:,2]
P[:,2] = np.array([vp[0],vp[1],1]) * 10e-09
cor["P"] = P
# fit Z vp
self._fit_z_vp(cor,cam_data,direction)
# store correspodence - map into format expected by new rcs class which has dynamic, static and reference (but set non-reference as Nan)
corr = {}
corr["P_static"] = torch.from_numpy(cor["P"]) * torch.nan
corr["H_static"] = torch.from_numpy(cor["H"]) * torch.nan
corr["P_reference"] = torch.from_numpy(cor["P"])
corr["H_reference"] = torch.from_numpy(cor["H"])
corr["P_dynamic"] = None
corr["H_dynamic"] = None
corr["FOV"] = cam_data[direction]["FOV"]
if len(cam_data["EB"]["mask"]) > 0:
corr["mask"] = cam_data["EB"]["mask"]
else:
corr["mask"] = cam_data["WB"]["mask"]
corr["time"] = None
corr_name = "{}_{}".format(camera,direction)
self.correspondence[corr_name] = corr
except:
pass
def _fit_z_vp(self,cor,im_data,direction):
print("fitting Z coordinate scale")
P_orig = cor["P"].copy()
max_scale = 10000
granularity = 1e-12
upper_bound = max_scale
lower_bound = -max_scale
# create a grid of 100 evenly spaced entries between upper and lower bound
C_grid = np.linspace(lower_bound,upper_bound,num = 100,dtype = np.float64)
step_size = C_grid[1] - C_grid[0]
iteration = 1
while step_size > granularity:
best_error = np.inf
best_C = None
# for each value of P, get average reprojection error
for C in C_grid:
# scale P
P = P_orig.copy()
P[:,2] *= C
# search for optimal scaling of z-axis row
vp_lines = im_data[direction]["z_vp_lines"]
# get bottom point (point # 2)
points = torch.stack([ torch.tensor([vpl[2] for vpl in vp_lines]),
torch.tensor([vpl[3] for vpl in vp_lines]) ]).transpose(1,0)
t_points = torch.stack([ torch.tensor([vpl[0] for vpl in vp_lines]),
torch.tensor([vpl[1] for vpl in vp_lines]) ]).transpose(1,0)
heights = torch.tensor([vpl[4] for vpl in vp_lines]).unsqueeze(1)
# project to space
d = points.shape[0]
# convert points into size [dm,3]
points = points.view(-1,2).double()
points = torch.cat((points,torch.ones([points.shape[0],1],device=points.device).double()),1) # add 3rd row
H = torch.from_numpy(cor["H"]).transpose(0,1).to(points.device)
new_pts = torch.matmul(points,H)
# divide each point 0th and 1st column by the 2nd column
new_pts[:,0] = new_pts[:,0] / new_pts[:,2]
new_pts[:,1] = new_pts[:,1] / new_pts[:,2]
# drop scale factor column
new_pts = new_pts[:,:2]
# reshape to [d,m,2]
new_pts = new_pts.view(d,2)
# add third column for height
new_pts_shifted = torch.cat((new_pts,heights.double()),1)
# add fourth column for scale factor
new_pts_shifted = torch.cat((new_pts_shifted,torch.ones(heights.shape)),1)
new_pts_shifted = torch.transpose(new_pts_shifted,0,1).double()
# project to image
P = torch.from_numpy(P).double().to(points.device)
new_pts = torch.matmul(P,new_pts_shifted).transpose(0,1)
# divide each point 0th and 1st column by the 2nd column
new_pts[:,0] = new_pts[:,0] / new_pts[:,2]
new_pts[:,1] = new_pts[:,1] / new_pts[:,2]
# drop scale factor column
new_pts = new_pts[:,:2]
# reshape to [d,m,2]
repro_top = new_pts.view(d,-1,2).squeeze()
# get error
error = torch.pow((repro_top - t_points),2).sum(dim = 1).sqrt().mean()
# if this is the best so far, store it
if error < best_error:
best_error = error
best_C = C
# define new upper, lower with width 2*step_size centered on best value
#print("On loop {}: best C so far: {} avg error {}".format(iteration,best_C,best_error))
lower_bound = best_C - 2*step_size
upper_bound = best_C + 2*step_size
C_grid = np.linspace(lower_bound,upper_bound,num = 100,dtype = np.float64)
step_size = C_grid[1] - C_grid[0]
#print("New C_grid: {}".format(C_grid.round(4)))
iteration += 1
P_new = P_orig.copy()
P_new[:,2] *= best_C
cor["P"] = P_new
def _fit_spline(self,space_dir,use_MM_offset = True):
"""
Spline fitting is done by:
1. Assemble all points labeled along a yellow line in either direction
2. Fit a spline to each side of each line
3. Sample each spline at fine intervals
4. Use finite difference method to determine the distance along the spline for each fit point
5. Refit the splines, this time parameterizing the spline by these distances (u parameter in scipy.splprep)
5b. For each line, sample and define the set of points midway between
5c. For each line, define a separate spline fit to these points that defines the position of that lane as a function of x (along roadway)
6. Sample each yellow-line spline at fine intervals
7. Move along one spline and at each point, find the closest point on each other spline
8. Define a point on the median/ midpoint axis as the average on these 4 splines
9. Use the set of median points to define a new spline
10. Use the finite difference method to reparameterize this spline according to distance along it
11. Optionally, compute a median spline distance offset from mile markers
12. Optionally, recompute the same spline, this time accounting for the MM offset
space_dir - str - path to directory with csv files of attributes labeled in space coordinates
use_MM_offset - bool - if True, offset according to I-24 highway mile markers
"""
print("Fitting median spline..")
samples_per_foot = 12
splines = {}
# First, load all annotations
for direction in ["EB","WB"]:
for line_side in ["i","o"]:
### State space, do once
ae_x = []
ae_y = []
ae_id = []
# 1. Assemble all points labeled along a yellow line in either direction
for file in os.listdir(space_dir):
if direction.lower() not in file:
continue
# load all points
dataframe = pd.read_csv(os.path.join(space_dir,file))
try:
dataframe = dataframe[dataframe['point_pos'].notnull()]
attribute_name = file.split(".csv")[0]
feature_idx = dataframe["point_id"].tolist()
st_id = [attribute_name + "_" + item for item in feature_idx]
st_x = dataframe["x"].tolist()
st_y = dataframe["y"].tolist()
#st_x = dataframe["st_x"].tolist()
#st_y = dataframe["st_y"].tolist()
ae_x += st_x
ae_y += st_y
ae_id += st_id
except:
dataframe = dataframe[dataframe['side'].notnull()]
attribute_name = file.split(".csv")[0]
feature_idx = dataframe["id"].tolist()
side = dataframe["side"].tolist()
st_id = [attribute_name + str(side[i]) + "_" + str(feature_idx[i]) for i in range(len(feature_idx))]
st_x = dataframe["x"].tolist()
st_y = dataframe["y"].tolist()
#st_x = dataframe["st_x"].tolist()
#st_y = dataframe["st_y"].tolist()
ae_x += st_x
ae_y += st_y
ae_id += st_id
for line in ["yel{}".format(line_side), "d1{}".format(line_side),"d2{}".format(line_side),"d3{}".format(line_side)]:
#print("On line {} {}".format(line,direction))
ae_spl_x = []
ae_spl_y = []
ae_spl_u = [] # u parameterizes distance along spline
ae_spl_id = []
letter_to_side = {"a":"i",
"b":"i",
"c":"o",
"d":"o"
}
for i in range(len(ae_x)):
try:
if line in ae_id[i] or ( len(ae_id[i].split("_")) == 4 and line == ae_id[i].split("_")[1] + letter_to_side[ae_id[i].split("_")[3]]):
#if "yel{}".format(line_side) in ae_id[i]:
ae_spl_x.append(ae_x[i])
ae_spl_y.append(ae_y[i])
ae_spl_id.append(ae_id[i])
except KeyError:
pass
# if possible, use spline to smooth points
# if self.median_tck is not None:
# ae_spl_x,ae_spl_y,ae_spl_id = self.shift_aerial_points2( ae_spl_x,ae_spl_y,ae_spl_id)
# 2. Fit a spline to each of EB, WB inside and outside
# find a sensible smoothness parameter
# compute the yellow line spline in state plane coordinates (sort points by y value since road is mostly north-south)
ae_data = np.stack([np.array(ae_spl_x),np.array(ae_spl_y)])
ae_data,idx = np.unique(ae_data,axis = 1,return_index = True)
order = np.argsort(ae_data[0,:])
ae_data2 = ae_data[:,order]#[::-1]]
order2 = np.argsort(ae_data[0,:])
ae_data = ae_data2.copy()
# 3. Sample the spline at fine intervals
# get spline and sample points on spline
w = np.ones(ae_data.shape[1])
ae_spl_x = [ae_spl_x[i] for i in idx]
ae_spl_y = [ae_spl_y[i] for i in idx]
ae_spl_id = [ae_spl_id[i] for i in idx]
# for dim in [0,1]:
# width = 13
# extend1 = torch.ones((width-1)//2) * ae_data[dim,0]
# extend2 = torch.ones((width-1)//2) * ae_data[dim,-1]
# ys_extended = torch.cat([extend1,torch.from_numpy(ae_data[dim,:]),extend2])
# smoother = np.hamming(width)
# smoother = smoother/ sum(smoother)
# ys = np.convolve(ys_extended,smoother,mode = "valid")
# ae_data[dim,:] = ys
knot_spacing = 0
s0 = 0.1
try:
ae_tck, ae_u = interpolate.splprep(ae_data.astype(float), s=s0, w = w, per=False)
except ValueError as e:
print(e)
span_dist = np.sqrt((ae_spl_x[0] - ae_spl_x[-1])**2 + (ae_spl_y[0] - ae_spl_y[-1])**2)
ae_x_prime, ae_y_prime = interpolate.splev(np.linspace(0, 1, int(span_dist*samples_per_foot)), ae_tck)
# TEMP
# plt.plot(ae_data[0,:],ae_data[1,:], "o-")
# legend.append(direction + "_" + line_side)
# 4. Use finite difference method to determine the distance along the spline for each fit point
fd_dist = np.concatenate( (np.array([0]), ((ae_x_prime[1:] - ae_x_prime[:-1])**2 + (ae_y_prime[1:] - ae_y_prime[:-1])**2)**0.5),axis = 0) # by convention fd_dist[0] will be 0, so fd_dist[i] = sum(int_dist[0:i])
integral_dist = np.cumsum(fd_dist)
# for each fit point, find closest point on spline, and assign it the corresponding integral distance
for p_idx in range(len(ae_spl_x)):
# I think these should instead reference ae_data because that one has been sorted
#px = ae_spl_x[p_idx]
#py = ae_spl_y[p_idx]
px = ae_data[0,p_idx]
py = ae_data[1,p_idx]
dist = ((ae_x_prime - px)**2 + (ae_y_prime - py)**2)**0.5
min_dist,min_idx= np.min(dist),np.argmin(dist)
ae_spl_u.append(integral_dist[min_idx])
# 5. Refit the splines, this time parameterizing the spline by these distances (u parameter in scipy.splprep)
#ae_spl_u.reverse()
# sort by increasing u
ae_spl_u = np.array(ae_spl_u)
sorted_idxs = np.argsort(ae_spl_u)
ae_spl_u = ae_spl_u[sorted_idxs]
ae_data = ae_data[:,sorted_idxs]
while True and knot_spacing < 10:
s0 *= 1.2
tck, u = interpolate.splprep(ae_data.astype(float), s=s0, w = w, u = ae_spl_u)
knots = tck[0]
knot_spacing = np.min(np.abs(knots[5:-4] - knots[4:-5]))
#print(knot_spacing,s0)
tck, u = interpolate.splprep(ae_data.astype(float), s=s0, w = w, u = ae_spl_u)
splines["{}_{}_{}".format(line,direction,line_side)] = [tck,u]
# to prevent any bleedover
del dist, min_dist, min_idx, ae_spl_y,ae_spl_x, ae_spl_u, ae_data
import matplotlib.pyplot as plt
plt.figure()
legend = []
# 6. Sample each of the 4 splines at fine intervals
for key in splines:
tck,u = splines[key]
span_dist = np.abs(u[0] - u[-1])
x_prime, y_prime = interpolate.splev(np.linspace(u[0], u[-1], int(span_dist)), tck)
splines[key].append(x_prime)
splines[key].append(y_prime)
plt.plot(x_prime,y_prime)
legend.append(key)
###### Now, for each pair of splines, sample each and get a midway spline. These will be the splines we use
for direction in ["EB","WB"]:
for line in ["yel","d1","d2","d3"]:
new_key = "{}_{}_center".format(direction,line)
print("Getting smooth centered spline for {}".format(new_key))
for key in splines.keys():
if direction in key and line in key and "i" in key:
i_spline = splines[key][0] # just tck
elif direction in key and line in key and "o" in key:
o_spline = splines[key][0] # just tck
u_range = np.linspace(np.min(splines[key][1]), np.max(splines[key][1]), 50)
# sample each spline at fine interval
#u_range = np.array(med_spl_u )
# sample each spline at the same points
x_in,y_in = np.array(interpolate.splev(u_range,i_spline))
x_out, y_out = np.array(interpolate.splev(u_range,o_spline))
# average the two points
y_mid = (y_in + y_out)/2
x_mid = (x_in + x_out )/2
data = np.stack([x_mid,y_mid])
# fit spline y(u)
s0 = 0.1
knot_spacing = 0
while knot_spacing < 100: # adjust spline smoothness for each center line
s0 *= 1.25
mid_line_tck,mid_line_u = interpolate.splprep(data, s=s0, u = u_range)
knots = mid_line_tck[0]
knot_spacing = np.min(np.abs(knots[5:-4] - knots[4:-5]))
#print(knot_spacing,s0)
# store
splines[new_key] = [mid_line_tck,mid_line_u]
# plot
x_prime, y_prime = interpolate.splev(np.linspace(u_range[0], u_range[-1], 5000), mid_line_tck)
splines[new_key].append(x_prime)
splines[new_key].append(y_prime)
plt.plot(x_prime,y_prime)
legend.append(new_key)
# plt.legend(legend)
# plt.show()
# # cache spline for each lane for plotting purposes
# self.all_splines = splines
# return
med_spl_x = []
med_spl_y = []
print("sampling yellow line splines")
# 7. Move along one spline and at each point, find the closest point on each other spline
# by default, we'll use EB_o as the base spline
for main_key in ["yelo_EB_o","yeli_EB_i","yelo_WB_o","yeli_WB_i"]:
#for main_key in ["yelo_WB_o","yeli_WB_i"]:
main_spl = splines[main_key]
main_x = main_spl[2]
main_y = main_spl[3]
for p_idx in range(len(main_x)):
px,py = main_x[p_idx],main_y[p_idx]
points_to_average = [np.array([px,py])]
for key in splines:
if key != main_key:
if key not in ["yelo_WB_o","yeli_WB_i","yelo_EB_o","yeli_EB_i"]: continue
arr_x,arr_y = splines[key][2], splines[key][3]
dist = np.sqrt((arr_x - px)**2 + (arr_y - py)**2)
min_dist,min_idx= np.min(dist),np.argmin(dist)
points_to_average.append( np.array([arr_x[min_idx],arr_y[min_idx]]))
if len(points_to_average) < 4:
print("Outlier removed")
continue
med_point = sum(points_to_average)/len(points_to_average)
# 8. Define a point on the median/ midpoint axis as the average on these 4 splines
med_spl_x.append(med_point[0])
med_spl_y.append(med_point[1])
print("Done sampling")
# 9. Use the set of median points to define a new spline
# sort by increasing x
med_data = np.stack([np.array(med_spl_x),np.array(med_spl_y)])
med_data = med_data[:,np.argsort(med_data[0])]
# remove weirdness (i.e. outlying points) s.t. both x and y are monotonic and strictly increasing
keep = (med_data[1,1:] < med_data[1,:-1]).astype(int).tolist()
keep = [1] + keep
keep = np.array(keep)
med_data = med_data[:,keep.nonzero()[0]]
keep = (med_data[0,1:] > med_data[0,:-1]).astype(int).tolist()
keep = [1] + keep
keep = np.array(keep)
med_data = med_data[:,keep.nonzero()[0]]
#med_data = np.ascontiguousarray(med_data)
s = 10
n_knots = len(med_data[0])
while n_knots > 300:
med_tck,med_u = interpolate.splprep(med_data, s=s, per=False)
n_knots = len(med_tck[0])
s = s**1.2
print("Fitting median spline, n_knots = {}".format(n_knots))
# 10. Use the finite difference method to reparameterize this spline according to distance along it
med_spl_x = med_data[0]
med_spl_y = med_data[1]
span_dist = np.sqrt((med_spl_x[0] - med_spl_x[-1])**2 + (med_spl_y[0] - med_spl_y[-1])**2)
med_x_prime, med_y_prime = interpolate.splev(np.linspace(0, 1, int(span_dist*samples_per_foot)), med_tck)
med_fd_dist = np.concatenate( (np.array([0]), ((med_x_prime[1:] - med_x_prime[:-1])**2 + (med_y_prime[1:] - med_y_prime[:-1])**2)**0.5),axis = 0) # by convention fd_dist[0] will be 0, so fd_dist[i] = sum(int_dist[0:i])
med_integral_dist = np.cumsum(med_fd_dist)
# for each fit point, find closest point on spline, and assign it the corresponding integral distance
med_spl_u = []
print("Getting integral distance along median spline")
for p_idx in range(len(med_data[0])):
px,py = med_data[0,p_idx], med_data[1,p_idx]
dist = ((med_x_prime - px)**2 + (med_y_prime - py)**2)**0.5
min_dist,min_idx= np.min(dist),np.argmin(dist)
med_spl_u.append(med_integral_dist[min_idx])
# sort by increasing u I guess
med_spl_u = np.array(med_spl_u)
sorted_idxs = np.argsort(med_spl_u)
med_spl_u = med_spl_u[sorted_idxs]
med_data = med_data[:,sorted_idxs]
# sort by strictly increasing u
keep = (med_spl_u[1:] > med_spl_u[:-1]).astype(int).tolist()
keep = [1] + keep
keep = np.array(keep)
med_data = med_data[:,keep.nonzero()[0]]
med_spl_u = med_spl_u[keep.nonzero()[0]]
import matplotlib.pyplot as plt
#plt.figure(figsize = (20,20))
plt.plot(med_data[0],med_data[1])
legend.append("Median")
smoothing_dist = 500
max_allowable_dev = 1
# at this point, we have the median data and the integrated median distances (med_spl_u) and med_data
# Let's try simply finding a single spline with <smoothing_dist> spaced fit-points and high-weighted edges
# plt.figure()
# plt.plot(med_spl_u)
# plt.plot(np.array(med_spl_u)[np.argsort(med_spl_u)])
# plt.legend(["Unsorted","Sorted"])
s = 8
min_dist = 0
max_dev = 0
while min_dist < smoothing_dist and max_dev < max_allowable_dev:
final_tck,final_u = interpolate.splprep(med_data.astype(float), s=s, u=med_spl_u)
knots = final_tck[0]
min_dist = np.min(np.abs(knots[4:] - knots[:-4]))
current_x,current_y = interpolate.splev(med_spl_u,final_tck)
dist = ((current_x - med_data[0,:])**2 + (current_y - med_data[1,:])**2)**0.5
max_dev = np.max(dist)
print("With s = {}, {} knots, and min knot spacing {}, max spline - median point deviation = {}".format(s,len(knots),min_dist,max_dev))
s = s**1.1
#final_tck, final_u = interpolate.splprep(med_data, u = med_spl_u)
self.median_tck = final_tck
self.median_u = final_u
# sample for final plotting
final_plot_x,final_plot_y = interpolate.splev(np.linspace(min(med_spl_u), max(med_spl_u), 2000), final_tck)
plt.plot(final_plot_x,final_plot_y)
legend.append("Final Spline")
# cache spline for each lane for plotting purposes
self.all_splines = splines
### get the inverse spline g(x) = u for guessing initial spline point
med_spl_u = np.array(med_spl_u)
print(med_data.shape,med_spl_u.shape)
# get guess_tck from all sparse
if True:
med_data = np.array([final_plot_x,final_plot_y])
med_spl_u = np.linspace(min(med_spl_u), max(med_spl_u), 2000)