This repository was archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnavigation.py
914 lines (650 loc) · 23.2 KB
/
navigation.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
"""
Implementation of navigation modules and algorithms.
"""
###########
# Imports #
###########
import cv2
import math
import numpy as np
import torch
import torchvision.transforms as transforms
from abc import ABC, abstractmethod
from functools import partial
from itertools import product
from typing import List, Tuple, Union
from analysis.markers import ArucoOpenCV, QROpenCV, QRZBar
from analysis.vanishing_point import VPClassic, VPEdgelets
from .controllers import Controller
from .environment import Environment
from learning.models import DenseNet, SmallConvNet, UNet, MiDaS
##########
# Typing #
##########
Image = np.array
###########
# Classes #
###########
# Modules
# - Abstract class
class NavModule(ABC):
"""
Abstract class used to define a navigation module.
A navigation module is a component of a navigation algorithm. It performs
several actions on drone input(s) and returns some information or directly
acts on the drone.
Each navigation module must inherit this class.
"""
def __init__(self, verbose: bool = False):
super().__init__()
self.verbose = verbose
def log(self, message: str):
"""
Display a message in console if verbose flag is enabled.
"""
if self.verbose:
print(f'[{self.__class__.__name__}] {message}')
@abstractmethod
def run(self, **kwargs) -> Union[object, None]:
"""
Take as inputs some data of the drone (image, IMU data, etc) and return
some information (action, position, etc) or directly act on the drone.
"""
pass
# - Analysis
class VanishingModule(NavModule):
"""
Abstract class used to define navigation module that works with vanishing
point.
"""
def __init__(self, controller: Controller, verbose=False):
super().__init__(verbose)
self.controller = controller
# Define adjustment actions
self.adjustments = {
'left': partial(self.controller.rotate, 'cw', 5),
'right': partial(self.controller.rotate, 'ccw', 5)
}
@abstractmethod
def _alignment(self, img: Image) -> str:
"""
Determine the alignment of the drone (left, right or center) based on
an image.
"""
pass
# Abstract interface of parent class
def run(self, img: Image):
while True:
alignment = self._alignment(img)
if alignment == 'center':
break
self.adjustments.get(alignment)()
img = self.controller.picture()
class AnalysisVanishingModule(VanishingModule):
"""
Module that adjusts the drone by estimating its alignment based on a
vanishing point detection using pure computer vision method.
"""
def __init__(self, detector_id: str, controller, verbose=False):
super().__init__(controller, verbose)
# Vanishing point detector
detectors = {
'classic': VPClassic,
'edgelets': VPEdgelets
}
self.detector = detectors.get(detector_id)()
# Bounds
self.lower, self.upper = None, None
# Abstract interface
def _alignment(self, img):
# Define bounds, if not defined
if self.lower is None:
h, w, _ = img.shape
mean, std = w / 2, w / 25
self.lower = (mean - 4 * std, mean - std)
self.upper = (mean + std, mean + 4 * std)
# Detect vanishing point
x, _ = self.detector.detect(img)
# Get alignment
alignment = 'center'
if self.upper[0] < x < self.upper[1]:
alignment = 'left'
elif self.lower[0] < x < self.lower[1]:
alignment = 'right'
self.log(f'Alignment: {alignment}')
return alignment
class MarkerModule(NavModule):
"""
Module that reads the content of a marker, if any, and returns it along
with coordinates of its corner points.
"""
def __init__(self, decoder_id: str, verbose=False):
super().__init__(verbose)
# Marker decoder
decoders = {
'aruco_opencv': ArucoOpenCV,
'qr_opencv': QROpenCV,
'qr_zbar': QRZBar
}
self.decoder = decoders.get(decoder_id)()
# Abstract interface
def run(self, img: Image) -> Tuple[str, List]:
decoded, pts = self.decoder.decode(img)
self.log(f'Decoded: {decoded}')
return decoded, pts
# - Deep Learning
class DeepModule(NavModule):
"""
Module that returns the output of a neural network using an image from the
drone as input.
"""
def __init__(
self,
n_channels: int,
model_id: str,
weights_pth: str,
verbose=False
):
super().__init__(verbose)
# Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
self.device = device
self.log(f'Device: {device}')
# Model
models = {
'densenet121': partial(DenseNet, densenet_id='121'),
'densenet161': partial(DenseNet, densenet_id='161'),
'small': SmallConvNet,
'unet': UNet,
'midas': MiDaS
}
model = models.get(model_id)(3, n_channels)
model = model.to(device)
if model_id != 'midas':
model.load_state_dict(torch.load(weights_pth, map_location=device))
model.eval()
self.model = model
# GPU warm-up
if torch.cuda.is_available():
with torch.no_grad():
for _ in range(10):
if model_id == 'midas':
dummy = torch.randn(1, 3, 224, 384)
else:
dummy = torch.randn(1, 3, 180, 320)
_ = self.model(dummy.to(self.device))
# Processing
size = (384, 224) if model_id == 'midas' else (320, 180)
self.preprocess = transforms.Compose([
lambda x: cv2.resize(x, size),
transforms.ToTensor()
])
self.to_list = transforms.Compose([
lambda x: torch.flatten(x),
lambda x: x.numpy()
])
self.to_img = transforms.Compose([
transforms.ToPILImage(),
lambda x: np.array(x)
])
# Abstract interface
def run(self, img: Image) -> np.array:
img = self.preprocess(img)
with torch.no_grad():
img = img.unsqueeze(0)
img = img.to(self.device)
pred = self.model(img).cpu()
pred = self.to_img(pred) if pred.dim() == 3 else self.to_list(pred)
self.log(f'Prediction: {pred}')
return pred
class DeepVanishingModule(VanishingModule):
"""
Module that adjusts the drone by estimating its alignment based on a
vanishing point detection using Deep Learning method.
"""
def __init__(
self,
grid_size: int,
model_id: str,
weights_pth: str,
controller,
verbose=False
):
super().__init__(controller, verbose)
# Deep module
self.deep = DeepModule(
n_channels=grid_size,
model_id=model_id,
weights_pth=weights_pth,
verbose=False
)
# Define middle cell and length of grid side
self.middle = math.floor(grid_size / 2)
self.side = math.sqrt(grid_size)
# Define left and right cells
bounds = [-self.side, 0, self.side]
self.left = [sum(x) for x in zip([self.middle + 1] * 3, bounds)]
self.right = [sum(x) for x in zip([self.middle - 1] * 3, bounds)]
# Abstract interface
def _alignment(self, img):
# Get cell that contains vanishing point
pred = self.deep.run(img)
cell = np.argmax(pred)
# Get alignment
alignment = 'center'
if cell in self.left:
alignment = 'left'
elif cell in self.right:
alignment = 'right'
self.log(f'Alignment: {alignment}')
return alignment
class DepthModule(NavModule):
"""
Module that infers depth map associated to an image and compute mean depth
of different areas in the image.
"""
def __init__(self, n: int = 3, verbose=False):
super().__init__(verbose)
# Deep module
self.deep = DeepModule(
n_channels=2, # dummy
model_id='midas',
weights_pth='', # dummy
verbose=False
)
# Grid size
self.n = n
# Abstract interface
def run(self, img: Image) -> float:
# Get depth map associated to image
depth = self.deep.run(img=img)
# Dimensions
h, w = depth.shape
# Split the image in cells and compute mean depth of each
cell = (w // self.n, h // self.n)
means = []
for (j, i) in product(range(self.n), range(self.n)):
left = i * cell[0]
right = (i + 1) * cell[0]
bottom = j * cell[1]
top = (j + 1) * cell[1]
cropped = depth[bottom:top, left:right]
means.append(np.mean(cropped))
self.log(f'Mean depths: {means}')
return means
# - Staircase
class StaircaseNaiveModule(NavModule):
"""
Module that moves the drone in a staircase (up or down).
"""
def __init__(self, controller: Controller, verbose=False):
super().__init__(verbose)
self.controller = controller
# Abstract interface
def run(self, img: Image, direction: str):
self.controller.move(direction, 30)
self.controller.move('forward', 30)
class StaircaseDepthModule(NavModule):
"""
Module that moves the drone in a staircase (up or down) based on relative
depth map estimation.
"""
def __init__(self, controller: Controller, verbose=False):
super().__init__(verbose)
self.controller = controller
# Depth module
self.depth = DepthModule(n=3, verbose=False)
# Threshold
self.threshold = 200
# Abstract interface
def run(self, img: Image, direction: str):
while True:
# Get mean depth estimations
means = self.depth.run(img=img)
# Compute depth of each zone
means = np.array(means)
top = np.mean(means[0:3])
center = np.mean(means[3:6])
bottom = np.mean(means[6:9])
# Move the drone
self.controller.move(direction, 30)
if top + self.threshold > center >= bottom:
self.controller.move(direction, 30)
else:
break
# Take a new picture
img = self.controller.picture()
class StaircaseMarkerModule(NavModule):
"""
Module that moves the drone in a staircase (up or down) based on marker
detection.
"""
def __init__(self, controller: Controller, verbose=False):
super().__init__(verbose)
self.controller = controller
# Marker module
self.marker = MarkerModule(decoder_id='aruco_opencv', verbose=True)
# (Known) width of the marker
self.width = 10
# Focal length
self.f = 1540
# Abstract interface
def run(self, img: Image, direction: str):
while True:
# Decode marker, if any
decoded, pts = self.marker.run(img=img)
# If no marker is detected, stop
if decoded is None:
break
# Perceived width
p = pts[2][0] - pts[3][0]
# Distance to marker
d = (self.width * self.f) / p
# Position of the middle points
h, _, _ = img.shape
mid_image = h // 2
mid_marker = np.mean([pts[0][1], pts[2][1]])
# Move the drone
threshold = h // 10
limits = [mid_image - threshold, mid_image + threshold]
if mid_marker > limits[0] and mid_marker < limits[1]:
self.controller.move('forward', max(0, d - 30))
self.controller.move(direction, 30)
# Take a new picture
img = self.controller.picture()
# Navigation algorithms
# - Abstract class
class NavAlgorithm(ABC):
"""
Abstract class used to define a navigation algorithm.
A navigation algorithm is an algorithm, based on an environment
representation and possibly navigation module(s), that moves automatically
the drone from its initial position to an objective defined.
Each navigation algorithm must inherit this class.
"""
def __init__(
self,
env: Environment,
controller: Controller,
show: bool = False
):
super().__init__()
self.env = env
self.controller = controller
self._show = show
# Path and associated sequence of actions
self.path = env.path()
self.sequence = env.path_to_seq(self.path)
# Key points of the environment
self._keypoints = self.env.extract_keypoints(self.path, self.sequence)
self._keypoints_idx = 0
# Possible actions of the drone
self.actions = {
'forward': lambda d: self.controller.move('forward', d),
'left': lambda a: self.controller.rotate('ccw', a),
'right': lambda a: self.controller.rotate('cw', a)
}
# Define custom steps for each action
self.steps = {'forward': 100, 'left': 90, 'right': 90}
# Common modules used by algorithms
self.vanishing = AnalysisVanishingModule(
detector_id='classic',
controller=self.controller,
verbose=True
)
self.staircase = StaircaseNaiveModule(
controller=self.controller,
verbose=True
)
# Define reference steps and counters for each action (according to
# environment representation precision) to properly update the agent
# position in environment representation
self._refs = {'forward': 100, 'left': 90, 'right': 90}
self._counters = {'forward': 0, 'left': 0, 'right': 0}
# Environment representation
def _env_move(self, action: str, **kwargs):
"""
Move the agent in the environment representation according to steps
defined.
"""
# Update counter
self._counters[action] += 1
# Define step and times
ref = self._refs[action]
now = self.steps[action]
step = int(ref / now) if ref > now else 1
times = 1 if ref > now else int(now / ref)
# Update agent in environment, if necessary
if step == 1 or self._counters[action] % step:
self.env.move(action=action, times=times, **kwargs)
def _env_update(self, pos: Tuple, **kwargs):
"""
Update the position of the agent in the environment representation.
"""
# Reset all counters
for key in self._counters.keys():
self._counters[key] = 0
# Update agent in environment
self.env.update(pos=pos, **kwargs)
def _env_show(self, **kwargs):
"""
Show the environment representation if flag is enabled.
"""
if self._show:
self.env.render(**kwargs)
# Navigation
@abstractmethod
def _is_keypoint(self, img: Image) -> bool:
"""
Define if the drone has reached a key point or not based on an image.
Each navigation algorithm must implement this method.
"""
pass
def _execute(self):
"""
Define how the drone executes actions during the navigation process.
By default, it uses images of the drone to determine next action by
checking if the drone has reach a key point or not.
This method can be override if the navigation algorithm has to work
differently.
"""
while not self.env.has_reached_obj():
img = self.controller.picture()
# Check if drone has reach a key point
#
# To add the '+ Env' verification:
# [...] and self.env.nearest_keypoint(self._keypoints) < 2:
if self._is_keypoint(img):
action, pos = self._keypoints[self._keypoints_idx]
self._keypoints_idx += 1
self._env_update(pos)
else:
# Align drone using vanishing point
self.vanishing.run(img=img)
action = 'forward'
# Execute action
if action in ['up', 'down']:
self.staircase.run(img, action)
else:
self.actions.get(action)(self.steps.get(action))
self._env_move(action)
# Show updated environment
self._env_show(path=self.path, what=['pos', 'obj'])
def navigate(self):
"""
Move automatically the drone from its initial position to an objective.
This navigation process follow a general template: the drone takes off,
executes actions and lands.
"""
# Show the environment
self._env_show(path=self.path, what=['pos', 'obj'])
# Take off
self.controller.arm()
self.controller.takeoff()
# Execute actions
self._execute()
# Land
self.controller.land()
self.controller.disarm()
# Keep environment open
self.env.keep()
# - Naive algorithms used for tests; unusable in real life
class NaiveAlgorithm(NavAlgorithm):
"""
Navigation algorithm based solely on optimal path finded and actions
associated.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Abstract interface
def _is_keypoint(self, img):
# Dummy implementation to respect abstract interface
return False
# Override how drone executes actions
def _execute(self):
# Group sequence of actions
grouped = self.env.group_seq(self.sequence)
# Execute each action
for action, times in grouped:
self.actions.get(action)(self._refs.get(action) * times)
self.env.move(action, times)
# Show updated environment
self._env_show(path=self.path, what=['pos', 'obj'])
class VanishingAlgorithm(NavAlgorithm):
"""
Navigation algorithm based solely on vanishing point detection method and
environment information.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Turn actions
self.turn_actions = ['left', 'right']
# Abstract interface
def _is_keypoint(self, img):
# Dummy implementation to respect abstract interface
return False
# Override how drone executes actions
def _execute(self):
# Execute action, adjusted with vanishing point
for action in self.sequence:
if action not in self.turn_actions:
img = self.controller.picture()
self.vanishing.run(img=img)
self.actions.get(action)(self._refs.get(action))
self.env.move(action)
# Show updated environment
self._env_show(path=self.path, what=['pos', 'obj'])
# - Real navigation algorithms, possibly usable in real life
class VisionAlgorithm(NavAlgorithm):
"""
Navigation algorithm that uses predictions of Deep Learning model to
determine if drone has reached a key point or not.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Deep module
self.deep = DeepModule(
n_channels=2,
model_id='densenet161',
weights_pth='densenet161.pth',
verbose=True
)
# Threshold of confidence
self.threshold = 0.5
# Abstract interface
def _is_keypoint(self, img):
pred = self.deep.run(img=img)
return pred[1] > self.threshold
class MarkerAlgorithm(NavAlgorithm):
"""
Navigation algorithm that uses marker detection and decoding to determine
if drone has reached a key point or not.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Marker module
self.marker = MarkerModule(decoder_id='aruco_opencv', verbose=True)
# Focal length of the camera (to adapt according to the camera!)
self.f = 1540
# (Known) width of the marker used (in cm)
self.width = 10
# Threshold on distance (in cm)
self.threshold = 100
# Abstract interface
def _is_keypoint(self, img):
decoded, pts = self.marker.run(img=img)
if decoded == '1':
# Perceived width
p = pts[2][0] - pts[3][0]
# Distance to marker
d = (self.width * self.f) / p
return d <= self.threshold
return False
class DepthAlgorithm(NavAlgorithm):
"""
Navigation algorithm that uses depth map associated to an image to
determine if drone has reached a key point or not.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Grid size
n = 3
# Depth module
self.depth = DepthModule(n=n, verbose=True)
# Middle cell
self.middle = math.floor((n ** 2) / 2)
# Threshold
self.threshold = 500
# Abstract interface
def _is_keypoint(self, img):
means = self.depth.run(img=img)
keypoint = False
for idx, value in enumerate(means):
if idx == self.middle:
pass
else:
if means[self.middle] - value < self.threshold:
keypoint = True
return keypoint
class VisionDepthAlgorithm(NavAlgorithm):
"""
Navigation algorithm that uses vision of the drone and depth estimation to
determine if drone has reached a key point or not.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Vision algorithm
self.vision = VisionAlgorithm(env, controller, show)
# Depth algorithm
self.depth = DepthAlgorithm(env, controller, show)
# Abstract interface
def _is_keypoint(self, img):
return self.vision._is_keypoint(img) and self.depth._is_keypoint(img)
class VisionMarkerAlgorithm(NavAlgorithm):
"""
Navigation algorithm that uses vision of the drone and marker detection to
determine if drone has reached a key point or not.
"""
def __init__(self, env, controller, show=False):
super().__init__(env, controller, show)
# Deep module
self.deep = DeepModule(
n_channels=2,
model_id='densenet161',
weights_pth='densenet161.pth',
verbose=True
)
# Threshold of confidence
self.threshold = 0.8
# Marker algorithm
self.marker = MarkerAlgorithm(env, controller, show)
# Abstract interface
def _is_keypoint(self, img):
pred = self.deep.run(img=img)
if pred[1] >= self.threshold:
return True
elif pred[1] > 0.5 and pred[1] < self.threshold:
return self.marker._is_keypoint(img)
return False