jacodd commited on
Commit
9869d0d
·
verified ·
1 Parent(s): 96930e3

Upload 37 files

Browse files
Files changed (37) hide show
  1. experiments/image2image/image2image.py +110 -0
  2. experiments/image2image/image_similarity.py +605 -0
  3. experiments/image2image/image_similarity_all.py +546 -0
  4. experiments/image2image/input/Gemini.png +3 -0
  5. experiments/image2image/input/cut.png +3 -0
  6. experiments/image2image/input/depth.npy +3 -0
  7. experiments/image2image/input/diffuser.png +3 -0
  8. experiments/image2image/input/isaacsim.jpg +3 -0
  9. experiments/image2image/input/others/CUT.png +3 -0
  10. experiments/image2image/input/others/Gemini.jpg +3 -0
  11. experiments/image2image/input/others/isaacsim2.png +3 -0
  12. experiments/image2image/input/others/phone1.jpg +3 -0
  13. experiments/image2image/input/real.jpg +3 -0
  14. experiments/image2image/input/rosario.jpg +3 -0
  15. experiments/image2image/output/similarity_heatmap_fid.png +3 -0
  16. experiments/rtabmap/behavior_trees/navigate_through_poses_w_replanning_and_recovery.xml +38 -0
  17. experiments/rtabmap/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml +36 -0
  18. experiments/rtabmap/nav2.launch.py +52 -0
  19. experiments/rtabmap/params/nav2_params.yaml +468 -0
  20. experiments/rtabmap/params/odom.txt +321 -0
  21. experiments/rtabmap/params/route.yaml +421 -0
  22. experiments/rtabmap/params/route2.yaml +68 -0
  23. experiments/rtabmap/params/slam.txt +398 -0
  24. experiments/rtabmap/params/u_route.yaml +421 -0
  25. experiments/rtabmap/rtab_odom.launch.py +110 -0
  26. experiments/rtabmap/scripts/follow_route.py +163 -0
  27. experiments/rtabmap/scripts/generate_route.py +121 -0
  28. experiments/rtabmap/scripts/navigator.py +150 -0
  29. experiments/semantic_segmentation/inference_2d_semantic.py +143 -0
  30. experiments/semantic_segmentation/rosario/01.jpg +3 -0
  31. experiments/semantic_segmentation/rosario/02.jpg +3 -0
  32. experiments/semantic_segmentation/rosario/03.jpg +3 -0
  33. experiments/semantic_segmentation/rosario/04.jpg +3 -0
  34. experiments/semantic_segmentation/rosario/05.jpg +3 -0
  35. experiments/semantic_segmentation/rosario/06.jpg +3 -0
  36. experiments/semantic_segmentation/train_2d_semantic.py +294 -0
  37. experiments/semantic_segmentation/unet_efficientnetb3_semantic.pth +3 -0
experiments/image2image/image2image.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import cv2
4
+ from PIL import Image
5
+ from diffusers import (
6
+ StableDiffusionControlNetPipeline,
7
+ ControlNetModel,
8
+ UniPCMultistepScheduler,
9
+ AutoencoderKL,
10
+ StableDiffusionControlNetImg2ImgPipeline
11
+ )
12
+
13
+ # 1. Load both ControlNet models
14
+ controlnets = [
15
+ ControlNetModel.from_pretrained("lllyasviel/control_v11f1p_sd15_depth", torch_dtype=torch.float16),
16
+ ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_canny", torch_dtype=torch.float16)
17
+ ]
18
+
19
+ # 2. Load the base pipeline with the high-quality VAE
20
+ vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
21
+ # pipe = StableDiffusionControlNetPipeline.from_pretrained(
22
+ # "runwayml/stable-diffusion-v1-5",
23
+ # controlnet=controlnets,
24
+ # vae=vae,
25
+ # torch_dtype=torch.float16
26
+ # )
27
+ # pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
28
+
29
+ pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
30
+ "runwayml/stable-diffusion-v1-5",
31
+ controlnet=controlnets,
32
+ vae=vae,
33
+ torch_dtype=torch.float16
34
+ )
35
+ pipe.enable_model_cpu_offload()
36
+
37
+ # 3. Prepare Control Images
38
+ init_image = Image.open("input/isaacsim.jpg").convert("RGB")
39
+ # A. Depth Map Processing (Invert + CLAHE)
40
+ depth_map_np = np.load("input/depth.npy")
41
+ depth_map_np = np.clip(depth_map_np, 0, 20)
42
+ depth_map_normalized = (depth_map_np - np.min(depth_map_np)) / (np.max(depth_map_np) - np.min(depth_map_np))
43
+ depth_map_inverted = ( (1.0 - depth_map_normalized) * 255 ).astype(np.uint8)
44
+ clahe = cv2.createCLAHE(clipLimit=2.5, tileGridSize=(8,8))
45
+ depth_final = Image.fromarray(clahe.apply(depth_map_inverted)).convert("RGB")
46
+
47
+ # B. Canny Edge Processing (From your Isaac Sim RGB image)
48
+ isaac_rgb = cv2.imread("input/isaacsim.jpg")
49
+ # Detect edges (Thresholds 100, 200 are usually good for clean synthetic renders)
50
+ canny_edges = cv2.Canny(isaac_rgb, 100, 200)
51
+ canny_final = Image.fromarray(canny_edges).convert("RGB")
52
+
53
+ # 4. Prompt based on Rosario/Real images
54
+ prompt = (
55
+ "A photorealistic high-angle shot of a soybean field in Brazil."
56
+ "real image, agriculture scene, natural lighting, high detail, 4k resolution,"
57
+ "field image,"
58
+ "Vibrant green leaves with detailed veins,"
59
+ "haze scattering effect"
60
+ "leaves with natural aspects,"
61
+ "dark brown cloddy soil with organic dirt textures and pebbles,"
62
+ )
63
+ negative_prompt = "cartoon, 3d render, plastic, smooth floor, blurry, low quality"
64
+
65
+ # 5. Run Inference
66
+ # We pass a list of images to match our list of ControlNets
67
+ # conditioning_scale [0.8, 0.4] tells the AI: "Prioritize Depth structure, but use Canny for the sharp lines"
68
+ generator = torch.Generator(device="cuda").manual_seed(42)
69
+
70
+ # output_image = pipe(
71
+ # prompt=prompt,
72
+ # negative_prompt=negative_prompt,
73
+ # image=[depth_final, canny_final],
74
+ # num_inference_steps=10,
75
+ # guidance_scale=4.2,
76
+ # strength=0.27,
77
+ # controlnet_conditioning_scale=[0.8, 0.4],
78
+ # generator=generator
79
+ # ).images[0]
80
+
81
+ output_image = pipe(
82
+ prompt=prompt,
83
+ negative_prompt=negative_prompt,
84
+ image=init_image, # The "Starting" image for light/color
85
+ control_image=[depth_final, canny_final], # The "Guides" for geometry
86
+ num_inference_steps=50, # Higher steps = better texture
87
+ strength=0.42, # 0.7 allows significant texture replacement
88
+ guidance_scale=7.7, # Higher guidance forces it to follow the prompt
89
+ controlnet_conditioning_scale=[0.9, 0.9], # Both ControlNets are important for structure and details
90
+ generator=generator
91
+ ).images[0]
92
+
93
+ output_image.save("soybean_translated.png")
94
+
95
+ # Visualize the results, input, depth, canny, and output
96
+ import matplotlib.pyplot as plt
97
+ fig, axs = plt.subplots(2, 2, figsize=(20, 5))
98
+ axs[0,0].imshow(cv2.cvtColor(isaac_rgb, cv2.COLOR_BGR2RGB))
99
+ axs[0,0].set_title("Isaac Sim RGB")
100
+ axs[0,0].axis("off")
101
+ axs[1,0].imshow(depth_final)
102
+ axs[1,0].set_title("Depth Map (Inverted + CLAHE)")
103
+ axs[1,0].axis("off")
104
+ axs[1,1].imshow(canny_final)
105
+ axs[1,1].set_title("Canny Edges")
106
+ axs[1,1].axis("off")
107
+ axs[0,1].imshow(output_image)
108
+ axs[0,1].set_title("Generated Image")
109
+ axs[0,1].axis("off")
110
+ plt.show()
experiments/image2image/image_similarity.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torchvision import models, transforms
4
+ from PIL import Image
5
+ import numpy as np
6
+ import os
7
+ from pathlib import Path
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+ from scipy.spatial.distance import sqeuclidean
11
+ from scipy import linalg
12
+
13
+ class ImageSimilarityFinder:
14
+ def __init__(self, model_name='resnet50', device=None):
15
+ """
16
+ Initialize the image similarity finder with a vision encoder model.
17
+
18
+ Args:
19
+ model_name: Name of the pretrained model ('resnet50', 'vit_b_32', etc.)
20
+ device: torch device (cuda or cpu)
21
+ """
22
+ self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
23
+ print(f"Using device: {self.device}")
24
+
25
+ # Load pretrained model
26
+ if model_name == 'resnet50':
27
+ self.model = models.resnet50(pretrained=True)
28
+ # Remove the final classification layer to get embeddings
29
+ self.model = torch.nn.Sequential(*list(self.model.children())[:-1])
30
+ elif model_name == 'efficientnet':
31
+ self.model = models.efficientnet_b0(pretrained=True)
32
+ self.model = torch.nn.Sequential(*list(self.model.children())[:-1])
33
+ else:
34
+ raise ValueError(f"Model {model_name} not supported")
35
+
36
+ self.model = self.model.to(self.device)
37
+ self.model.eval()
38
+
39
+ # Image preprocessing
40
+ self.transform = transforms.Compose([
41
+ transforms.Resize((224, 224)),
42
+ transforms.ToTensor(),
43
+ transforms.Normalize(
44
+ mean=[0.485, 0.456, 0.406],
45
+ std=[0.229, 0.224, 0.225]
46
+ )
47
+ ])
48
+
49
+ def get_image_embedding(self, image_path):
50
+ """Extract embedding from an image."""
51
+ image = Image.open(image_path).convert('RGB')
52
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
53
+
54
+ with torch.no_grad():
55
+ embedding = self.model(image_tensor)
56
+
57
+ # Flatten the embedding
58
+ embedding = embedding.view(embedding.size(0), -1)
59
+ return embedding
60
+
61
+ def compute_similarity(self, embedding1, embedding2, metric='cosine'):
62
+ """
63
+ Compute similarity between two embeddings.
64
+
65
+ Args:
66
+ embedding1, embedding2: Image embeddings
67
+ metric: 'cosine' or 'euclidean'
68
+
69
+ Returns:
70
+ Similarity score (0-1 for cosine)
71
+ """
72
+ if metric == 'cosine':
73
+ similarity = F.cosine_similarity(embedding1, embedding2, dim=1)
74
+ elif metric == 'euclidean':
75
+ distance = torch.norm(embedding1 - embedding2, dim=1)
76
+ similarity = 1 / (1 + distance) # Convert distance to similarity
77
+ else:
78
+ raise ValueError(f"Metric {metric} not supported")
79
+
80
+ return similarity.item()
81
+
82
+ def find_similar_images(self, folder_path, metric='cosine', target_image_file=None):
83
+ """
84
+ Find similarities between images in a folder.
85
+
86
+ If target_image_file is specified, computes similarity of all other images to that one.
87
+ Otherwise, computes an all-vs-all similarity matrix.
88
+
89
+ Args:
90
+ folder_path: Path to folder containing images
91
+ metric: 'cosine' or 'euclidean'
92
+ target_image_file: Filename of the image to compare against others.
93
+
94
+ Returns:
95
+ If target_image_file is given: (other_image_files, similarity_scores_1d)
96
+ If target_image_file is None: (all_image_files, similarity_matrix_2d)
97
+ """
98
+ # Get all image files
99
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'}
100
+ image_files = [
101
+ f for f in os.listdir(folder_path)
102
+ if os.path.splitext(f)[1].lower() in image_extensions
103
+ ]
104
+
105
+ if not image_files:
106
+ print("No images found in the folder!")
107
+ return None
108
+
109
+ print(f"Found {len(image_files)} images: {image_files}")
110
+
111
+ # Get embeddings for all images
112
+ embeddings = {}
113
+ print("\nExtracting embeddings...")
114
+ for img_file in image_files:
115
+ img_path = os.path.join(folder_path, img_file)
116
+ embedding = self.get_image_embedding(img_path)
117
+ embeddings[img_file] = embedding
118
+ print(f" ✓ {img_file}")
119
+
120
+ if target_image_file:
121
+ if target_image_file not in embeddings:
122
+ print(f"Error: Target image '{target_image_file}' not found in folder.")
123
+ return None
124
+
125
+ print(f"\nComputing similarity of '{target_image_file}' against other images...")
126
+ target_embedding = embeddings[target_image_file]
127
+
128
+ other_files = [f for f in image_files if f != target_image_file]
129
+ scores = []
130
+
131
+ for other_file in other_files:
132
+ score = self.compute_similarity(target_embedding, embeddings[other_file], metric=metric)
133
+ scores.append(score)
134
+
135
+ return other_files, np.array(scores)
136
+
137
+ else:
138
+ # Compute similarity matrix
139
+ n_images = len(image_files)
140
+ similarity_matrix = np.zeros((n_images, n_images))
141
+
142
+ print("\nComputing similarities...")
143
+ for i, img1 in enumerate(image_files):
144
+ for j, img2 in enumerate(image_files):
145
+ similarity = self.compute_similarity(
146
+ embeddings[img1],
147
+ embeddings[img2],
148
+ metric=metric
149
+ )
150
+ similarity_matrix[i, j] = similarity
151
+
152
+ return image_files, similarity_matrix
153
+
154
+ def plot_similarity_matrix(self, image_files, similarity_matrix, save_path=None, folder_path=None, target_image_file=None):
155
+ """Visualize the similarity matrix as a heatmap, or as a bar chart if a target image is provided."""
156
+
157
+ if target_image_file and folder_path and similarity_matrix.ndim == 1:
158
+ # One-vs-all bar chart
159
+ from matplotlib.offsetbox import OffsetImage, AnnotationBbox
160
+ plt.figure(figsize=(15, 9))
161
+ ax = plt.gca()
162
+
163
+ # Sort for better visualization
164
+ sorted_indices = np.argsort(similarity_matrix)[::-1]
165
+ sorted_files = [image_files[i] for i in sorted_indices]
166
+ sorted_scores = similarity_matrix[sorted_indices]
167
+
168
+ ax.bar(range(len(sorted_files)), sorted_scores, color='lightblue')
169
+
170
+ ax.set_xticks(range(len(sorted_files)))
171
+ ax.set_xticklabels([]) # Hide text labels, we will use images
172
+
173
+ for i, filename in enumerate(sorted_files):
174
+ try:
175
+ img_path = os.path.join(folder_path, filename)
176
+ img = Image.open(img_path).convert("RGB")
177
+ img.thumbnail((120, 120)) # Resize for label
178
+
179
+ oi = OffsetImage(img, zoom=0.7)
180
+ box = AnnotationBbox(oi, (i, 0), frameon=False, xybox=(0, -50), boxcoords="data", pad=0, xycoords="data", box_alignment=(0.5, 1.0))
181
+ ax.add_artist(box)
182
+
183
+ # Add score text above bar
184
+ ax.text(i, sorted_scores[i] + 0.01, f'{sorted_scores[i]:.3f}', ha='center', va='bottom', fontsize=9)
185
+
186
+ except FileNotFoundError:
187
+ print(f"Warning: could not find image {filename} to create label.")
188
+ ax.text(i, -0.1, filename, rotation=90, ha='center', va='top')
189
+
190
+ ax.set_ylim(0, 1.1)
191
+ ax.set_xlim(-0.7, len(image_files) - 0.3)
192
+ ax.set_ylabel('Cosine Similarity (higher = more similar)')
193
+ ax.set_title(f'Similarity of other images compared to "{target_image_file}"')
194
+ plt.tight_layout(rect=[0, 0.1, 1, 0.95]) # Adjust layout to make space for images
195
+
196
+ else:
197
+ # Original heatmap for matrix
198
+ plt.figure(figsize=(10, 8))
199
+ sns.heatmap(
200
+ similarity_matrix,
201
+ xticklabels=image_files,
202
+ yticklabels=image_files,
203
+ annot=True,
204
+ fmt='.3f',
205
+ cmap='coolwarm',
206
+ vmin=0,
207
+ vmax=1
208
+ )
209
+ plt.title('Image Similarity Matrix (Cosine Similarity)')
210
+ plt.tight_layout()
211
+
212
+ if save_path:
213
+ # Create directory if it doesn't exist
214
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
215
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
216
+ print(f"\nPlot saved to {save_path}")
217
+
218
+ plt.show()
219
+
220
+ def print_similarity_results(self, image_files, similarity_matrix, target_image_file=None):
221
+ """Print similarity results in a readable format."""
222
+ print("\n" + "="*80)
223
+ print("IMAGE SIMILARITY RESULTS")
224
+ print("="*80 + "\n")
225
+
226
+ if target_image_file and similarity_matrix.ndim == 1:
227
+ print(f"Similarities compared to '{target_image_file}':\n")
228
+
229
+ # Sort for printing
230
+ sorted_pairs = sorted(zip(similarity_matrix, image_files), reverse=True)
231
+
232
+ for similarity, img_file in sorted_pairs:
233
+ bar_length = int(similarity * 40)
234
+ bar = '█' * bar_length + '░' * (40 - bar_length)
235
+ print(f"{img_file}")
236
+ print(f" [{bar}] {similarity:.4f}")
237
+ else:
238
+ for i in range(len(image_files)):
239
+ for j in range(i + 1, len(image_files)):
240
+ img1 = image_files[i]
241
+ img2 = image_files[j]
242
+ similarity = similarity_matrix[i, j]
243
+
244
+ # Create a visual representation
245
+ bar_length = int(similarity * 40)
246
+ bar = '█' * bar_length + '░' * (40 - bar_length)
247
+
248
+ print(f"{img1} <-> {img2}")
249
+ print(f" [{bar}] {similarity:.4f}")
250
+
251
+
252
+ class FIDSimilarityFinder:
253
+ """Compute Fréchet Inception Distance (FID) between images."""
254
+
255
+ def __init__(self, device=None):
256
+ """
257
+ Initialize FID calculator using InceptionV3 model.
258
+
259
+ Args:
260
+ device: torch device (cuda or cpu)
261
+ """
262
+ self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
263
+ print(f"Using device: {self.device}")
264
+
265
+ # Load InceptionV3 model (pretrained on ImageNet)
266
+ inception = models.inception_v3(pretrained=True)
267
+ inception.eval()
268
+
269
+ # Create a wrapper to extract features before the final layer
270
+ class InceptionFeatureExtractor(torch.nn.Module):
271
+ def __init__(self, inception_model):
272
+ super().__init__()
273
+ self.inception = inception_model
274
+ # Remove the final fc layer
275
+ self.inception.fc = torch.nn.Identity()
276
+
277
+ def forward(self, x):
278
+ # Pass through all layers except fc
279
+ x = self.inception.Conv2d_1a_3x3(x)
280
+ x = self.inception.Conv2d_2a_3x3(x)
281
+ x = self.inception.Conv2d_2b_3x3(x)
282
+ x = self.inception.maxpool1(x)
283
+ x = self.inception.Conv2d_3b_1x1(x)
284
+ x = self.inception.Conv2d_4a_3x3(x)
285
+ x = self.inception.maxpool2(x)
286
+ x = self.inception.Mixed_5b(x)
287
+ x = self.inception.Mixed_5c(x)
288
+ x = self.inception.Mixed_5d(x)
289
+ x = self.inception.Mixed_6a(x)
290
+ x = self.inception.Mixed_6b(x)
291
+ x = self.inception.Mixed_6c(x)
292
+ x = self.inception.Mixed_6d(x)
293
+ x = self.inception.Mixed_6e(x)
294
+ x = self.inception.Mixed_7a(x)
295
+ x = self.inception.Mixed_7b(x)
296
+ x = self.inception.Mixed_7c(x)
297
+ x = self.inception.avgpool(x)
298
+ x = torch.flatten(x, 1)
299
+ return x
300
+
301
+ self.model = InceptionFeatureExtractor(inception)
302
+ self.model = self.model.to(self.device)
303
+ self.model.eval()
304
+
305
+ # Image preprocessing for InceptionV3
306
+ self.transform = transforms.Compose([
307
+ transforms.Resize((299, 299)),
308
+ transforms.ToTensor(),
309
+ transforms.Normalize(
310
+ mean=[0.485, 0.456, 0.406],
311
+ std=[0.229, 0.224, 0.225]
312
+ )
313
+ ])
314
+
315
+ def get_inception_features(self, image_path):
316
+ """Extract InceptionV3 features from an image."""
317
+ image = Image.open(image_path).convert('RGB')
318
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
319
+
320
+ with torch.no_grad():
321
+ # Pass through the model up to the average pool
322
+ features = self.model(image_tensor)
323
+ # Flatten to 1D vector for each image
324
+ features = features.view(features.size(0), -1)
325
+
326
+ return features.cpu().numpy()
327
+
328
+ def calculate_frechet_distance(self, mu1, sigma1, mu2, sigma2, eps=1e-6):
329
+ """Calculate Fréchet distance between two Gaussians."""
330
+ mu1 = np.atleast_1d(mu1)
331
+ mu2 = np.atleast_1d(mu2)
332
+ sigma1 = np.atleast_2d(sigma1)
333
+ sigma2 = np.atleast_2d(sigma2)
334
+
335
+ assert mu1.shape == mu2.shape, "Statistics must have matching dimensions"
336
+ assert sigma1.shape == sigma2.shape, "Statistics must have matching dimensions"
337
+
338
+ # Compute difference
339
+ diff = mu1 - mu2
340
+
341
+ # Compute matrix square root
342
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
343
+
344
+ # Handle complex results
345
+ if np.iscomplexobj(covmean):
346
+ covmean = covmean.real
347
+
348
+ # Calculate FID
349
+ tr_covmean = np.trace(covmean)
350
+ fid = diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
351
+
352
+ return np.sqrt(np.maximum(fid, 0.0))
353
+
354
+ def compute_fid_matrix(self, folder_path, target_image_file=None):
355
+ """
356
+ Compute FID between all pairs of images in a folder, or against a single target image.
357
+ Lower FID indicates higher similarity.
358
+
359
+ Args:
360
+ folder_path: Path to folder containing images
361
+ target_image_file: If specified, compute FID of other images against this one.
362
+
363
+ Returns:
364
+ image_files, fid_scores (1D or 2D array)
365
+ """
366
+ # Get all image files
367
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'}
368
+ image_files = sorted([
369
+ f for f in os.listdir(folder_path)
370
+ if os.path.splitext(f)[1].lower() in image_extensions
371
+ ])
372
+
373
+ if not image_files:
374
+ print("No images found in the folder!")
375
+ return None
376
+
377
+ print(f"Found {len(image_files)} images: {image_files}")
378
+
379
+ # Extract features for all images
380
+ all_features = {}
381
+ print("\nExtracting InceptionV3 features...")
382
+ for img_file in image_files:
383
+ img_path = os.path.join(folder_path, img_file)
384
+ features = self.get_inception_features(img_path)
385
+ all_features[img_file] = features
386
+ print(f" ✓ {img_file}")
387
+
388
+ if target_image_file:
389
+ if target_image_file not in all_features:
390
+ print(f"Error: Target image '{target_image_file}' not found.")
391
+ return None
392
+
393
+ print(f"\nComputing FID of '{target_image_file}' against other images...")
394
+ target_mu = all_features[target_image_file].flatten()
395
+
396
+ other_files = [f for f in image_files if f != target_image_file]
397
+ fid_scores = []
398
+
399
+ for other_file in other_files:
400
+ other_mu = all_features[other_file].flatten()
401
+ fid = np.linalg.norm(other_mu - target_mu)
402
+ fid_scores.append(fid)
403
+
404
+ return other_files, np.array(fid_scores)
405
+
406
+ else:
407
+ # Compute FID matrix
408
+ n_images = len(image_files)
409
+ fid_matrix = np.zeros((n_images, n_images))
410
+
411
+ print("\nComputing FID-based distances...")
412
+
413
+ for i in range(n_images):
414
+ for j in range(i, n_images):
415
+ if i == j:
416
+ fid_matrix[i, j] = 0.0
417
+ else:
418
+ mu1 = all_features[image_files[i]].flatten()
419
+ mu2 = all_features[image_files[j]].flatten()
420
+
421
+ # Compute Euclidean distance as FID approximation
422
+ fid = np.linalg.norm(mu1 - mu2)
423
+ fid_matrix[i, j] = fid
424
+ fid_matrix[j, i] = fid
425
+
426
+ return image_files, fid_matrix
427
+
428
+ def plot_fid_matrix(self, image_files, fid_matrix, save_path=None, folder_path=None, target_image_file=None):
429
+ """Visualize the FID matrix as a heatmap, or as a bar chart if a target image is provided."""
430
+ if target_image_file and folder_path and fid_matrix.ndim == 1:
431
+ # One-vs-all bar chart for FID
432
+ from matplotlib.offsetbox import OffsetImage, AnnotationBbox
433
+ plt.figure(figsize=(15, 9))
434
+ ax = plt.gca()
435
+
436
+ # Sort by distance (ascending)
437
+ sorted_indices = np.argsort(fid_matrix)
438
+ sorted_files = [image_files[i] for i in sorted_indices]
439
+ sorted_scores = fid_matrix[sorted_indices]
440
+
441
+ ax.bar(range(len(sorted_files)), sorted_scores, color='lightgreen')
442
+
443
+ ax.set_xticks(range(len(sorted_files)))
444
+ ax.set_xticklabels([])
445
+
446
+ for i, filename in enumerate(sorted_files):
447
+ try:
448
+ img_path = os.path.join(folder_path, filename)
449
+ img = Image.open(img_path).convert("RGB")
450
+ img.thumbnail((120, 120))
451
+
452
+ oi = OffsetImage(img, zoom=0.7)
453
+ box = AnnotationBbox(oi, (i, 0), frameon=False, xybox=(0, -50), boxcoords="data", pad=0, xycoords="data", box_alignment=(0.5, 1.0))
454
+ ax.add_artist(box)
455
+
456
+ ax.text(i, sorted_scores[i], f'{sorted_scores[i]:.2f}', ha='center', va='bottom', fontsize=9, bbox=dict(facecolor='white', alpha=0.5, pad=1))
457
+ except FileNotFoundError:
458
+ print(f"Warning: could not find image {filename} to create label.")
459
+ ax.text(i, -0.1, filename, rotation=90, ha='center', va='top')
460
+
461
+ if len(sorted_scores) > 0:
462
+ ax.set_ylim(0, max(sorted_scores) * 1.15)
463
+ ax.set_xlim(-0.7, len(image_files) - 0.3)
464
+ ax.set_ylabel('FID Distance (lower = more similar)')
465
+ ax.set_title(f'FID Distance of other images from "{target_image_file}"')
466
+ plt.tight_layout(rect=[0, 0.1, 1, 0.95])
467
+
468
+ else:
469
+ # Original heatmap
470
+ plt.figure(figsize=(10, 8))
471
+ sns.heatmap(
472
+ fid_matrix,
473
+ xticklabels=image_files,
474
+ yticklabels=image_files,
475
+ annot=True,
476
+ fmt='.2f',
477
+ cmap='RdYlGn_r', # Reversed: red = high distance (different), green = low distance (similar)
478
+ cbar_kws={'label': 'FID Distance (lower = more similar)'}
479
+ )
480
+ plt.title('Fréchet Inception Distance (FID) Matrix')
481
+ plt.tight_layout()
482
+
483
+ if save_path:
484
+ # Create directory if it doesn't exist
485
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
486
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
487
+ print(f"\nHeatmap saved to {save_path}")
488
+
489
+ plt.show()
490
+
491
+ def print_fid_results(self, image_files, fid_matrix, target_image_file=None):
492
+ """Print FID results in a readable format."""
493
+ print("\n" + "="*80)
494
+ print("FRÉCHET INCEPTION DISTANCE (FID) RESULTS")
495
+ print("="*80)
496
+ print("\nNote: Lower FID = more similar images\n")
497
+
498
+ if target_image_file and fid_matrix.ndim == 1:
499
+ print(f"FID distances from '{target_image_file}':\n")
500
+
501
+ # Sort for printing
502
+ sorted_pairs = sorted(zip(fid_matrix, image_files))
503
+
504
+ if not sorted_pairs: return
505
+
506
+ max_fid = sorted_pairs[-1][0] if sorted_pairs else 1
507
+
508
+ for fid, img_file in sorted_pairs:
509
+ # Inverted bar: shorter is better
510
+ bar_length = int((1 - fid / max_fid) * 40) if max_fid > 0 else 0
511
+ bar = '█' * bar_length + '░' * (40 - bar_length)
512
+ print(f"{img_file}")
513
+ print(f" [{bar}] FID: {fid:.4f}")
514
+
515
+ else:
516
+ # Create sorted list of pairwise distances
517
+ distances = []
518
+ for i in range(len(image_files)):
519
+ for j in range(i + 1, len(image_files)):
520
+ distances.append((
521
+ image_files[i],
522
+ image_files[j],
523
+ fid_matrix[i, j]
524
+ ))
525
+
526
+ # Sort by FID distance
527
+ distances.sort(key=lambda x: x[2])
528
+
529
+ if not distances: return
530
+
531
+ print("Pairwise FID Distances (sorted by similarity):")
532
+ max_fid = max(d[2] for d in distances) if distances else 1
533
+ for img1, img2, fid in distances:
534
+ # Create a visual representation (inverted: shorter bar = more similar)
535
+ bar_length = int((1 - fid / max_fid) * 40) if max_fid > 0 else 0
536
+ bar = '█' * bar_length + '░' * (40 - bar_length)
537
+
538
+ print(f"{img1} <-> {img2}")
539
+ print(f" [{bar}] FID: {fid:.4f}")
540
+
541
+
542
+ def main():
543
+ # Set folder path and target image
544
+ folder_path = "./input"
545
+ target_image_file = "rosario.jpg" # The image to compare against others
546
+
547
+ # Check if target file exists
548
+ if not os.path.exists(os.path.join(folder_path, target_image_file)):
549
+ print(f"Error: Target image '{target_image_file}' not found in '{folder_path}'")
550
+ # List other available images
551
+ try:
552
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'}
553
+ avail_images = [f for f in os.listdir(folder_path) if os.path.splitext(f)[1].lower() in image_extensions]
554
+ if avail_images:
555
+ print("Available images:", avail_images)
556
+ except FileNotFoundError:
557
+ print(f"Error: Folder '{folder_path}' not found.")
558
+ return
559
+
560
+ print("\n" + "="*80)
561
+ print("IMAGE SIMILARITY ANALYSIS")
562
+ print(f"Target Image: {target_image_file}")
563
+ print("="*80)
564
+
565
+ # Always perform both analyses for the target image
566
+
567
+ # Method 1: ResNet50 + Cosine Similarity
568
+ print("\n" + "="*80)
569
+ print("METHOD 1: ResNet50 + Cosine Similarity")
570
+ print("="*80)
571
+ similarity_finder = ImageSimilarityFinder(model_name='resnet50')
572
+
573
+ results = similarity_finder.find_similar_images(
574
+ folder_path,
575
+ metric='cosine',
576
+ target_image_file=target_image_file
577
+ )
578
+
579
+ if results:
580
+ image_files, similarity_scores = results
581
+ similarity_finder.print_similarity_results(image_files, similarity_scores, target_image_file=target_image_file)
582
+ output_path = os.path.join(folder_path,'output', f'similarity_to_{Path(target_image_file).stem}_resnet50.png')
583
+ similarity_finder.plot_similarity_matrix(image_files, similarity_scores, output_path, folder_path=folder_path, target_image_file=target_image_file)
584
+
585
+ # Method 2: InceptionV3 + FID
586
+ print("\n" + "="*80)
587
+ print("METHOD 2: InceptionV3 + Fréchet Inception Distance (FID)")
588
+ print("="*80)
589
+ fid_finder = FIDSimilarityFinder()
590
+
591
+ results = fid_finder.compute_fid_matrix(folder_path, target_image_file=target_image_file)
592
+
593
+ if results:
594
+ image_files, fid_scores = results
595
+ fid_finder.print_fid_results(image_files, fid_scores, target_image_file=target_image_file)
596
+ output_path = os.path.join(folder_path,'output', f'similarity_to_{Path(target_image_file).stem}_fid.png')
597
+ fid_finder.plot_fid_matrix(image_files, fid_scores, output_path, folder_path=folder_path, target_image_file=target_image_file)
598
+
599
+ print("\n" + "="*80)
600
+ print("✓ Analysis complete!")
601
+ print("="*80)
602
+
603
+
604
+ if __name__ == "__main__":
605
+ main()
experiments/image2image/image_similarity_all.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torchvision import models, transforms
4
+ from PIL import Image
5
+ import numpy as np
6
+ import os
7
+ from pathlib import Path
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+ from scipy.spatial.distance import sqeuclidean
11
+ from scipy import linalg
12
+ from matplotlib.offsetbox import OffsetImage, AnnotationBbox
13
+
14
+
15
+ class ImageSimilarityFinder:
16
+ def __init__(self, model_name='resnet50', device=None):
17
+ """
18
+ Initialize the image similarity finder with a vision encoder model.
19
+
20
+ Args:
21
+ model_name: Name of the pretrained model ('resnet50', 'vit_b_32', etc.)
22
+ device: torch device (cuda or cpu)
23
+ """
24
+ self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
25
+ print(f"Using device: {self.device}")
26
+
27
+ # Load pretrained model
28
+ if model_name == 'resnet50':
29
+ self.model = models.resnet50(pretrained=True)
30
+ # Remove the final classification layer to get embeddings
31
+ self.model = torch.nn.Sequential(*list(self.model.children())[:-1])
32
+ elif model_name == 'efficientnet':
33
+ self.model = models.efficientnet_b0(pretrained=True)
34
+ self.model = torch.nn.Sequential(*list(self.model.children())[:-1])
35
+ else:
36
+ raise ValueError(f"Model {model_name} not supported")
37
+
38
+ self.model = self.model.to(self.device)
39
+ self.model.eval()
40
+
41
+ # Image preprocessing
42
+ self.transform = transforms.Compose([
43
+ transforms.Resize((224, 224)),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize(
46
+ mean=[0.485, 0.456, 0.406],
47
+ std=[0.229, 0.224, 0.225]
48
+ )
49
+ ])
50
+
51
+ def get_image_embedding(self, image_path):
52
+ """Extract embedding from an image."""
53
+ image = Image.open(image_path).convert('RGB')
54
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
55
+
56
+ with torch.no_grad():
57
+ embedding = self.model(image_tensor)
58
+
59
+ # Flatten the embedding
60
+ embedding = embedding.view(embedding.size(0), -1)
61
+ return embedding
62
+
63
+ def compute_similarity(self, embedding1, embedding2, metric='cosine'):
64
+ """
65
+ Compute similarity between two embeddings.
66
+
67
+ Args:
68
+ embedding1, embedding2: Image embeddings
69
+ metric: 'cosine' or 'euclidean'
70
+
71
+ Returns:
72
+ Similarity score (0-1 for cosine)
73
+ """
74
+ if metric == 'cosine':
75
+ similarity = F.cosine_similarity(embedding1, embedding2, dim=1)
76
+ elif metric == 'euclidean':
77
+ distance = torch.norm(embedding1 - embedding2, dim=1)
78
+ similarity = 1 / (1 + distance) # Convert distance to similarity
79
+ else:
80
+ raise ValueError(f"Metric {metric} not supported")
81
+
82
+ return similarity.item()
83
+
84
+ def find_similar_images(self, folder_path, metric='cosine'):
85
+ """
86
+ Find similarities between all images in a folder.
87
+
88
+ Args:
89
+ folder_path: Path to folder containing images
90
+ metric: 'cosine' or 'euclidean'
91
+
92
+ Returns:
93
+ Dictionary with image names and their similarity matrix
94
+ """
95
+ # Get all image files
96
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'}
97
+ image_files = [
98
+ f for f in os.listdir(folder_path)
99
+ if os.path.splitext(f)[1].lower() in image_extensions
100
+ ]
101
+
102
+ if not image_files:
103
+ print("No images found in the folder!")
104
+ return None
105
+
106
+ print(f"Found {len(image_files)} images: {image_files}")
107
+
108
+ # Get embeddings for all images
109
+ embeddings = {}
110
+ print("\nExtracting embeddings...")
111
+ for img_file in image_files:
112
+ img_path = os.path.join(folder_path, img_file)
113
+ embedding = self.get_image_embedding(img_path)
114
+ embeddings[img_file] = embedding
115
+ print(f" ✓ {img_file}")
116
+
117
+ # Compute similarity matrix
118
+ n_images = len(image_files)
119
+ similarity_matrix = np.zeros((n_images, n_images))
120
+
121
+ print("\nComputing similarities...")
122
+ for i, img1 in enumerate(image_files):
123
+ for j, img2 in enumerate(image_files):
124
+ similarity = self.compute_similarity(
125
+ embeddings[img1],
126
+ embeddings[img2],
127
+ metric=metric
128
+ )
129
+ similarity_matrix[i, j] = similarity
130
+
131
+ return image_files, similarity_matrix
132
+
133
+ # def plot_similarity_matrix(self, image_files, similarity_matrix, save_path=None):
134
+ # """Visualize the similarity matrix as a heatmap."""
135
+ # plt.figure(figsize=(10, 8))
136
+ # sns.heatmap(
137
+ # similarity_matrix,
138
+ # xticklabels=image_files,
139
+ # yticklabels=image_files,
140
+ # annot=True,
141
+ # fmt='.3f',
142
+ # cmap='coolwarm',
143
+ # vmin=0,
144
+ # vmax=1
145
+ # )
146
+ # plt.title('Image Similarity Matrix (Cosine Similarity)')
147
+ # plt.tight_layout()
148
+
149
+ # if save_path:
150
+ # # Create directory if it doesn't exist
151
+ # os.makedirs(os.path.dirname(save_path), exist_ok=True)
152
+ # plt.savefig(save_path, dpi=150, bbox_inches='tight')
153
+ # print(f"\nHeatmap saved to {save_path}")
154
+
155
+ # plt.show()
156
+
157
+
158
+ def plot_similarity_matrix(self, image_files, similarity_matrix, folder_path, save_path=None):
159
+ """Visualize the similarity matrix as a heatmap with images on the axes."""
160
+ fig, ax = plt.subplots(figsize=(12, 10))
161
+
162
+ # Create the heatmap
163
+ sns.heatmap(
164
+ similarity_matrix,
165
+ annot=True,
166
+ fmt='.3f',
167
+ cmap='coolwarm',
168
+ vmin=0,
169
+ vmax=1,
170
+ ax=ax,
171
+ cbar_kws={'pad': 0.1} # Make room for images
172
+ )
173
+
174
+ def add_image_anchors(axis_type, tick_positions, labels):
175
+ for i, (pos, img_name) in enumerate(zip(tick_positions, labels)):
176
+ # Load and thumbnail the image
177
+ img_path = os.path.join('input', img_name)
178
+ img = Image.open(img_path).convert('RGB')
179
+ img.thumbnail((200, 200)) # Resize for the axis
180
+
181
+ imagebox = OffsetImage(img, zoom=0.5) # Adjust zoom based on your DPI
182
+
183
+ if axis_type == 'x':
184
+ # Position image below the X-axis
185
+ ab = AnnotationBbox(imagebox, (pos, 0),
186
+ xybox=(0, -65), # Distance from axis
187
+ xycoords=('data', 'axes fraction'),
188
+ boxcoords="offset points",
189
+ frameon=False)
190
+ else:
191
+ # Position image to the left of the Y-axis
192
+ ab = AnnotationBbox(imagebox, (0, pos),
193
+ xybox=(-65, 0),
194
+ xycoords=('axes fraction', 'data'),
195
+ boxcoords="offset points",
196
+ frameon=False)
197
+ ax.add_artist(ab)
198
+
199
+ # Get tick positions (Seaborn centers them at 0.5, 1.5, etc.)
200
+ tick_positions = np.arange(len(image_files)) + 0.5
201
+
202
+ # Add images to both axes
203
+ add_image_anchors('x', tick_positions, image_files)
204
+ add_image_anchors('y', tick_positions, image_files)
205
+
206
+ # Remove text labels to avoid clutter
207
+ ax.set_xticklabels([])
208
+ ax.set_yticklabels([])
209
+
210
+ plt.title('Visual Image Similarity Matrix', pad=20)
211
+ plt.tight_layout()
212
+
213
+ if save_path:
214
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
215
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
216
+ print(f"\nHeatmap with images saved to {save_path}")
217
+
218
+ plt.show()
219
+
220
+ def print_similarity_results(self, image_files, similarity_matrix):
221
+ """Print similarity results in a readable format."""
222
+ print("\n" + "="*80)
223
+ print("IMAGE SIMILARITY RESULTS")
224
+ print("="*80 + "\n")
225
+
226
+ for i in range(len(image_files)):
227
+ for j in range(i + 1, len(image_files)):
228
+ img1 = image_files[i]
229
+ img2 = image_files[j]
230
+ similarity = similarity_matrix[i, j]
231
+
232
+ # Create a visual representation
233
+ bar_length = int(similarity * 40)
234
+ bar = '█' * bar_length + '░' * (40 - bar_length)
235
+
236
+ print(f"{img1} <-> {img2}")
237
+ print(f" [{bar}] {similarity:.4f}")
238
+
239
+
240
+ class FIDSimilarityFinder:
241
+ """Compute Fréchet Inception Distance (FID) between images."""
242
+
243
+ def __init__(self, device=None):
244
+ """
245
+ Initialize FID calculator using InceptionV3 model.
246
+
247
+ Args:
248
+ device: torch device (cuda or cpu)
249
+ """
250
+ self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
251
+ print(f"Using device: {self.device}")
252
+
253
+ # Load InceptionV3 model (pretrained on ImageNet)
254
+ inception = models.inception_v3(pretrained=True)
255
+ inception.eval()
256
+
257
+ # Create a wrapper to extract features before the final layer
258
+ class InceptionFeatureExtractor(torch.nn.Module):
259
+ def __init__(self, inception_model):
260
+ super().__init__()
261
+ self.inception = inception_model
262
+ # Remove the final fc layer
263
+ self.inception.fc = torch.nn.Identity()
264
+
265
+ def forward(self, x):
266
+ # Pass through all layers except fc
267
+ x = self.inception.Conv2d_1a_3x3(x)
268
+ x = self.inception.Conv2d_2a_3x3(x)
269
+ x = self.inception.Conv2d_2b_3x3(x)
270
+ x = self.inception.maxpool1(x)
271
+ x = self.inception.Conv2d_3b_1x1(x)
272
+ x = self.inception.Conv2d_4a_3x3(x)
273
+ x = self.inception.maxpool2(x)
274
+ x = self.inception.Mixed_5b(x)
275
+ x = self.inception.Mixed_5c(x)
276
+ x = self.inception.Mixed_5d(x)
277
+ x = self.inception.Mixed_6a(x)
278
+ x = self.inception.Mixed_6b(x)
279
+ x = self.inception.Mixed_6c(x)
280
+ x = self.inception.Mixed_6d(x)
281
+ x = self.inception.Mixed_6e(x)
282
+ x = self.inception.Mixed_7a(x)
283
+ x = self.inception.Mixed_7b(x)
284
+ x = self.inception.Mixed_7c(x)
285
+ x = self.inception.avgpool(x)
286
+ x = torch.flatten(x, 1)
287
+ return x
288
+
289
+ self.model = InceptionFeatureExtractor(inception)
290
+ self.model = self.model.to(self.device)
291
+ self.model.eval()
292
+
293
+ # Image preprocessing for InceptionV3
294
+ self.transform = transforms.Compose([
295
+ transforms.Resize((299, 299)),
296
+ transforms.ToTensor(),
297
+ transforms.Normalize(
298
+ mean=[0.485, 0.456, 0.406],
299
+ std=[0.229, 0.224, 0.225]
300
+ )
301
+ ])
302
+
303
+ def get_inception_features(self, image_path):
304
+ """Extract InceptionV3 features from an image."""
305
+ image = Image.open(image_path).convert('RGB')
306
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
307
+
308
+ with torch.no_grad():
309
+ # Pass through the model up to the average pool
310
+ features = self.model(image_tensor)
311
+ # Flatten to 1D vector for each image
312
+ features = features.view(features.size(0), -1)
313
+
314
+ return features.cpu().numpy()
315
+
316
+ def calculate_frechet_distance(self, mu1, sigma1, mu2, sigma2, eps=1e-6):
317
+ """Calculate Fréchet distance between two Gaussians."""
318
+ mu1 = np.atleast_1d(mu1)
319
+ mu2 = np.atleast_1d(mu2)
320
+ sigma1 = np.atleast_2d(sigma1)
321
+ sigma2 = np.atleast_2d(sigma2)
322
+
323
+ assert mu1.shape == mu2.shape, "Statistics must have matching dimensions"
324
+ assert sigma1.shape == sigma2.shape, "Statistics must have matching dimensions"
325
+
326
+ # Compute difference
327
+ diff = mu1 - mu2
328
+
329
+ # Compute matrix square root
330
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
331
+
332
+ # Handle complex results
333
+ if np.iscomplexobj(covmean):
334
+ covmean = covmean.real
335
+
336
+ # Calculate FID
337
+ tr_covmean = np.trace(covmean)
338
+ fid = diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
339
+
340
+ return np.sqrt(np.maximum(fid, 0.0))
341
+
342
+ def compute_fid_matrix(self, folder_path):
343
+ """
344
+ Compute FID between all pairs of images in a folder.
345
+ Lower FID indicates higher similarity.
346
+
347
+ Args:
348
+ folder_path: Path to folder containing images
349
+
350
+ Returns:
351
+ image_files, fid_matrix
352
+ """
353
+ # Get all image files
354
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'}
355
+ image_files = sorted([
356
+ f for f in os.listdir(folder_path)
357
+ if os.path.splitext(f)[1].lower() in image_extensions
358
+ ])
359
+
360
+ if not image_files:
361
+ print("No images found in the folder!")
362
+ return None
363
+
364
+ print(f"Found {len(image_files)} images: {image_files}")
365
+
366
+ # Extract features for all images
367
+ all_features = {}
368
+ print("\nExtracting InceptionV3 features...")
369
+ for img_file in image_files:
370
+ img_path = os.path.join(folder_path, img_file)
371
+ features = self.get_inception_features(img_path)
372
+ all_features[img_file] = features
373
+ print(f" ✓ {img_file}")
374
+
375
+ # Compute FID matrix
376
+ n_images = len(image_files)
377
+ fid_matrix = np.zeros((n_images, n_images))
378
+
379
+ print("\nComputing FID-based distances...")
380
+
381
+ # For single images, we compute a simplified FID using the feature vectors themselves
382
+ # Stack all features for covariance computation
383
+ all_stacked = np.vstack([all_features[f] for f in image_files])
384
+
385
+ for i in range(n_images):
386
+ for j in range(n_images):
387
+ if i == j:
388
+ fid_matrix[i, j] = 0.0
389
+ else:
390
+ # Get individual feature vectors
391
+ mu1 = all_features[image_files[i]].flatten()
392
+ mu2 = all_features[image_files[j]].flatten()
393
+
394
+ # Use a simplified FID: just compute the Wasserstein distance between features
395
+ # with a small regularization for covariance
396
+ diff = mu1 - mu2
397
+
398
+ # Compute Euclidean distance as FID approximation
399
+ fid = np.linalg.norm(diff)
400
+ fid_matrix[i, j] = fid
401
+
402
+ return image_files, fid_matrix
403
+
404
+ def plot_fid_matrix(self, image_files, fid_matrix, save_path=None):
405
+ """Visualize the FID matrix as a heatmap."""
406
+ fig, ax = plt.subplots(figsize=(12, 10))
407
+ sns.heatmap(
408
+ fid_matrix,
409
+ annot=True,
410
+ fmt='.2f',
411
+ ax=ax,
412
+ cmap='RdYlGn_r', # Reversed: red = high distance (different), green = low distance (similar)
413
+ cbar_kws={'label': 'FID Distance (lower = more similar)'}
414
+ )
415
+
416
+ def add_image_anchors(axis_type, tick_positions, labels):
417
+ for i, (pos, img_name) in enumerate(zip(tick_positions, labels)):
418
+ # Load and thumbnail the image
419
+ img_path = os.path.join('input', img_name)
420
+ img = Image.open(img_path).convert('RGB')
421
+ img.thumbnail((200, 200)) # Resize for the axis
422
+
423
+ imagebox = OffsetImage(img, zoom=0.5) # Adjust zoom based on your DPI
424
+
425
+ if axis_type == 'x':
426
+ # Position image below the X-axis
427
+ ab = AnnotationBbox(imagebox, (pos, 0),
428
+ xybox=(0, -65), # Distance from axis
429
+ xycoords=('data', 'axes fraction'),
430
+ boxcoords="offset points",
431
+ frameon=False)
432
+ else:
433
+ # Position image to the left of the Y-axis
434
+ ab = AnnotationBbox(imagebox, (0, pos),
435
+ xybox=(-65, 0),
436
+ xycoords=('axes fraction', 'data'),
437
+ boxcoords="offset points",
438
+ frameon=False)
439
+ ax.add_artist(ab)
440
+
441
+ # Get tick positions (Seaborn centers them at 0.5, 1.5, etc.)
442
+ tick_positions = np.arange(len(image_files)) + 0.5
443
+ # Add images to both axes
444
+ add_image_anchors('x', tick_positions, image_files)
445
+ add_image_anchors('y', tick_positions, image_files)
446
+ # Remove text labels to avoid clutter
447
+ ax.set_xticklabels([])
448
+ ax.set_yticklabels([])
449
+
450
+
451
+ plt.title('Fréchet Inception Distance (FID) Matrix')
452
+ plt.tight_layout()
453
+
454
+ if save_path:
455
+ # Create directory if it doesn't exist
456
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
457
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
458
+ print(f"\nHeatmap saved to {save_path}")
459
+
460
+ plt.show()
461
+
462
+ def print_fid_results(self, image_files, fid_matrix):
463
+ """Print FID results in a readable format."""
464
+ print("\n" + "="*80)
465
+ print("FRÉCHET INCEPTION DISTANCE (FID) RESULTS")
466
+ print("="*80)
467
+ print("\nNote: Lower FID = more similar images\n")
468
+
469
+ # Create sorted list of pairwise distances
470
+ distances = []
471
+ for i in range(len(image_files)):
472
+ for j in range(i + 1, len(image_files)):
473
+ distances.append((
474
+ image_files[i],
475
+ image_files[j],
476
+ fid_matrix[i, j]
477
+ ))
478
+
479
+ # Sort by FID distance
480
+ distances.sort(key=lambda x: x[2])
481
+
482
+ print("Pairwise FID Distances (sorted by similarity):")
483
+ for img1, img2, fid in distances:
484
+ # Create a visual representation (inverted: shorter bar = more similar)
485
+ max_fid = max(d[2] for d in distances)
486
+ bar_length = int((1 - fid / max_fid) * 40)
487
+ bar = '█' * bar_length + '░' * (40 - bar_length)
488
+
489
+ print(f"{img1} <-> {img2}")
490
+ print(f" [{bar}] FID: {fid:.4f}")
491
+
492
+
493
+ def main():
494
+ # Set folder path
495
+ folder_path = "./input"
496
+
497
+ print("\n" + "="*80)
498
+ print("IMAGE SIMILARITY ANALYSIS")
499
+ print("="*80)
500
+ print("\nChoose analysis method:")
501
+ print("1. ResNet50 + Cosine Similarity (faster, lightweight)")
502
+ print("2. InceptionV3 + Fréchet Inception Distance / FID (more robust)")
503
+ print("3. Both analyses")
504
+
505
+ choice = input("\nEnter your choice (1-3): ").strip()
506
+
507
+ # Method 1: ResNet50 + Cosine Similarity
508
+ if choice in ['1', '3']:
509
+ print("\n" + "="*80)
510
+ print("METHOD 1: ResNet50 + Cosine Similarity")
511
+ print("="*80)
512
+ similarity_finder = ImageSimilarityFinder(model_name='resnet50')
513
+
514
+ results = similarity_finder.find_similar_images(
515
+ folder_path,
516
+ metric='cosine'
517
+ )
518
+
519
+ if results:
520
+ image_files, similarity_matrix = results
521
+ similarity_finder.print_similarity_results(image_files, similarity_matrix)
522
+ output_path = os.path.join(folder_path,'output', 'similarity_heatmap_resnet50.png')
523
+ similarity_finder.plot_similarity_matrix(image_files, similarity_matrix, output_path)
524
+
525
+ # Method 2: InceptionV3 + FID
526
+ if choice in ['2', '3']:
527
+ print("\n" + "="*80)
528
+ print("METHOD 2: InceptionV3 + Fréchet Inception Distance (FID)")
529
+ print("="*80)
530
+ fid_finder = FIDSimilarityFinder()
531
+
532
+ results = fid_finder.compute_fid_matrix(folder_path)
533
+
534
+ if results:
535
+ image_files, fid_matrix = results
536
+ fid_finder.print_fid_results(image_files, fid_matrix)
537
+ output_path = os.path.join('./output', 'similarity_heatmap_fid.png')
538
+ fid_finder.plot_fid_matrix(image_files, fid_matrix, output_path)
539
+
540
+ print("\n" + "="*80)
541
+ print("✓ Analysis complete!")
542
+ print("="*80)
543
+
544
+
545
+ if __name__ == "__main__":
546
+ main()
experiments/image2image/input/Gemini.png ADDED

Git LFS Details

  • SHA256: f9b5af57fc45cc231ba43f63005b325967aa9312ff427b72fbaa212486081fc4
  • Pointer size: 132 Bytes
  • Size of remote file: 8.05 MB
experiments/image2image/input/cut.png ADDED

Git LFS Details

  • SHA256: b9fd706d629dc4348c7e23df893fb610f91d82fa411f3183ae201656045d1592
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
experiments/image2image/input/depth.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4a853e7c39c0d6e498dda1f604cc073cdce83cc0c33f07d1fab17113e1bfb1d
3
+ size 1228928
experiments/image2image/input/diffuser.png ADDED

Git LFS Details

  • SHA256: dbdf93c9662b781b1b97f1b8f0083191fafb4dda364ebcad1843cbc7b59c0cdb
  • Pointer size: 131 Bytes
  • Size of remote file: 591 kB
experiments/image2image/input/isaacsim.jpg ADDED

Git LFS Details

  • SHA256: bc35297624bddca53332547501d603c9f4fd1afddf5d13171e900ab30efd968a
  • Pointer size: 131 Bytes
  • Size of remote file: 188 kB
experiments/image2image/input/others/CUT.png ADDED

Git LFS Details

  • SHA256: 52b7a9faa4b3d39c7eb88187a0dbd683a584da9b480be577959a82bb029ffa4d
  • Pointer size: 131 Bytes
  • Size of remote file: 101 kB
experiments/image2image/input/others/Gemini.jpg ADDED

Git LFS Details

  • SHA256: 766df392012139bd59ab61e99a8fa75b7465cb7aab4d8dccd589d33a84468440
  • Pointer size: 131 Bytes
  • Size of remote file: 357 kB
experiments/image2image/input/others/isaacsim2.png ADDED

Git LFS Details

  • SHA256: 69697887a249f31463fe1b229366e29c1aabf069acc6cb2297437ab8ab7154ba
  • Pointer size: 131 Bytes
  • Size of remote file: 130 kB
experiments/image2image/input/others/phone1.jpg ADDED

Git LFS Details

  • SHA256: 3c000a35ca272f39472a18a91904cfb8287c9a8ecda8392e0238779de398cc1e
  • Pointer size: 131 Bytes
  • Size of remote file: 375 kB
experiments/image2image/input/real.jpg ADDED

Git LFS Details

  • SHA256: ea34419d86ffa6eb5a3fa57a360b5b0e13799c6db09af80a7d37e3be18aa69dd
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
experiments/image2image/input/rosario.jpg ADDED

Git LFS Details

  • SHA256: 49c61f998bcf5ffa1642c1b6ba215738154871bb45925ee98067ec96a118ca28
  • Pointer size: 131 Bytes
  • Size of remote file: 476 kB
experiments/image2image/output/similarity_heatmap_fid.png ADDED

Git LFS Details

  • SHA256: a6d5e2f6cd4aba132afcc2679afc8a17b6dd5bea31ce80a9840ca3f48bc2e7b9
  • Pointer size: 132 Bytes
  • Size of remote file: 1.02 MB
experiments/rtabmap/behavior_trees/navigate_through_poses_w_replanning_and_recovery.xml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <!--
3
+ This Behavior Tree replans the global path periodically at 1 Hz through an array of poses continuously
4
+ and it also has recovery actions specific to planning / control as well as general system issues.
5
+ -->
6
+ <root main_tree_to_execute="MainTree">
7
+ <BehaviorTree ID="MainTree">
8
+ <RecoveryNode number_of_retries="6" name="NavigateRecovery">
9
+ <PipelineSequence name="NavigateWithReplanning">
10
+ <RateController hz="5.0">
11
+ <RecoveryNode number_of_retries="1" name="ComputePathThroughPoses">
12
+ <ReactiveSequence>
13
+ <RemovePassedGoals input_goals="{goals}" output_goals="{goals}" radius="0.7"/>
14
+ <ComputePathThroughPoses goals="{goals}" path="{path}" planner_id="GridBased"/>
15
+ </ReactiveSequence>
16
+ <ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
17
+ </RecoveryNode>
18
+ </RateController>
19
+ <RecoveryNode number_of_retries="1" name="FollowPath">
20
+ <FollowPath path="{path}" controller_id="FollowPath"/>
21
+ <ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
22
+ </RecoveryNode>
23
+ </PipelineSequence>
24
+ <ReactiveFallback name="RecoveryFallback">
25
+ <GoalUpdated/>
26
+ <RoundRobin name="RecoveryActions">
27
+ <Sequence name="ClearingActions">
28
+ <ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
29
+ <ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
30
+ </Sequence>
31
+ <Spin spin_dist="1.57"/>
32
+ <Wait wait_duration="5"/>
33
+ <BackUp backup_dist="0.30" backup_speed="0.05"/>
34
+ </RoundRobin>
35
+ </ReactiveFallback>
36
+ </RecoveryNode>
37
+ </BehaviorTree>
38
+ </root>
experiments/rtabmap/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <!--
3
+ This Behavior Tree replans the global path periodically at 1 Hz and it also has
4
+ recovery actions specific to planning / control as well as general system issues.
5
+ This will be continuous if a kinematically valid planner is selected.
6
+ -->
7
+ <root main_tree_to_execute="MainTree">
8
+ <BehaviorTree ID="MainTree">
9
+ <RecoveryNode number_of_retries="6" name="NavigateRecovery">
10
+ <PipelineSequence name="NavigateWithReplanning">
11
+ <RateController hz="5.0">
12
+ <RecoveryNode number_of_retries="1" name="ComputePathToPose">
13
+ <ComputePathToPose goal="{goal}" path="{path}" planner_id="GridBased"/>
14
+ <ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
15
+ </RecoveryNode>
16
+ </RateController>
17
+ <RecoveryNode number_of_retries="1" name="FollowPath">
18
+ <FollowPath path="{path}" controller_id="FollowPath"/>
19
+ <ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
20
+ </RecoveryNode>
21
+ </PipelineSequence>
22
+ <ReactiveFallback name="RecoveryFallback">
23
+ <GoalUpdated/>
24
+ <RoundRobin name="RecoveryActions">
25
+ <Sequence name="ClearingActions">
26
+ <ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
27
+ <ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
28
+ </Sequence>
29
+ <Spin spin_dist="1.57"/>
30
+ <Wait wait_duration="5"/>
31
+ <BackUp backup_dist="0.30" backup_speed="0.05"/>
32
+ </RoundRobin>
33
+ </ReactiveFallback>
34
+ </RecoveryNode>
35
+ </BehaviorTree>
36
+ </root>
experiments/rtabmap/nav2.launch.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from launch_ros.actions import Node
4
+ from ament_index_python.packages import get_package_share_directory
5
+ from launch import LaunchDescription
6
+ from launch.actions import IncludeLaunchDescription
7
+ from launch.launch_description_sources import PythonLaunchDescriptionSource
8
+ from launch.actions import DeclareLaunchArgument
9
+ from launch.substitutions import LaunchConfiguration
10
+
11
+ def generate_launch_description():
12
+ # Package Paths
13
+ nav2_bringup_dir = get_package_share_directory('nav2_bringup')
14
+
15
+ # Launch Arguments
16
+ use_sim_time = LaunchConfiguration('use_sim_time', default='true')
17
+ params_file = LaunchConfiguration('params_file', default=os.path.join(
18
+ NAME_OF_YOUR_PKG, 'params', 'nav2_params.yaml'))
19
+
20
+ return LaunchDescription([
21
+ DeclareLaunchArgument(
22
+ 'use_sim_time',
23
+ default_value='true',
24
+ description='Use simulation clock if true'),
25
+
26
+ DeclareLaunchArgument(
27
+ 'params_file',
28
+ default_value=params_file,
29
+ description='Full path to param file to load'),
30
+
31
+
32
+ IncludeLaunchDescription(
33
+ PythonLaunchDescriptionSource(
34
+ os.path.join(nav2_bringup_dir, 'launch', 'navigation_launch.py')
35
+ ),
36
+ launch_arguments={
37
+ 'use_sim_time': use_sim_time,
38
+ 'params_file': params_file,
39
+ 'autostart': 'false'
40
+ }.items(),
41
+ ),
42
+
43
+ Node(
44
+ package='NAME_OF_YOUR_PKG',
45
+ executable='follow_route',
46
+ name='follow_route',
47
+ parameters=[{
48
+ 'use_sim_time': True
49
+ }],
50
+ output='screen'
51
+ ),
52
+ ])
experiments/rtabmap/params/nav2_params.yaml ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GPS WPF CHANGES:
2
+ # - amcl params where removed. They are not needed because global localization is provided
3
+ # by an ekf node on robot_localization fusing gps data with local odometry sources
4
+ # - static layer is removed from both costmaps, in this tutorial we assume there is no map
5
+ # of the environment
6
+ # - global costmap is set to be rolling to allow the robot to traverse big environment by
7
+ # following successive relatively close waypoints that fit in a smaller rolling costmap
8
+
9
+ bt_navigator:
10
+ ros__parameters:
11
+ use_sim_time: True
12
+ global_frame: map
13
+ robot_base_frame: base_link
14
+ odom_topic: /odom
15
+ bt_loop_duration: 10
16
+ default_server_timeout: 20
17
+ wait_for_service_timeout: 1000
18
+ navigators: ["navigate_to_pose", "navigate_through_poses"]
19
+ navigate_to_pose:
20
+ plugin: "nav2_bt_navigator::NavigateToPoseNavigator"
21
+ navigate_through_poses:
22
+ plugin: "nav2_bt_navigator::NavigateThroughPosesNavigator"
23
+ # 'default_nav_through_poses_bt_xml' and 'default_nav_to_pose_bt_xml' are use defaults:
24
+ # nav2_bt_navigator/navigate_to_pose_w_replanning_and_recovery.xml
25
+ # nav2_bt_navigator/navigate_through_poses_w_replanning_and_recovery.xml
26
+ # They can be set here or via a RewrittenYaml remap from a parent launch file to Nav2.
27
+ default_nav_to_pose_bt_xml: $(find-pkg-share NAME_OF_YOUR_PKG)/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml
28
+ default_nav_through_poses_bt_xml: $(find-pkg-share NAME_OF_YOUR_PKG)/behavior_trees/navigate_through_poses_w_replanning_and_recovery.xml
29
+
30
+ # plugin_lib_names is used to add custom BT plugins to the executor (vector of strings).
31
+ # Built-in plugins are added automatically
32
+ # plugin_lib_names: []
33
+
34
+ error_code_name_prefixes:
35
+ - compute_path
36
+ - follow_path
37
+
38
+ controller_server:
39
+ ros__parameters:
40
+ use_sim_time: True
41
+ controller_frequency: 30.0
42
+ min_x_velocity_threshold: 0.001
43
+ min_y_velocity_threshold: 0.5
44
+ min_theta_velocity_threshold: 0.001
45
+ failure_tolerance: 30.0
46
+ progress_checker_plugins: ["progress_checker"]
47
+ goal_checker_plugins: ["general_goal_checker"] # "precise_goal_checker"
48
+ controller_plugins: ["FollowPath"]
49
+
50
+ # Progress checker parameters
51
+ progress_checker:
52
+ plugin: "nav2_controller::SimpleProgressChecker"
53
+ required_movement_radius: 0.5
54
+ movement_time_allowance: 10.0
55
+ # Goal checker parameters
56
+ #precise_goal_checker:
57
+ # plugin: "nav2_controller::SimpleGoalChecker"
58
+ # xy_goal_tolerance: 0.25
59
+ # yaw_goal_tolerance: 0.25
60
+ # stateful: True
61
+ general_goal_checker:
62
+ stateful: True
63
+ plugin: "nav2_controller::SimpleGoalChecker"
64
+ xy_goal_tolerance: 0.25
65
+ yaw_goal_tolerance: 0.25
66
+ # DWB parameters
67
+ FollowPath:
68
+ FollowPath:
69
+ plugin: "nav2_mppi_controller::MPPIController"
70
+ time_steps: 42
71
+ model_dt: 0.05
72
+ batch_size: 2000
73
+ vx_std: 0.2
74
+ vy_std: 0.2
75
+ wz_std: 0.4
76
+ vx_max: 1.2
77
+ vx_min: -0.35
78
+ vy_max: 0.5
79
+ wz_max: 3.5
80
+ iteration_count: 1
81
+ prune_distance: 3.0
82
+ transform_tolerance: 0.2
83
+ temperature: 0.3
84
+ gamma: 0.01
85
+ motion_model: "DiffDrive"
86
+ visualize: false
87
+ regenerate_noises: false
88
+ TrajectoryVisualizer:
89
+ trajectory_step: 5
90
+ time_step: 3
91
+ AckermannConstraints:
92
+ min_turning_r: 0.2
93
+ critics:
94
+ [
95
+ "ConstraintCritic",
96
+ "CostCritic",
97
+ "GoalCritic",
98
+ "GoalAngleCritic",
99
+ "PathAlignCritic",
100
+ "PathFollowCritic",
101
+ "PathAngleCritic",
102
+ "PreferForwardCritic",
103
+ ]
104
+ ConstraintCritic:
105
+ enabled: true
106
+ cost_power: 1
107
+ cost_weight: 4.0
108
+ GoalCritic:
109
+ enabled: true
110
+ cost_power: 1
111
+ cost_weight: 5.0
112
+ threshold_to_consider: 1.4
113
+ GoalAngleCritic:
114
+ enabled: true
115
+ cost_power: 1
116
+ cost_weight: 2.0
117
+ threshold_to_consider: 0.5
118
+ PreferForwardCritic:
119
+ enabled: true
120
+ cost_power: 1
121
+ cost_weight: 5.0
122
+ threshold_to_consider: 0.5
123
+ CostCritic:
124
+ enabled: true
125
+ cost_power: 1
126
+ cost_weight: 3.81
127
+ near_collision_cost: 253
128
+ critical_cost: 300.0
129
+ consider_footprint: false
130
+ collision_cost: 1000000.0
131
+ near_goal_distance: 1.0
132
+ trajectory_point_step: 2
133
+ PathAlignCritic:
134
+ enabled: true
135
+ cost_power: 1
136
+ cost_weight: 15.0
137
+ max_path_occupancy_ratio: 0.05
138
+ trajectory_point_step: 4
139
+ threshold_to_consider: 0.25
140
+ offset_from_furthest: 2
141
+ use_path_orientations: false
142
+ PathFollowCritic:
143
+ enabled: true
144
+ cost_power: 1
145
+ cost_weight: 5.0
146
+ offset_from_furthest: 5
147
+ threshold_to_consider: 1.4
148
+ PathAngleCritic:
149
+ enabled: true
150
+ cost_power: 1
151
+ cost_weight: 7.0
152
+ offset_from_furthest: 4
153
+ threshold_to_consider: 0.25
154
+ max_angle_to_furthest: 1.0
155
+ mode: 0
156
+ # TwirlingCritic:
157
+ # enabled: true
158
+ # twirling_cost_power: 1
159
+ # twirling_cost_weight: 10.0
160
+
161
+ # GPS WPF CHANGE: Remove static layer
162
+ local_costmap:
163
+ local_costmap:
164
+ ros__parameters:
165
+ use_sim_time: True
166
+ update_frequency: 5.0
167
+ publish_frequency: 5.0
168
+ global_frame: map
169
+ robot_base_frame: base_link
170
+ rolling_window: true
171
+ width: 10
172
+ height: 10
173
+ resolution: 0.1
174
+ robot_radius: 0.22
175
+ plugins: ["voxel_layer", "inflation_layer"]
176
+ inflation_layer:
177
+ plugin: "nav2_costmap_2d::InflationLayer"
178
+ cost_scaling_factor: 3.0
179
+ inflation_radius: 0.55
180
+ voxel_layer:
181
+ plugin: "nav2_costmap_2d::VoxelLayer"
182
+ enabled: false
183
+ publish_voxel_map: True
184
+ origin_z: 0.0
185
+ z_resolution: 0.05
186
+ z_voxels: 16
187
+ max_obstacle_height: 2.0
188
+ mark_threshold: 0
189
+ observation_sources: pointcloud
190
+ pointcloud:
191
+ topic: /cloud_map
192
+ max_obstacle_height: 2.0
193
+ min_obstacle_height: 0.0
194
+ obstacle_range: 2.5
195
+ raytrace_range: 3.0
196
+ observation_persistence: 0.0
197
+ data_type: "PointCloud2"
198
+ marking: True
199
+ clearing: True
200
+ # observation_sources: scan
201
+ # scan:
202
+ # topic: /scan
203
+ # max_obstacle_height: 2.0
204
+ # clearing: True
205
+ # marking: True
206
+ # data_type: "LaserScan"
207
+ # raytrace_max_range: 3.0
208
+ # raytrace_min_range: 0.0
209
+ # obstacle_max_range: 2.5
210
+ # obstacle_min_range: 0.0
211
+ always_send_full_costmap: true
212
+
213
+ # GPS WPF CHANGE: Remove static layer
214
+ global_costmap:
215
+ global_costmap:
216
+ ros__parameters:
217
+ use_sim_time: True
218
+ update_frequency: 1.0
219
+ publish_frequency: 1.0
220
+ global_frame: map
221
+ robot_base_frame: base_link
222
+ robot_radius: 0.22
223
+ resolution: 0.25
224
+ # When using GPS navigation you will potentially traverse huge environments which are not practical to
225
+ # fit on a big static costmap. Thus it is recommended to use a rolling global costmap large enough to
226
+ # contain each pair of successive waypoints. See: https://github.com/ros-planning/navigation2/issues/2174
227
+ rolling_window: True
228
+ width: 30
229
+ height: 30
230
+ # origin_x: 0.0
231
+ # origin_y: 0.0
232
+ track_unknown_space: false
233
+ # no static map
234
+ plugins: ["obstacle_layer", "inflation_layer"]
235
+ obstacle_layer:
236
+ plugin: "nav2_costmap_2d::ObstacleLayer"
237
+ enabled: false
238
+ observation_sources: pointcloud
239
+ pointcloud:
240
+ topic: /cloud_map
241
+ max_obstacle_height: 2.0
242
+ min_obstacle_height: 0.0
243
+ obstacle_range: 2.5
244
+ raytrace_range: 3.0
245
+ observation_persistence: 0.0
246
+ data_type: "PointCloud2"
247
+ marking: True
248
+ clearing: True
249
+ # observation_sources: scan
250
+ # scan:
251
+ # topic: /scan
252
+ # max_obstacle_height: 2.0
253
+ # clearing: True
254
+ # marking: True
255
+ # data_type: "LaserScan"
256
+ # raytrace_max_range: 3.0
257
+ # raytrace_min_range: 0.0
258
+ # obstacle_max_range: 2.5
259
+ # obstacle_min_range: 0.0
260
+ # # outdoors there will probably be more inf points
261
+ # inf_is_valid: true
262
+ inflation_layer:
263
+ plugin: "nav2_costmap_2d::InflationLayer"
264
+ cost_scaling_factor: 3.0
265
+ inflation_radius: 0.55
266
+ always_send_full_costmap: true
267
+
268
+ # The yaml_filename does not need to be specified since it going to be set by defaults in launch.
269
+ # If you'd rather set it in the yaml, remove the default "map" value in the tb3_simulation_launch.py
270
+ # file & provide full path to map below. If CLI map configuration or launch default is provided, that will be used.
271
+ # map_server:
272
+ # ros__parameters:
273
+ # yaml_filename: ""
274
+
275
+ map_saver:
276
+ ros__parameters:
277
+ save_map_timeout: 5.0
278
+ free_thresh_default: 0.25
279
+ occupied_thresh_default: 0.65
280
+ map_subscribe_transient_local: True
281
+ service_introspection_mode: "disabled"
282
+
283
+ planner_server:
284
+ ros__parameters:
285
+ use_sim_time: True
286
+ expected_planner_frequency: 20.0
287
+ planner_plugins: ["GridBased"]
288
+ costmap_update_timeout: 1.0
289
+ service_introspection_mode: "disabled"
290
+ GridBased:
291
+ plugin: "nav2_navfn_planner/NavfnPlanner"
292
+ tolerance: 0.5
293
+ use_astar: false
294
+ allow_unknown: true
295
+
296
+ smoother_server:
297
+ ros__parameters:
298
+ use_sim_time: True
299
+ smoother_plugins: ["simple_smoother"]
300
+ simple_smoother:
301
+ plugin: "nav2_smoother::SimpleSmoother"
302
+ tolerance: 1.0e-10
303
+ max_its: 1000
304
+ refinement_num: 2
305
+ # True for Hybrid A* or State Lattice to not smooth over directional changes
306
+ enforce_path_inversion: True
307
+ do_refinement: True
308
+
309
+ behavior_server:
310
+ ros__parameters:
311
+ use_sim_time: True
312
+ local_costmap_topic: local_costmap/costmap_raw
313
+ global_costmap_topic: global_costmap/costmap_raw
314
+ local_footprint_topic: local_costmap/published_footprint
315
+ global_footprint_topic: global_costmap/published_footprint
316
+ cycle_frequency: 10.0
317
+ behavior_plugins:
318
+ ["spin", "backup", "drive_on_heading", "assisted_teleop", "wait"]
319
+ spin:
320
+ plugin: "nav2_behaviors/Spin"
321
+ backup:
322
+ plugin: "nav2_behaviors/BackUp"
323
+ acceleration_limit: 2.5
324
+ deceleration_limit: -2.5
325
+ minimum_speed: 0.10
326
+ drive_on_heading:
327
+ plugin: "nav2_behaviors/DriveOnHeading"
328
+ acceleration_limit: 2.5
329
+ deceleration_limit: -2.5
330
+ minimum_speed: 0.10
331
+ wait:
332
+ plugin: "nav2_behaviors/Wait"
333
+ assisted_teleop:
334
+ plugin: "nav2_behaviors/AssistedTeleop"
335
+ local_frame: odom
336
+ global_frame: map
337
+ robot_base_frame: base_link
338
+ transform_tolerance: 0.2
339
+ simulate_ahead_time: 2.0
340
+ max_rotational_vel: 1.0
341
+ min_rotational_vel: 0.4
342
+ rotational_acc_lim: 3.2
343
+
344
+ waypoint_follower:
345
+ ros__parameters:
346
+ use_sim_time: True
347
+ loop_rate: 20
348
+ stop_on_failure: false
349
+ service_introspection_mode: "disabled"
350
+ waypoint_task_executor_plugin: "wait_at_waypoint"
351
+ wait_at_waypoint:
352
+ plugin: "nav2_waypoint_follower::WaitAtWaypoint"
353
+ enabled: True
354
+ waypoint_pause_duration: 200
355
+
356
+ velocity_smoother:
357
+ ros__parameters:
358
+ use_sim_time: True
359
+ smoothing_frequency: 20.0
360
+ scale_velocities: False
361
+ feedback: "OPEN_LOOP"
362
+ max_velocity: [1.0, 0.0, 2.0]
363
+ min_velocity: [-0.5, 0.0, -2.0]
364
+ max_accel: [2.5, 0.0, 3.2]
365
+ max_decel: [-2.5, 0.0, -3.2]
366
+ odom_topic: "odom"
367
+ odom_duration: 0.1
368
+ deadband_velocity: [0.0, 0.0, 0.0]
369
+ velocity_timeout: 1.0
370
+
371
+ # collision_monitor:
372
+ # ros__parameters:
373
+ # base_frame_id: "base_footprint"
374
+ # odom_frame_id: "odom"
375
+ # cmd_vel_in_topic: "cmd_vel_smoothed"
376
+ # cmd_vel_out_topic: "cmd_vel"
377
+ # state_topic: "collision_monitor_state"
378
+ # transform_tolerance: 0.2
379
+ # source_timeout: 1.0
380
+ # base_shift_correction: True
381
+ # stop_pub_timeout: 2.0
382
+ # # Polygons represent zone around the robot for "stop", "slowdown" and "limit" action types,
383
+ # # and robot footprint for "approach" action type.
384
+ # polygons: ["FootprintApproach"]
385
+ # FootprintApproach:
386
+ # type: "polygon"
387
+ # action_type: "approach"
388
+ # footprint_topic: "/local_costmap/published_footprint"
389
+ # time_before_collision: 2.0
390
+ # simulation_time_step: 0.1
391
+ # min_points: 6
392
+ # visualize: False
393
+ # enabled: True
394
+ # observation_sources: ["scan"]
395
+ # scan:
396
+ # type: "scan"
397
+ # topic: "scan"
398
+ # min_height: 0.15
399
+ # max_height: 2.0
400
+ # enabled: True
401
+
402
+ # docking_server:
403
+ # ros__parameters:
404
+ # controller_frequency: 50.0
405
+ # initial_perception_timeout: 5.0
406
+ # wait_charge_timeout: 5.0
407
+ # dock_approach_timeout: 30.0
408
+ # undock_linear_tolerance: 0.05
409
+ # undock_angular_tolerance: 0.1
410
+ # max_retries: 3
411
+ # base_frame: "base_link"
412
+ # fixed_frame: "odom"
413
+ # dock_prestaging_tolerance: 0.5
414
+ # service_introspection_mode: "disabled"
415
+
416
+ # # Types of docks
417
+ # dock_plugins: ["simple_charging_dock"]
418
+ # simple_charging_dock:
419
+ # plugin: "opennav_docking::SimpleChargingDock"
420
+ # docking_threshold: 0.05
421
+ # staging_x_offset: -0.7
422
+ # use_external_detection_pose: true
423
+ # use_battery_status: false # true
424
+ # use_stall_detection: false # true
425
+ # dock_direction: "forward"
426
+
427
+ # external_detection_timeout: 1.0
428
+ # external_detection_translation_x: -0.18
429
+ # external_detection_translation_y: 0.0
430
+ # external_detection_rotation_roll: -1.57
431
+ # external_detection_rotation_pitch: -1.57
432
+ # external_detection_rotation_yaw: 0.0
433
+ # filter_coef: 0.1
434
+
435
+ # # Dock instances
436
+ # # The following example illustrates configuring dock instances.
437
+ # # docks: ['home_dock'] # Input your docks here
438
+ # # home_dock:
439
+ # # type: 'simple_charging_dock'
440
+ # # frame: map
441
+ # # pose: [0.0, 0.0, 0.0]
442
+
443
+ # controller:
444
+ # k_phi: 3.0
445
+ # k_delta: 2.0
446
+ # v_linear_min: 0.15
447
+ # v_linear_max: 0.15
448
+ # use_collision_detection: true
449
+ # costmap_topic: "/local_costmap/costmap_raw"
450
+ # footprint_topic: "/local_costmap/published_footprint"
451
+ # transform_tolerance: 0.1
452
+ # projection_time: 5.0
453
+ # simulation_step: 0.1
454
+ # dock_collision_threshold: 0.3
455
+
456
+ # loopback_simulator:
457
+ # ros__parameters:
458
+ # base_frame_id: "base_footprint"
459
+ # odom_frame_id: "odom"
460
+ # map_frame_id: "map"
461
+ # scan_frame_id: "base_scan" # tb4_loopback_simulator.launch.py remaps to 'rplidar_link'
462
+ # update_duration: 0.02
463
+ # scan_range_min: 0.05
464
+ # scan_range_max: 30.0
465
+ # scan_angle_min: -3.1415
466
+ # scan_angle_max: 3.1415
467
+ # scan_angle_increment: 0.02617
468
+ # scan_use_inf: true
experiments/rtabmap/params/odom.txt ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Param: BRIEF/Bytes = "32" [Bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes.]
2
+ Param: BRISK/Octaves = "3" [Detection octaves. Use 0 to do single scale.]
3
+ Param: BRISK/PatternScale = "1" [Apply this scale to the pattern used for sampling the neighbourhood of a keypoint.]
4
+ Param: BRISK/Thresh = "30" [FAST/AGAST detection threshold score.]
5
+ Param: FAST/CV = "0" [Enable FastCV implementation if non-zero (and RTAB-Map is built with FastCV support). Values should be 9 and 10.]
6
+ Param: FAST/Gpu = "false" [GPU-FAST: Use GPU version of FAST. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
7
+ Param: FAST/GpuKeypointsRatio = "0.05" [Used with FAST GPU.]
8
+ Param: FAST/GridCols = "0" [Grid cols (0 to disable). Adapts the detector to partition the source image into a grid and detect points in each cell.]
9
+ Param: FAST/GridRows = "0" [Grid rows (0 to disable). Adapts the detector to partition the source image into a grid and detect points in each cell.]
10
+ Param: FAST/MaxThreshold = "200" [Maximum threshold. Used only when FAST/GridRows and FAST/GridCols are set.]
11
+ Param: FAST/MinThreshold = "7" [Minimum threshold. Used only when FAST/GridRows and FAST/GridCols are set.]
12
+ Param: FAST/NonmaxSuppression = "true" [If true, non-maximum suppression is applied to detected corners (keypoints).]
13
+ Param: FAST/Threshold = "20" [Threshold on difference between intensity of the central pixel and pixels of a circle around this pixel.]
14
+ Param: FREAK/NOctaves = "4" [Number of octaves covered by the detected keypoints.]
15
+ Param: FREAK/OrientationNormalized = "true" [Enable orientation normalization.]
16
+ Param: FREAK/PatternScale = "22" [Scaling of the description pattern.]
17
+ Param: FREAK/ScaleNormalized = "true" [Enable scale normalization.]
18
+ Param: GFTT/BlockSize = "3" []
19
+ Param: GFTT/Gpu = "false" [GPU-GFTT: Use GPU version of GFTT. This option is enabled only if OpenCV>=3 is built with CUDA and GPUs are detected.]
20
+ Param: GFTT/K = "0.04" []
21
+ Param: GFTT/MinDistance = "7" []
22
+ Param: GFTT/QualityLevel = "0.001" []
23
+ Param: GFTT/UseHarrisDetector = "false" []
24
+ Param: GMS/ThresholdFactor = "6.0" [The higher, the less matches.]
25
+ Param: GMS/WithRotation = "false" [Take rotation transformation into account.]
26
+ Param: GMS/WithScale = "false" [Take scale transformation into account.]
27
+ Param: GTSAM/IncRelinearizeSkip = "1" [Only relinearize any variables every X calls to ISAM2::update(). See GTSAM::ISAM2 doc for more info.]
28
+ Param: GTSAM/IncRelinearizeThreshold = "0.01" [Only relinearize variables whose linear delta magnitude is greater than this threshold. See GTSAM::ISAM2 doc for more info.]
29
+ Param: GTSAM/Incremental = "false" [Do graph optimization incrementally (iSAM2) to increase optimization speed on loop closures. Note that only GaussNewton and Dogleg optimization algorithms are supported (GTSAM/Optimizer) in this mode.]
30
+ Param: GTSAM/Optimizer = "1" [0=Levenberg 1=GaussNewton 2=Dogleg]
31
+ Param: KAZE/Diffusivity = "1" [Diffusivity type: 0=DIFF_PM_G1, 1=DIFF_PM_G2, 2=DIFF_WEICKERT or 3=DIFF_CHARBONNIER.]
32
+ Param: KAZE/Extended = "false" [Set to enable extraction of extended (128-byte) descriptor.]
33
+ Param: KAZE/NOctaveLayers = "4" [Default number of sublevels per scale level.]
34
+ Param: KAZE/NOctaves = "4" [Maximum octave evolution of the image.]
35
+ Param: KAZE/Threshold = "0.001" [Detector response threshold to accept keypoint.]
36
+ Param: KAZE/Upright = "false" [Set to enable use of upright descriptors (non rotation-invariant).]
37
+ Param: Kp/ByteToFloat = "false" [For Kp/NNStrategy=1, binary descriptors are converted to float by converting each byte to float instead of converting each bit to float. When converting bytes instead of bits, less memory is used and search is faster at the cost of slightly less accurate matching.]
38
+ Param: ORB/EdgeThreshold = "19" [This is size of the border where the features are not detected. It should roughly match the patchSize parameter.]
39
+ Param: ORB/FirstLevel = "0" [It should be 0 in the current implementation.]
40
+ Param: ORB/Gpu = "false" [GPU-ORB: Use GPU version of ORB. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
41
+ Param: ORB/NLevels = "3" [The number of pyramid levels. The smallest level will have linear size equal to input_image_linear_size/pow(scaleFactor, nlevels).]
42
+ Param: ORB/PatchSize = "31" [size of the patch used by the oriented BRIEF descriptor. Of course, on smaller pyramid layers the perceived image area covered by a feature will be larger.]
43
+ Param: ORB/ScaleFactor = "2" [Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor will mean that to cover certain scale range you will need more pyramid levels and so the speed will suffer.]
44
+ Param: ORB/ScoreType = "0" [The default HARRIS_SCORE=0 means that Harris algorithm is used to rank features (the score is written to KeyPoint::score and is used to retain best nfeatures features); FAST_SCORE=1 is alternative value of the parameter that produces slightly less stable keypoints, but it is a little faster to compute.]
45
+ Param: ORB/WTA_K = "2" [The number of points that produce each element of the oriented BRIEF descriptor. The default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 random points (of course, those point coordinates are random, but they are generated from the pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3).]
46
+ Param: Odom/AlignWithGround = "false" [Align odometry with the ground on initialization.]
47
+ Param: Odom/Deskewing = "true" [Lidar deskewing. If input lidar has time channel, it will be deskewed with a constant motion model (with IMU orientation and/or guess if provided).]
48
+ Param: Odom/FillInfoData = "true" [Fill info with data (inliers/outliers features).]
49
+ Param: Odom/FilteringStrategy = "0" [0=No filtering 1=Kalman filtering 2=Particle filtering. This filter is used to smooth the odometry output.]
50
+ Param: Odom/GuessMotion = "true" [Guess next transformation from the last motion computed.]
51
+ Param: Odom/GuessSmoothingDelay = "0" [Guess smoothing delay (s). Estimated velocity is averaged based on last transforms up to this maximum delay. This can help to get smoother velocity prediction. Last velocity computed is used directly if "Odom/FilteringStrategy" is set or the delay is below the odometry rate.]
52
+ Param: Odom/Holonomic = "true" [If the robot is holonomic (strafing commands can be issued). If not, y value will be estimated from x and yaw values (y=x*tan(yaw)).]
53
+ Param: Odom/ImageBufferSize = "1" [Data buffer size (0 min inf).]
54
+ Param: Odom/ImageDecimation = "1" [Decimation of the RGB image before registration. If depth size is larger than decimated RGB size, depth is decimated to be always at most equal to RGB size. If Vis/DepthAsMask is true and if depth is smaller than decimated RGB, depth may be interpolated to match RGB size for feature detection.]
55
+ Param: Odom/KalmanMeasurementNoise = "0.01" [Process measurement covariance value.]
56
+ Param: Odom/KalmanProcessNoise = "0.001" [Process noise covariance value.]
57
+ Param: Odom/KeyFrameThr = "0.3" [[Visual] Create a new keyframe when the number of inliers drops under this ratio of features in last frame. Setting the value to 0 means that a keyframe is created for each processed frame.]
58
+ Param: Odom/ParticleLambdaR = "100" [Lambda of rotational components (roll,pitch,yaw).]
59
+ Param: Odom/ParticleLambdaT = "100" [Lambda of translation components (x,y,z).]
60
+ Param: Odom/ParticleNoiseR = "0.002" [Noise (rad) of rotational components (roll,pitch,yaw).]
61
+ Param: Odom/ParticleNoiseT = "0.002" [Noise (m) of translation components (x,y,z).]
62
+ Param: Odom/ParticleSize = "400" [Number of particles of the filter.]
63
+ Param: Odom/ResetCountdown = "0" [Automatically reset odometry after X consecutive images where odometry cannot be computed (a value of 0 disables auto-reset). When a reset occurs, odometry resumes from the last successfully computed pose with large covariance to trigger a new map. If external odometry is used, it will also be reset based on the motion estimated relative to the last computed pose but no large covariance will be received, so that a new map won't be triggered.]
64
+ Param: Odom/ScanKeyFrameThr = "0.9" [[Geometry] Create a new keyframe when the number of ICP inliers drops under this ratio of points in last frame's scan. Setting the value to 0 means that a keyframe is created for each processed frame.]
65
+ Param: Odom/Strategy = "0" [0=Frame-to-Map (F2M) 1=Frame-to-Frame (F2F) 2=Fovis 3=viso2 4=DVO-SLAM 5=ORB_SLAM 6=OKVIS 7=LOAM 8=MSCKF_VIO 9=VINS-Fusion 10=OpenVINS 11=FLOAM 12=Open3D 13=cuVSLAM]
66
+ Param: Odom/VisKeyFrameThr = "150" [[Visual] Create a new keyframe when the number of inliers drops under this threshold. Setting the value to 0 means that a keyframe is created for each processed frame.]
67
+ Param: OdomF2M/BundleAdjustment = "1" [Local bundle adjustment: 0=disabled, 1=g2o, 2=cvsba, 3=Ceres.]
68
+ Param: OdomF2M/BundleAdjustmentMaxFrames = "10" [Maximum frames used for bundle adjustment (0=inf or all current frames in the local map).]
69
+ Param: OdomF2M/BundleAdjustmentMaxKeyFramesPerFeature = "0" [Maximum keyframes per feature for bundle adjustment. 0 means not limit.]
70
+ Param: OdomF2M/BundleAdjustmentMinMotion = "0.0" [To create a new keyframe with bundle adjustment, a minimum motion (in pixels) can be required. The motion is computed by the average distance between inliers of the previous keyframe and new frame.]
71
+ Param: OdomF2M/BundleUpdateFeatureMapOnAllFrames = "false" [Update 3D local feature map on every frame with bundle adjustment. Recommended if Vis/DepthAsMask=false and Mem/UseOdomFeatures=true so that features without depth are better triangulated on every frame (not only on keyframes). If disabled, the feature map is updated only when a new keyframe is added (legacy approach).]
72
+ Param: OdomF2M/FloorThreshold = "0.0" [[Visual] Only track features in 3D feature map that are over this threshold (height in base frame). Can be useful to ignore reflections on the floor. 0 means disabled.]
73
+ Param: OdomF2M/InitDepthFactor = "0.05" [[Visual] Depth factor used to initialize depth of features without depth. Depth = Factor * fx.]
74
+ Param: OdomF2M/MaxNewFeatures = "0" [[Visual] Maximum features (sorted by keypoint response) added to local map from a new key-frame. 0 means no limit.]
75
+ Param: OdomF2M/MaxSize = "2000" [[Visual] Local map size: If > 0 (example 5000), the odometry will maintain a local map of X maximum words.]
76
+ Param: OdomF2M/ScanMaxSize = "2000" [[Geometry] Maximum local scan map size.]
77
+ Param: OdomF2M/ScanRange = "0" [[Geometry] Distance Range used to filter points of local map (when > 0). 0 means local map is updated using time and not range.]
78
+ Param: OdomF2M/ScanSubtractAngle = "45" [[Geometry] Max angle (degrees) used to filter points of a new added scan to local map (when "OdomF2M/ScanSubtractRadius">0). 0 means any angle.]
79
+ Param: OdomF2M/ScanSubtractRadius = "0.05" [[Geometry] Radius used to filter points of a new added scan to local map. This could match the voxel size of the scans.]
80
+ Param: OdomF2M/ValidDepthRatio = "0.75" [If a new frame has points without valid depth, they are added to local feature map only if points with valid depth on total points is over this ratio. Setting to 1 means no points without valid depth are added to local feature map.]
81
+ Param: OdomFovis/BucketHeight = "80" []
82
+ Param: OdomFovis/BucketWidth = "80" []
83
+ Param: OdomFovis/CliqueInlierThreshold = "0.1" [See Howard's greedy max-clique algorithm for determining the maximum set of mutually consisten feature matches. This specifies the compatibility threshold, in meters.]
84
+ Param: OdomFovis/FastThreshold = "20" [FAST threshold.]
85
+ Param: OdomFovis/FastThresholdAdaptiveGain = "0.005" [FAST threshold adaptive gain.]
86
+ Param: OdomFovis/FeatureSearchWindow = "25" [Specifies the size of the search window to apply when searching for feature matches across time frames. The search is conducted around the feature location predicted by the initial rotation estimate.]
87
+ Param: OdomFovis/FeatureWindowSize = "9" [The size of the n x n image patch surrounding each feature, used for keypoint matching.]
88
+ Param: OdomFovis/InlierMaxReprojectionError = "1.5" [The maximum image-space reprojection error (in pixels) a feature match is allowed to have and still be considered an inlier in the set of features used for motion estimation.]
89
+ Param: OdomFovis/MaxKeypointsPerBucket = "25" []
90
+ Param: OdomFovis/MaxMeanReprojectionError = "10.0" [Maximum mean reprojection error over the inlier feature matches for the motion estimate to be considered valid.]
91
+ Param: OdomFovis/MaxPyramidLevel = "3" [The maximum Gaussian pyramid level to process the image at. Pyramid level 1 corresponds to the original image.]
92
+ Param: OdomFovis/MinFeaturesForEstimate = "20" [Minimum number of features in the inlier set for the motion estimate to be considered valid.]
93
+ Param: OdomFovis/MinPyramidLevel = "0" [The minimum pyramid level.]
94
+ Param: OdomFovis/StereoMaxDisparity = "128" []
95
+ Param: OdomFovis/StereoMaxDistEpipolarLine = "1.5" []
96
+ Param: OdomFovis/StereoMaxRefinementDisplacement = "1.0" []
97
+ Param: OdomFovis/StereoRequireMutualMatch = "true" []
98
+ Param: OdomFovis/TargetPixelsPerFeature = "250" [Specifies the desired feature density as a ratio of input image pixels per feature detected. This number is used to control the adaptive feature thresholding.]
99
+ Param: OdomFovis/UpdateTargetFeaturesWithRefined = "false" [When subpixel refinement is enabled, the refined feature locations can be saved over the original feature locations. This has a slightly negative impact on frame-to-frame visual odometry, but is likely better when using this library as part of a visual SLAM algorithm.]
100
+ Param: OdomFovis/UseAdaptiveThreshold = "true" [Use FAST adaptive threshold.]
101
+ Param: OdomFovis/UseBucketing = "true" []
102
+ Param: OdomFovis/UseHomographyInitialization = "true" [Use homography initialization.]
103
+ Param: OdomFovis/UseImageNormalization = "false" []
104
+ Param: OdomFovis/UseSubpixelRefinement = "true" [Specifies whether or not to refine feature matches to subpixel resolution.]
105
+ Param: OdomLOAM/AngVar = "0.01" [Angular output variance.]
106
+ Param: OdomLOAM/LinVar = "0.01" [Linear output variance.]
107
+ Param: OdomLOAM/LocalMapping = "true" [Local mapping. It adds more time to compute odometry, but accuracy is significantly improved.]
108
+ Param: OdomLOAM/Resolution = "0.2" [Map resolution]
109
+ Param: OdomLOAM/ScanPeriod = "0.1" [Scan period (s)]
110
+ Param: OdomLOAM/Sensor = "2" [Velodyne sensor: 0=VLP-16, 1=HDL-32, 2=HDL-64E]
111
+ Param: OdomMSCKF/FastThreshold = "10" []
112
+ Param: OdomMSCKF/GridCol = "5" []
113
+ Param: OdomMSCKF/GridMaxFeatureNum = "4" []
114
+ Param: OdomMSCKF/GridMinFeatureNum = "3" []
115
+ Param: OdomMSCKF/GridRow = "4" []
116
+ Param: OdomMSCKF/InitCovAccBias = "0.01" []
117
+ Param: OdomMSCKF/InitCovExRot = "0.00030462" []
118
+ Param: OdomMSCKF/InitCovExTrans = "0.000025" []
119
+ Param: OdomMSCKF/InitCovGyroBias = "0.01" []
120
+ Param: OdomMSCKF/InitCovVel = "0.25" []
121
+ Param: OdomMSCKF/MaxCamStateSize = "20" []
122
+ Param: OdomMSCKF/MaxIteration = "30" []
123
+ Param: OdomMSCKF/NoiseAcc = "0.05" []
124
+ Param: OdomMSCKF/NoiseAccBias = "0.01" []
125
+ Param: OdomMSCKF/NoiseFeature = "0.035" []
126
+ Param: OdomMSCKF/NoiseGyro = "0.005" []
127
+ Param: OdomMSCKF/NoiseGyroBias = "0.001" []
128
+ Param: OdomMSCKF/OptTranslationThreshold = "0" []
129
+ Param: OdomMSCKF/PatchSize = "15" []
130
+ Param: OdomMSCKF/PositionStdThreshold = "8.0" []
131
+ Param: OdomMSCKF/PyramidLevels = "3" []
132
+ Param: OdomMSCKF/RansacThreshold = "3" []
133
+ Param: OdomMSCKF/RotationThreshold = "0.2618" []
134
+ Param: OdomMSCKF/StereoThreshold = "5" []
135
+ Param: OdomMSCKF/TrackPrecision = "0.01" []
136
+ Param: OdomMSCKF/TrackingRateThreshold = "0.5" []
137
+ Param: OdomMSCKF/TranslationThreshold = "0.4" []
138
+ Param: OdomMono/InitMinFlow = "100" [Minimum optical flow required for the initialization step.]
139
+ Param: OdomMono/InitMinTranslation = "0.1" [Minimum translation required for the initialization step.]
140
+ Param: OdomMono/MaxVariance = "0.01" [Maximum variance to add new points to local map.]
141
+ Param: OdomMono/MinTranslation = "0.02" [Minimum translation to add new points to local map. On initialization, translation x 5 is used as the minimum.]
142
+ Param: OdomOKVIS/ConfigPath = "" [Path of OKVIS config file.]
143
+ Param: OdomORBSLAM/AccNoise = "0.1" [IMU accelerometer "white noise".]
144
+ Param: OdomORBSLAM/AccWalk = "0.0001" [IMU accelerometer "random walk".]
145
+ Param: OdomORBSLAM/Bf = "0.076" [Fake IR projector baseline (m) used only when stereo is not used.]
146
+ Param: OdomORBSLAM/Fps = "0.0" [Camera FPS (0 to estimate from input data).]
147
+ Param: OdomORBSLAM/GyroNoise = "0.01" [IMU gyroscope "white noise".]
148
+ Param: OdomORBSLAM/GyroWalk = "0.000001" [IMU gyroscope "random walk".]
149
+ Param: OdomORBSLAM/Inertial = "false" [Enable IMU. Only supported with ORB_SLAM3.]
150
+ Param: OdomORBSLAM/MapSize = "3000" [Maximum size of the feature map (0 means infinite). Only supported with ORB_SLAM2.]
151
+ Param: OdomORBSLAM/MaxFeatures = "1000" [Maximum ORB features extracted per frame.]
152
+ Param: OdomORBSLAM/SamplingRate = "0" [IMU sampling rate (0 to estimate from input data).]
153
+ Param: OdomORBSLAM/ThDepth = "40.0" [Close/Far threshold. Baseline times.]
154
+ Param: OdomORBSLAM/VocPath = "" [Path to ORB vocabulary (*.txt).]
155
+ Param: OdomOpen3D/MaxDepth = "3.0" [Maximum depth.]
156
+ Param: OdomOpen3D/Method = "0" [Registration method: 0=PointToPlane, 1=Intensity, 2=Hybrid.]
157
+ Param: OdomOpenVINS/AccelerometerNoiseDensity = "0.01" [[m/s^2/sqrt(Hz)] (accel "white noise")]
158
+ Param: OdomOpenVINS/AccelerometerRandomWalk = "0.001" [[m/s^3/sqrt(Hz)] (accel bias diffusion)]
159
+ Param: OdomOpenVINS/CalibCamExtrinsics = "false" [Bool to determine whether or not to calibrate imu-to-camera pose]
160
+ Param: OdomOpenVINS/CalibCamIntrinsics = "false" [Bool to determine whether or not to calibrate camera intrinsics]
161
+ Param: OdomOpenVINS/CalibCamTimeoffset = "false" [Bool to determine whether or not to calibrate camera to IMU time offset]
162
+ Param: OdomOpenVINS/CalibIMUGSensitivity = "false" [Bool to determine whether or not to calibrate the Gravity sensitivity]
163
+ Param: OdomOpenVINS/CalibIMUIntrinsics = "false" [Bool to determine whether or not to calibrate the IMU intrinsics]
164
+ Param: OdomOpenVINS/DtSLAMDelay = "0.0" [Delay, in seconds, that we should wait from init before we start estimating SLAM features]
165
+ Param: OdomOpenVINS/FeatRepMSCKF = "0" [What representation our features are in (msckf features)]
166
+ Param: OdomOpenVINS/FeatRepSLAM = "4" [What representation our features are in (slam features)]
167
+ Param: OdomOpenVINS/FiMaxBaseline = "40" [Max baseline ratio to accept triangulated features]
168
+ Param: OdomOpenVINS/FiMaxCondNumber = "10000" [Max condition number of linear triangulation matrix accept triangulated features]
169
+ Param: OdomOpenVINS/FiMaxRuns = "5" [Max runs for Levenberg-Marquardt]
170
+ Param: OdomOpenVINS/FiRefineFeatures = "true" [If we should perform Levenberg-Marquardt refinement]
171
+ Param: OdomOpenVINS/FiTriangulate1d = "false" [If we should perform 1d triangulation instead of 3d]
172
+ Param: OdomOpenVINS/GravityMag = "9.81" [Gravity magnitude in the global frame (i.e. should be 9.81 typically)]
173
+ Param: OdomOpenVINS/GyroscopeNoiseDensity = "0.001" [[rad/s/sqrt(Hz)] (gyro "white noise")]
174
+ Param: OdomOpenVINS/GyroscopeRandomWalk = "0.0001" [[rad/s^2/sqrt(Hz)] (gyro bias diffusion)]
175
+ Param: OdomOpenVINS/InitDynInflationBa = "100.0" [What to inflate the recovered bias_a covariance by]
176
+ Param: OdomOpenVINS/InitDynInflationBg = "10.0" [What to inflate the recovered bias_g covariance by]
177
+ Param: OdomOpenVINS/InitDynInflationOri = "10.0" [What to inflate the recovered q_GtoI covariance by]
178
+ Param: OdomOpenVINS/InitDynInflationVel = "100.0" [What to inflate the recovered v_IinG covariance by]
179
+ Param: OdomOpenVINS/InitDynMLEMaxIter = "50" [How many iterations the MLE refinement should use (zero to skip the MLE)]
180
+ Param: OdomOpenVINS/InitDynMLEMaxThreads = "6" [How many threads the MLE should use]
181
+ Param: OdomOpenVINS/InitDynMLEMaxTime = "0.05" [How many seconds the MLE should be completed in]
182
+ Param: OdomOpenVINS/InitDynMLEOptCalib = "false" [If we should optimize calibration during intialization (not recommended)]
183
+ Param: OdomOpenVINS/InitDynMinDeg = "10.0" [Orientation change needed to try to init]
184
+ Param: OdomOpenVINS/InitDynMinRecCond = "1e-15" [Reciprocal condition number thresh for info inversion]
185
+ Param: OdomOpenVINS/InitDynNumPose = "6" [Number of poses to use within our window time (evenly spaced)]
186
+ Param: OdomOpenVINS/InitDynUse = "false" [If dynamic initialization should be used]
187
+ Param: OdomOpenVINS/InitIMUThresh = "1.0" [Variance threshold on our acceleration to be classified as moving]
188
+ Param: OdomOpenVINS/InitMaxDisparity = "10.0" [Max disparity to consider the platform stationary (dependent on resolution)]
189
+ Param: OdomOpenVINS/InitMaxFeatures = "50" [How many features to track during initialization (saves on computation)]
190
+ Param: OdomOpenVINS/InitWindowTime = "2.0" [Amount of time we will initialize over (seconds)]
191
+ Param: OdomOpenVINS/Integration = "1" [0=discrete, 1=rk4, 2=analytical (if rk4 or analytical used then analytical covariance propagation is used)]
192
+ Param: OdomOpenVINS/LeftMaskPath = "" [Mask for left image]
193
+ Param: OdomOpenVINS/MaxClones = "11" [Max clone size of sliding window]
194
+ Param: OdomOpenVINS/MaxMSCKFInUpdate = "50" [Max number of MSCKF features we will use at a given image timestep.]
195
+ Param: OdomOpenVINS/MaxSLAM = "50" [Max number of estimated SLAM features]
196
+ Param: OdomOpenVINS/MaxSLAMInUpdate = "25" [Max number of SLAM features we allow to be included in a single EKF update.]
197
+ Param: OdomOpenVINS/MinPxDist = "15" [Eistance between features (features near each other provide less information)]
198
+ Param: OdomOpenVINS/NumPts = "200" [Number of points (per camera) we will extract and try to track]
199
+ Param: OdomOpenVINS/RightMaskPath = "" [Mask for right image]
200
+ Param: OdomOpenVINS/TryZUPT = "true" [If we should try to use zero velocity update]
201
+ Param: OdomOpenVINS/UpMSCKFChi2Multiplier = "1.0" [Chi2 multiplier for MSCKF features]
202
+ Param: OdomOpenVINS/UpMSCKFSigmaPx = "1.0" [Pixel noise for MSCKF features]
203
+ Param: OdomOpenVINS/UpSLAMChi2Multiplier = "1.0" [Chi2 multiplier for SLAM features]
204
+ Param: OdomOpenVINS/UpSLAMSigmaPx = "1.0" [Pixel noise for SLAM features]
205
+ Param: OdomOpenVINS/UseFEJ = "true" [If first-estimate Jacobians should be used (enable for good consistency)]
206
+ Param: OdomOpenVINS/UseKLT = "true" [If true we will use KLT, otherwise use a ORB descriptor + robust matching]
207
+ Param: OdomOpenVINS/UseStereo = "true" [If we have more than 1 camera, if we should try to track stereo constraints between pairs]
208
+ Param: OdomOpenVINS/ZUPTChi2Multiplier = "0.0" [Chi2 multiplier for zero velocity]
209
+ Param: OdomOpenVINS/ZUPTMaxDisparity = "0.5" [Max disparity we will consider to try to do a zupt (i.e. if above this, don't do zupt)]
210
+ Param: OdomOpenVINS/ZUPTMaxVelodicy = "0.1" [Max velocity we will consider to try to do a zupt (i.e. if above this, don't do zupt)]
211
+ Param: OdomOpenVINS/ZUPTNoiseMultiplier = "10.0" [Multiplier of our zupt measurement IMU noise matrix (default should be 1.0)]
212
+ Param: OdomOpenVINS/ZUPTOnlyAtBeginning = "false" [If we should only use the zupt at the very beginning static initialization phase]
213
+ Param: OdomVINSFusion/ConfigPath = "" [Path of VINS-Fusion config file.]
214
+ Param: OdomViso2/BucketHeight = "50" [Height of bucket.]
215
+ Param: OdomViso2/BucketMaxFeatures = "2" [Maximal number of features per bucket.]
216
+ Param: OdomViso2/BucketWidth = "50" [Width of bucket.]
217
+ Param: OdomViso2/InlierThreshold = "2.0" [Fundamental matrix inlier threshold.]
218
+ Param: OdomViso2/MatchBinsize = "50" [Matching bin width/height (affects efficiency only).]
219
+ Param: OdomViso2/MatchDispTolerance = "2" [Disparity tolerance for stereo matches (in pixels).]
220
+ Param: OdomViso2/MatchHalfResolution = "true" [Match at half resolution, refine at full resolution.]
221
+ Param: OdomViso2/MatchMultiStage = "true" [Multistage matching (denser and faster).]
222
+ Param: OdomViso2/MatchNmsN = "3" [Non-max-suppression: min. distance between maxima (in pixels).]
223
+ Param: OdomViso2/MatchNmsTau = "50" [Non-max-suppression: interest point peakiness threshold.]
224
+ Param: OdomViso2/MatchOutlierDispTolerance = "5" [Outlier removal: disparity tolerance (in pixels).]
225
+ Param: OdomViso2/MatchOutlierFlowTolerance = "5" [Outlier removal: flow tolerance (in pixels).]
226
+ Param: OdomViso2/MatchRadius = "200" [Matching radius (du/dv in pixels).]
227
+ Param: OdomViso2/MatchRefinement = "1" [Refinement (0=none,1=pixel,2=subpixel).]
228
+ Param: OdomViso2/RansacIters = "200" [Number of RANSAC iterations.]
229
+ Param: OdomViso2/Reweighting = "true" [Lower border weights (more robust to calibration errors).]
230
+ Param: Optimizer/Epsilon = "0.00001" [Stop optimizing when the error improvement is less than this value.]
231
+ Param: Optimizer/GravitySigma = "0.3" [Gravity sigma value (>=0, typically between 0.1 and 0.3). Optimization is done while preserving gravity orientation of the poses. This should be used only with visual/lidar inertial odometry approaches, for which we assume that all odometry poses are aligned with gravity. Set to 0 to disable gravity constraints. Currently supported only with g2o and GTSAM optimization strategies (see Optimizer/Strategy).]
232
+ Param: Optimizer/Iterations = "20" [Optimization iterations.]
233
+ Param: Optimizer/LandmarksIgnored = "false" [Ignore landmark constraints while optimizing. Currently only g2o and gtsam optimization supports this.]
234
+ Param: Optimizer/PriorsIgnored = "true" [Ignore prior constraints (global pose or GPS) while optimizing. Currently only g2o and gtsam optimization supports this.]
235
+ Param: Optimizer/Robust = "false" [Robust graph optimization using Vertigo (only work for g2o and GTSAM optimization strategies).]
236
+ Param: Optimizer/Strategy = "2" [Graph optimization strategy: 0=TORO, 1=g2o, 2=GTSAM and 3=Ceres.]
237
+ Param: Optimizer/VarianceIgnored = "false" [Ignore constraints' variance. If checked, identity information matrix is used for each constraint. Otherwise, an information matrix is generated from the variance saved in the links.]
238
+ Param: PyDetector/Cuda = "true" [Use cuda.]
239
+ Param: PyDetector/Path = "" [Path to python script file (see available ones in rtabmap/corelib/src/python/*). See the header to see where the script should be copied.]
240
+ Param: PyMatcher/Cuda = "true" [Used by SuperGlue.]
241
+ Param: PyMatcher/Iterations = "20" [Sinkhorn iterations. Used by SuperGlue.]
242
+ Param: PyMatcher/Model = "indoor" [For SuperGlue, set only "indoor" or "outdoor". For OANet, set path to one of the pth file (e.g., "OANet/model/gl3d/sift-4000/model_best.pth").]
243
+ Param: PyMatcher/Path = "" [Path to python script file (see available ones in rtabmap/corelib/src/python/*). See the header to see where the script should be copied.]
244
+ Param: PyMatcher/Threshold = "0.2" [Used by SuperGlue.]
245
+ Param: Reg/Force3DoF = "false" [Force 3 degrees-of-freedom transform (3Dof: x,y and yaw). Parameters z, roll and pitch will be set to 0.]
246
+ Param: Reg/RepeatOnce = "true" [Do a second registration with the output of the first registration as guess. Only done if no guess was provided for the first registration (like on loop closure). It can be useful if the registration approach used can use a guess to get better matches.]
247
+ Param: Reg/Strategy = "0" [0=Vis, 1=Icp, 2=VisIcp]
248
+ Param: Rtabmap/ImagesAlreadyRectified = "true" [Images are already rectified. By default RTAB-Map assumes that received images are rectified. If they are not, they can be rectified by RTAB-Map if this parameter is false.]
249
+ Param: Rtabmap/PublishRAMUsage = "false" [Publishing RAM usage in statistics (may add a small overhead to get info from the system).]
250
+ Param: SIFT/ContrastThreshold = "0.04" [The contrast threshold used to filter out weak features in semi-uniform (low-contrast) regions. The larger the threshold, the less features are produced by the detector. Not used by CudaSift (see SIFT/GaussianThreshold instead).]
251
+ Param: SIFT/EdgeThreshold = "10" [The threshold used to filter out edge-like features. Note that the its meaning is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are filtered out (more features are retained).]
252
+ Param: SIFT/GaussianThreshold = "2.0" [CudaSift: Threshold on difference of Gaussians for feature pruning. The higher the threshold, the less features are produced by the detector.]
253
+ Param: SIFT/Gpu = "false" [CudaSift: Use GPU version of SIFT. This option is enabled only if RTAB-Map is built with CudaSift dependency and GPUs are detected.]
254
+ Param: SIFT/NOctaveLayers = "3" [The number of layers in each octave. 3 is the value used in D. Lowe paper. The number of octaves is computed automatically from the image resolution. Not used by CudaSift, the number of octaves is still computed automatically.]
255
+ Param: SIFT/PreciseUpscale = "false" [Whether to enable precise upscaling in the scale pyramid (OpenCV >= 4.8).]
256
+ Param: SIFT/RootSIFT = "false" [Apply RootSIFT normalization of the descriptors.]
257
+ Param: SIFT/Sigma = "1.6" [The sigma of the Gaussian applied to the input image at the octave #0. If your image is captured with a weak camera with soft lenses, you might want to reduce the number.]
258
+ Param: SIFT/Upscale = "false" [CudaSift: Whether to enable upscaling.]
259
+ Param: SURF/Extended = "false" [Extended descriptor flag (true - use extended 128-element descriptors; false - use 64-element descriptors).]
260
+ Param: SURF/GpuKeypointsRatio = "0.01" [Used with SURF GPU.]
261
+ Param: SURF/GpuVersion = "false" [GPU-SURF: Use GPU version of SURF. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
262
+ Param: SURF/HessianThreshold = "500" [Threshold for hessian keypoint detector used in SURF.]
263
+ Param: SURF/OctaveLayers = "2" [Number of octave layers within each octave.]
264
+ Param: SURF/Octaves = "4" [Number of pyramid octaves the keypoint detector will use.]
265
+ Param: SURF/Upright = "false" [Up-right or rotated features flag (true - do not compute orientation of features; false - compute orientation).]
266
+ Param: SuperPoint/Cuda = "true" [Use Cuda device for Torch, otherwise CPU device is used by default.]
267
+ Param: SuperPoint/ModelPath = "" [[Required] Path to pre-trained weights Torch file of SuperPoint (*.pt).]
268
+ Param: SuperPoint/NMS = "true" [If true, non-maximum suppression is applied to detected keypoints.]
269
+ Param: SuperPoint/NMSRadius = "4" [[SuperPoint/NMS=true] Minimum distance (pixels) between keypoints.]
270
+ Param: SuperPoint/Threshold = "0.010" [Detector response threshold to accept keypoint.]
271
+ Param: SuperPointRpautrat/Cuda = "true" [Use Cuda device for Torch, otherwise CPU device is used by default.]
272
+ Param: SuperPointRpautrat/ModelPath = "" [[Required] SuperPoint python model file (superpoint_pytorch.py).]
273
+ Param: SuperPointRpautrat/NMS = "true" [If true, non-maximum suppression is applied to detected keypoints.]
274
+ Param: SuperPointRpautrat/NMSRadius = "4" [[SuperPointRpautrat/NMS=true] Minimum distance (pixels) between keypoints.]
275
+ Param: SuperPointRpautrat/Threshold = "0.005" [Detector response threshold to accept keypoint.]
276
+ Param: SuperPointRpautrat/WeightsPath = "" [[Required] SuperPoint weights file (*.pth).]
277
+ Param: Vis/BundleAdjustment = "1" [Optimization with bundle adjustment: 0=disabled, 1=g2o, 2=cvsba, 3=Ceres.]
278
+ Param: Vis/CorFlowEps = "0.01" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
279
+ Param: Vis/CorFlowGpu = "false" [[Vis/CorType=1] Enable GPU version of the optical flow approach (only available if OpenCV is built with CUDA).]
280
+ Param: Vis/CorFlowIterations = "30" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
281
+ Param: Vis/CorFlowMaxLevel = "3" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
282
+ Param: Vis/CorFlowWinSize = "16" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
283
+ Param: Vis/CorGuessMatchToProjection = "false" [[Vis/CorType=0] Match frame's corners to source's projected points (when guess transform is provided) instead of projected points to frame's corners.]
284
+ Param: Vis/CorGuessWinSize = "40" [[Vis/CorType=0] Matching window size (pixels) around projected points when a guess transform is provided to find correspondences. 0 means disabled.]
285
+ Param: Vis/CorNNDR = "0.8" [[Vis/CorType=0] NNDR: nearest neighbor distance ratio. Used for knn features matching approach.]
286
+ Param: Vis/CorNNType = "1" [[Vis/CorType=0] kNNFlannNaive=0, kNNFlannKdTree=1, kNNFlannLSH=2, kNNBruteForce=3, kNNBruteForceGPU=4, BruteForceCrossCheck=5, SuperGlue=6, GMS=7. Used for features matching approach.]
287
+ Param: Vis/CorType = "0" [Correspondences computation approach: 0=Features Matching, 1=Optical Flow]
288
+ Param: Vis/DepthAsMask = "true" [Use depth image as mask when extracting features.]
289
+ Param: Vis/DepthMaskFloorThr = "0.0" [Filter floor from depth mask below specified threshold (m) before extracting features. 0 means disabled, negative means remove all objects above the floor threshold instead. Ignored if Vis/DepthAsMask is false.]
290
+ Param: Vis/EpipolarGeometryVar = "0.1" [[Vis/EstimationType = 2] Epipolar geometry maximum variance to accept the transformation.]
291
+ Param: Vis/EstimationType = "1" [Motion estimation approach: 0:3D->3D, 1:3D->2D (PnP), 2:2D->2D (Epipolar Geometry)]
292
+ Param: Vis/FeatureType = "8" [0=SURF 1=SIFT 2=ORB 3=FAST/FREAK 4=FAST/BRIEF 5=GFTT/FREAK 6=GFTT/BRIEF 7=BRISK 8=GFTT/ORB 9=KAZE 10=ORB-OCTREE 11=SuperPoint 12=SURF/FREAK 13=GFTT/DAISY 14=SURF/DAISY 15=PyDetector 16=SuperPoint-Rpautrat]
293
+ Param: Vis/GridCols = "1" [Number of columns of the grid used to extract uniformly "Vis/MaxFeatures / grid cells" features from each cell.]
294
+ Param: Vis/GridRows = "1" [Number of rows of the grid used to extract uniformly "Vis/MaxFeatures / grid cells" features from each cell.]
295
+ Param: Vis/InlierDistance = "0.1" [[Vis/EstimationType = 0] Maximum distance for feature correspondences. Used by 3D->3D estimation approach.]
296
+ Param: Vis/Iterations = "300" [Maximum iterations to compute the transform.]
297
+ Param: Vis/MaxDepth = "0" [Max depth of the features (0 means no limit).]
298
+ Param: Vis/MaxFeatures = "1000" [0 no limits.]
299
+ Param: Vis/MeanInliersDistance = "0.0" [Maximum distance (m) of the mean distance of inliers from the camera to accept the transformation. 0 means disabled.]
300
+ Param: Vis/MinDepth = "0" [Min depth of the features (0 means no limit).]
301
+ Param: Vis/MinInliers = "20" [Minimum feature correspondences to compute/accept the transformation.]
302
+ Param: Vis/MinInliersDistribution = "0.0" [Minimum distribution value of the inliers in the image to accept the transformation. The distribution is the second eigen value of the PCA (Principal Component Analysis) on the keypoints of the normalized image [-0.5, 0.5]. The value would be between 0 and 0.5. 0 means disabled.]
303
+ Param: Vis/PnPFlags = "0" [[Vis/EstimationType = 1] PnP flags: 0=Iterative, 1=EPNP, 2=P3P]
304
+ Param: Vis/PnPMaxVariance = "0.0" [[Vis/EstimationType = 1] Max linear variance between 3D point correspondences after PnP. 0 means disabled.]
305
+ Param: Vis/PnPRefineIterations = "0" [[Vis/EstimationType = 1] Refine iterations. Set to 0 if "Vis/BundleAdjustment" is also used.]
306
+ Param: Vis/PnPReprojError = "2" [[Vis/EstimationType = 1] PnP reprojection error.]
307
+ Param: Vis/PnPSamplingPolicy = "1" [[Vis/EstimationType = 1] Multi-camera random sampling policy: 0=AUTO, 1=ANY, 2=HOMOGENEOUS. With HOMOGENEOUS policy, RANSAC will be done uniformly against all cameras, so at least 2 matches per camera are required. With ANY policy, RANSAC is not constraint to sample on all cameras at the same time. AUTO policy will use HOMOGENEOUS if there are at least 2 matches per camera, otherwise it will fallback to ANY policy.]
308
+ Param: Vis/PnPSplitLinearCovComponents = "false" [[Vis/EstimationType = 1] Compute variance for each linear component instead of using the combined XYZ variance for all linear components.]
309
+ Param: Vis/PnPVarianceMedianRatio = "4" [[Vis/EstimationType = 1] Ratio used to compute variance of the estimated transformation if 3D correspondences are provided (should be > 1). The higher it is, the smaller the covariance will be. With accurate depth estimation, this could be set to 2. For depth estimated by stereo, 4 or more maybe used to ignore large errors of very far points.]
310
+ Param: Vis/RefineIterations = "5" [[Vis/EstimationType = 0] Number of iterations used to refine the transformation found by RANSAC. 0 means that the transformation is not refined.]
311
+ Param: Vis/RoiRatios = "0.0 0.0 0.0 0.0" [Region of interest ratios [left, right, top, bottom].]
312
+ Param: Vis/SSC = "false" [If true, SSC (Suppression via Square Covering) is applied to limit keypoints.]
313
+ Param: Vis/SubPixEps = "0.02" [See cv::cornerSubPix().]
314
+ Param: Vis/SubPixIterations = "0" [See cv::cornerSubPix(). 0 disables sub pixel refining.]
315
+ Param: Vis/SubPixWinSize = "3" [See cv::cornerSubPix().]
316
+ Param: g2o/Baseline = "0.075" [When doing bundle adjustment with RGB-D data, we can set a fake baseline (m) to do stereo bundle adjustment (if 0, mono bundle adjustment is done). For stereo data, the baseline in the calibration is used directly.]
317
+ Param: g2o/Optimizer = "0" [0=Levenberg 1=GaussNewton]
318
+ Param: g2o/PixelVariance = "1.0" [Pixel variance used for bundle adjustment.]
319
+ Param: g2o/RobustKernelDelta = "8" [Robust kernel delta used for bundle adjustment (0 means don't use robust kernel). Observations with chi2 over this threshold will be ignored in the second optimization pass.]
320
+ Param: g2o/Solver = "0" [0=csparse 1=pcg 2=cholmod 3=Eigen]
321
+ [ WARN] (2026-04-02 12:44:52.093) RGBDOdometryNode.cpp:58::main() Node will now exit after showing default odometry parameters because argument "--params" is detected!
experiments/rtabmap/params/route.yaml ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ waypoints:
2
+ - pose:
3
+ orientation:
4
+ theta: 0.0
5
+ position:
6
+ x: 0.0
7
+ y: 0.0
8
+ - pose:
9
+ orientation:
10
+ theta: 0.0
11
+ position:
12
+ x: 1.0
13
+ y: 0.0
14
+ - pose:
15
+ orientation:
16
+ theta: 0.0
17
+ position:
18
+ x: 2.0
19
+ y: 0.0
20
+ - pose:
21
+ orientation:
22
+ theta: 0.0
23
+ position:
24
+ x: 3.0
25
+ y: 0.0
26
+ - pose:
27
+ orientation:
28
+ theta: 0.0
29
+ position:
30
+ x: 4.0
31
+ y: 0.0
32
+ - pose:
33
+ orientation:
34
+ theta: 0.0
35
+ position:
36
+ x: 5.0
37
+ y: 0.0
38
+ - pose:
39
+ orientation:
40
+ theta: 0.0
41
+ position:
42
+ x: 6.0
43
+ y: 0.0
44
+ - pose:
45
+ orientation:
46
+ theta: 0.0
47
+ position:
48
+ x: 7.0
49
+ y: 0.0
50
+ - pose:
51
+ orientation:
52
+ theta: 0.0
53
+ position:
54
+ x: 8.0
55
+ y: 0.0
56
+ - pose:
57
+ orientation:
58
+ theta: 0.0
59
+ position:
60
+ x: 9.0
61
+ y: 0.0
62
+ - pose:
63
+ orientation:
64
+ theta: 0.031415926535897046
65
+ position:
66
+ x: 10.0
67
+ y: 0.0
68
+ - pose:
69
+ orientation:
70
+ theta: 0.09424777960769377
71
+ position:
72
+ x: 10.156976298823285
73
+ y: 0.0049331789293209916
74
+ - pose:
75
+ orientation:
76
+ theta: 0.15707963267949113
77
+ position:
78
+ x: 10.313333083910761
79
+ y: 0.019713246713805255
80
+ - pose:
81
+ orientation:
82
+ theta: 0.21991148575128608
83
+ position:
84
+ x: 10.468453286464312
85
+ y: 0.044281873178278364
86
+ - pose:
87
+ orientation:
88
+ theta: 0.2827433388230835
89
+ position:
90
+ x: 10.621724717912137
91
+ y: 0.07854209717842231
92
+ - pose:
93
+ orientation:
94
+ theta: 0.34557519189487673
95
+ position:
96
+ x: 10.772542485937368
97
+ y: 0.12235870926211634
98
+ - pose:
99
+ orientation:
100
+ theta: 0.4084070449666701
101
+ position:
102
+ x: 10.920311381711695
103
+ y: 0.17555878527937185
104
+ - pose:
105
+ orientation:
106
+ theta: 0.4712388980384709
107
+ position:
108
+ x: 11.064448228912681
109
+ y: 0.23793236883495084
110
+ - pose:
111
+ orientation:
112
+ theta: 0.5340707511102667
113
+ position:
114
+ x: 11.204384185254288
115
+ y: 0.3092332998903409
116
+ - pose:
117
+ orientation:
118
+ theta: 0.596902604182055
119
+ position:
120
+ x: 11.33956698744749
121
+ y: 0.3891801862449622
122
+ - pose:
123
+ orientation:
124
+ theta: 0.6597344572538617
125
+ position:
126
+ x: 11.469463130731183
127
+ y: 0.47745751406263137
128
+ - pose:
129
+ orientation:
130
+ theta: 0.7225663103256492
131
+ position:
132
+ x: 11.593559974371724
133
+ y: 0.573716893060527
134
+ - pose:
135
+ orientation:
136
+ theta: 0.7853981633974443
137
+ position:
138
+ x: 11.711367764821722
139
+ y: 0.677578431446471
140
+ - pose:
141
+ orientation:
142
+ theta: 0.848230016469254
143
+ position:
144
+ x: 11.82242156855353
145
+ y: 0.7886322351782784
146
+ - pose:
147
+ orientation:
148
+ theta: 0.9110618695410353
149
+ position:
150
+ x: 11.926283106939472
151
+ y: 0.9064400256282759
152
+ - pose:
153
+ orientation:
154
+ theta: 0.9738937226128352
155
+ position:
156
+ x: 12.022542485937368
157
+ y: 1.0305368692688168
158
+ - pose:
159
+ orientation:
160
+ theta: 1.036725575684632
161
+ position:
162
+ x: 12.110819813755038
163
+ y: 1.1604330125525086
164
+ - pose:
165
+ orientation:
166
+ theta: 1.0995574287564258
167
+ position:
168
+ x: 12.19076670010966
169
+ y: 1.2956158147457122
170
+ - pose:
171
+ orientation:
172
+ theta: 1.162389281828222
173
+ position:
174
+ x: 12.26206763116505
175
+ y: 1.4355517710873185
176
+ - pose:
177
+ orientation:
178
+ theta: 1.2252211349000215
179
+ position:
180
+ x: 12.324441214720629
181
+ y: 1.579688618288305
182
+ - pose:
183
+ orientation:
184
+ theta: 1.2880529879718174
185
+ position:
186
+ x: 12.377641290737884
187
+ y: 1.7274575140626314
188
+ - pose:
189
+ orientation:
190
+ theta: 1.3508848410436078
191
+ position:
192
+ x: 12.421457902821578
193
+ y: 1.8782752820878632
194
+ - pose:
195
+ orientation:
196
+ theta: 1.4137166941154133
197
+ position:
198
+ x: 12.455718126821722
199
+ y: 2.0315467135356884
200
+ - pose:
201
+ orientation:
202
+ theta: 1.4765485471871949
203
+ position:
204
+ x: 12.480286753286194
205
+ y: 2.186666916089239
206
+ - pose:
207
+ orientation:
208
+ theta: 1.5393804002590021
209
+ position:
210
+ x: 12.49506682107068
211
+ y: 2.3430237011767163
212
+ - pose:
213
+ orientation:
214
+ theta: 1.602212253330791
215
+ position:
216
+ x: 12.5
217
+ y: 2.5
218
+ - pose:
219
+ orientation:
220
+ theta: 1.6650441064025985
221
+ position:
222
+ x: 12.49506682107068
223
+ y: 2.6569762988232837
224
+ - pose:
225
+ orientation:
226
+ theta: 1.7278759594743793
227
+ position:
228
+ x: 12.480286753286194
229
+ y: 2.8133330839107606
230
+ - pose:
231
+ orientation:
232
+ theta: 1.7907078125461848
233
+ position:
234
+ x: 12.455718126821722
235
+ y: 2.9684532864643116
236
+ - pose:
237
+ orientation:
238
+ theta: 1.8535396656179774
239
+ position:
240
+ x: 12.421457902821578
241
+ y: 3.1217247179121372
242
+ - pose:
243
+ orientation:
244
+ theta: 1.9163715186897716
245
+ position:
246
+ x: 12.377641290737884
247
+ y: 3.272542485937368
248
+ - pose:
249
+ orientation:
250
+ theta: 1.9792033717615685
251
+ position:
252
+ x: 12.324441214720629
253
+ y: 3.4203113817116946
254
+ - pose:
255
+ orientation:
256
+ theta: 2.0420352248333673
257
+ position:
258
+ x: 12.26206763116505
259
+ y: 3.564448228912682
260
+ - pose:
261
+ orientation:
262
+ theta: 2.1048670779051704
263
+ position:
264
+ x: 12.19076670010966
265
+ y: 3.7043841852542885
266
+ - pose:
267
+ orientation:
268
+ theta: 2.1676989309769525
269
+ position:
270
+ x: 12.110819813755036
271
+ y: 3.8395669874474923
272
+ - pose:
273
+ orientation:
274
+ theta: 2.230530784048755
275
+ position:
276
+ x: 12.022542485937368
277
+ y: 3.969463130731183
278
+ - pose:
279
+ orientation:
280
+ theta: 2.2933626371205498
281
+ position:
282
+ x: 11.926283106939472
283
+ y: 4.093559974371725
284
+ - pose:
285
+ orientation:
286
+ theta: 2.356194490192345
287
+ position:
288
+ x: 11.822421568553528
289
+ y: 4.211367764821722
290
+ - pose:
291
+ orientation:
292
+ theta: 2.4190263432641324
293
+ position:
294
+ x: 11.711367764821722
295
+ y: 4.322421568553528
296
+ - pose:
297
+ orientation:
298
+ theta: 2.4818581963359407
299
+ position:
300
+ x: 11.593559974371725
301
+ y: 4.426283106939473
302
+ - pose:
303
+ orientation:
304
+ theta: 2.544690049407734
305
+ position:
306
+ x: 11.469463130731183
307
+ y: 4.522542485937368
308
+ - pose:
309
+ orientation:
310
+ theta: 2.6075219024795273
311
+ position:
312
+ x: 11.339566987447492
313
+ y: 4.610819813755037
314
+ - pose:
315
+ orientation:
316
+ theta: 2.6703537555513224
317
+ position:
318
+ x: 11.204384185254288
319
+ y: 4.690766700109659
320
+ - pose:
321
+ orientation:
322
+ theta: 2.733185608623123
323
+ position:
324
+ x: 11.064448228912681
325
+ y: 4.762067631165049
326
+ - pose:
327
+ orientation:
328
+ theta: 2.796017461694914
329
+ position:
330
+ x: 10.920311381711695
331
+ y: 4.824441214720628
332
+ - pose:
333
+ orientation:
334
+ theta: 2.8588493147667124
335
+ position:
336
+ x: 10.772542485937368
337
+ y: 4.877641290737884
338
+ - pose:
339
+ orientation:
340
+ theta: 2.9216811678385044
341
+ position:
342
+ x: 10.621724717912137
343
+ y: 4.921457902821578
344
+ - pose:
345
+ orientation:
346
+ theta: 2.9845130209103106
347
+ position:
348
+ x: 10.468453286464312
349
+ y: 4.955718126821722
350
+ - pose:
351
+ orientation:
352
+ theta: 3.047344873982091
353
+ position:
354
+ x: 10.313333083910761
355
+ y: 4.980286753286194
356
+ - pose:
357
+ orientation:
358
+ theta: 3.110176727053899
359
+ position:
360
+ x: 10.156976298823285
361
+ y: 4.9950668210706795
362
+ - pose:
363
+ orientation:
364
+ theta: 3.141592653589793
365
+ position:
366
+ x: 10.0
367
+ y: 5.0
368
+ - pose:
369
+ orientation:
370
+ theta: 3.141592653589793
371
+ position:
372
+ x: 9.0
373
+ y: 5.0
374
+ - pose:
375
+ orientation:
376
+ theta: 3.141592653589793
377
+ position:
378
+ x: 8.0
379
+ y: 5.0
380
+ - pose:
381
+ orientation:
382
+ theta: 3.141592653589793
383
+ position:
384
+ x: 7.0
385
+ y: 5.0
386
+ - pose:
387
+ orientation:
388
+ theta: 3.141592653589793
389
+ position:
390
+ x: 6.0
391
+ y: 5.0
392
+ - pose:
393
+ orientation:
394
+ theta: 3.141592653589793
395
+ position:
396
+ x: 5.0
397
+ y: 5.0
398
+ - pose:
399
+ orientation:
400
+ theta: 3.141592653589793
401
+ position:
402
+ x: 4.0
403
+ y: 5.0
404
+ - pose:
405
+ orientation:
406
+ theta: 3.141592653589793
407
+ position:
408
+ x: 3.0
409
+ y: 5.0
410
+ - pose:
411
+ orientation:
412
+ theta: 3.141592653589793
413
+ position:
414
+ x: 2.0
415
+ y: 5.0
416
+ - pose:
417
+ orientation:
418
+ theta: 3.141592653589793
419
+ position:
420
+ x: 1.0
421
+ y: 5.0
experiments/rtabmap/params/route2.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ waypoints:
2
+ - pose:
3
+ position:
4
+ x: 3
5
+ y: 0
6
+ orientation:
7
+ z: 0
8
+ w: 1
9
+ - pose:
10
+ position:
11
+ x: 6
12
+ y: 0
13
+ orientation:
14
+ z: 0
15
+ w: 1
16
+ - pose:
17
+ position:
18
+ x: 9
19
+ y: 0
20
+ orientation:
21
+ z: 0
22
+ w: 1
23
+ - pose:
24
+ position:
25
+ x: 11
26
+ y: -1
27
+ orientation:
28
+ z: -0.7071068
29
+ w: 0.7071068
30
+ - pose:
31
+ position:
32
+ x: 11
33
+ y: -2
34
+ orientation:
35
+ z: -0.9489846
36
+ w: 0.3153224
37
+ - pose:
38
+ position:
39
+ x: 9
40
+ y: -3
41
+ orientation:
42
+ z: 1
43
+ w: 0
44
+ - pose:
45
+ position:
46
+ x: 6
47
+ y: -3
48
+ orientation:
49
+ z: 1
50
+ w: 0
51
+ - pose:
52
+ position:
53
+ x: 3
54
+ y: -3
55
+ orientation:
56
+ z: 1
57
+ w: 0
58
+ - pose:
59
+ position:
60
+ x: 0
61
+ y: -3
62
+ orientation:
63
+ z: 1
64
+ w: 0
65
+
66
+
67
+
68
+
experiments/rtabmap/params/slam.txt ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ jaco@A70i:~/ws$ ros2 run rtabmap_slam rtabmap --params
2
+ Param: BRIEF/Bytes = "32" [Bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes.]
3
+ Param: BRISK/Octaves = "3" [Detection octaves. Use 0 to do single scale.]
4
+ Param: BRISK/PatternScale = "1" [Apply this scale to the pattern used for sampling the neighbourhood of a keypoint.]
5
+ Param: BRISK/Thresh = "30" [FAST/AGAST detection threshold score.]
6
+ Param: Bayes/FullPredictionUpdate = "false" [Regenerate all the prediction matrix on each iteration (otherwise only removed/added ids are updated).]
7
+ Param: Bayes/PredictionLC = "0.1 0.36 0.30 0.16 0.062 0.0151 0.00255 0.000324 2.5e-05 1.3e-06 4.8e-08 1.2e-09 1.9e-11 2.2e-13 1.7e-15 8.5e-18 2.9e-20 6.9e-23" [Prediction of loop closures (Gaussian-like, here with sigma=1.6) - Format: {VirtualPlaceProb, LoopClosureProb, NeighborLvl1, NeighborLvl2, ...}.]
8
+ Param: Bayes/VirtualPlacePriorThr = "0.9" [Virtual place prior]
9
+ Param: Db/TargetVersion = "" [Target database version for backward compatibility purpose. Only Major and minor versions are used and should be set (e.g., 0.19 vs 0.20 or 1.0 vs 2.0). Patch version is ignored (e.g., 0.20.1 and 0.20.3 will generate a 0.20 database).]
10
+ Param: DbSqlite3/CacheSize = "10000" [Sqlite cache size (default is 2000).]
11
+ Param: DbSqlite3/InMemory = "false" [Using database in the memory instead of a file on the hard disk.]
12
+ Param: DbSqlite3/JournalMode = "3" [0=DELETE, 1=TRUNCATE, 2=PERSIST, 3=MEMORY, 4=OFF (see sqlite3 doc : "PRAGMA journal_mode")]
13
+ Param: DbSqlite3/Synchronous = "0" [0=OFF, 1=NORMAL, 2=FULL (see sqlite3 doc : "PRAGMA synchronous")]
14
+ Param: DbSqlite3/TempStore = "2" [0=DEFAULT, 1=FILE, 2=MEMORY (see sqlite3 doc : "PRAGMA temp_store")]
15
+ Param: FAST/CV = "0" [Enable FastCV implementation if non-zero (and RTAB-Map is built with FastCV support). Values should be 9 and 10.]
16
+ Param: FAST/Gpu = "false" [GPU-FAST: Use GPU version of FAST. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
17
+ Param: FAST/GpuKeypointsRatio = "0.05" [Used with FAST GPU.]
18
+ Param: FAST/GridCols = "0" [Grid cols (0 to disable). Adapts the detector to partition the source image into a grid and detect points in each cell.]
19
+ Param: FAST/GridRows = "0" [Grid rows (0 to disable). Adapts the detector to partition the source image into a grid and detect points in each cell.]
20
+ Param: FAST/MaxThreshold = "200" [Maximum threshold. Used only when FAST/GridRows and FAST/GridCols are set.]
21
+ Param: FAST/MinThreshold = "7" [Minimum threshold. Used only when FAST/GridRows and FAST/GridCols are set.]
22
+ Param: FAST/NonmaxSuppression = "true" [If true, non-maximum suppression is applied to detected corners (keypoints).]
23
+ Param: FAST/Threshold = "20" [Threshold on difference between intensity of the central pixel and pixels of a circle around this pixel.]
24
+ Param: FREAK/NOctaves = "4" [Number of octaves covered by the detected keypoints.]
25
+ Param: FREAK/OrientationNormalized = "true" [Enable orientation normalization.]
26
+ Param: FREAK/PatternScale = "22" [Scaling of the description pattern.]
27
+ Param: FREAK/ScaleNormalized = "true" [Enable scale normalization.]
28
+ Param: GFTT/BlockSize = "3" []
29
+ Param: GFTT/Gpu = "false" [GPU-GFTT: Use GPU version of GFTT. This option is enabled only if OpenCV>=3 is built with CUDA and GPUs are detected.]
30
+ Param: GFTT/K = "0.04" []
31
+ Param: GFTT/MinDistance = "7" []
32
+ Param: GFTT/QualityLevel = "0.001" []
33
+ Param: GFTT/UseHarrisDetector = "false" []
34
+ Param: GMS/ThresholdFactor = "6.0" [The higher, the less matches.]
35
+ Param: GMS/WithRotation = "false" [Take rotation transformation into account.]
36
+ Param: GMS/WithScale = "false" [Take scale transformation into account.]
37
+ Param: GTSAM/IncRelinearizeSkip = "1" [Only relinearize any variables every X calls to ISAM2::update(). See GTSAM::ISAM2 doc for more info.]
38
+ Param: GTSAM/IncRelinearizeThreshold = "0.01" [Only relinearize variables whose linear delta magnitude is greater than this threshold. See GTSAM::ISAM2 doc for more info.]
39
+ Param: GTSAM/Incremental = "false" [Do graph optimization incrementally (iSAM2) to increase optimization speed on loop closures. Note that only GaussNewton and Dogleg optimization algorithms are supported (GTSAM/Optimizer) in this mode.]
40
+ Param: GTSAM/Optimizer = "1" [0=Levenberg 1=GaussNewton 2=Dogleg]
41
+ Param: Grid/3D = "true" [A 3D occupancy grid is required if you want an OctoMap (3D ray tracing). Set to false if you want only a 2D map, the cloud will be projected on xy plane. A 2D map can be still generated if checked, but it requires more memory and time to generate it. Ignored if laser scan is 2D and "Grid/Sensor" is 0.]
42
+ Param: Grid/CellSize = "0.05" [Resolution of the occupancy grid.]
43
+ Param: Grid/ClusterRadius = "0.1" [[Grid/NormalsSegmentation=true] Cluster maximum radius.]
44
+ Param: Grid/DepthDecimation = "4" [[Grid/DepthDecimation=true] Decimation of the depth image before creating cloud.]
45
+ Param: Grid/DepthRoiRatios = "0.0 0.0 0.0 0.0" [[Grid/Sensor>=1] Region of interest ratios [left, right, top, bottom].]
46
+ Param: Grid/FlatObstacleDetected = "true" [[Grid/NormalsSegmentation=true] Flat obstacles detected.]
47
+ Param: Grid/FootprintHeight = "0.0" [Footprint height used to filter points over the footprint of the robot. Footprint length and width should be set.]
48
+ Param: Grid/FootprintLength = "0.0" [Footprint length used to filter points over the footprint of the robot.]
49
+ Param: Grid/FootprintWidth = "0.0" [Footprint width used to filter points over the footprint of the robot. Footprint length should be set.]
50
+ Param: Grid/GroundIsObstacle = "false" [[Grid/3D=true] Ground segmentation (Grid/NormalsSegmentation) is ignored, all points are obstacles. Use this only if you want an OctoMap with ground identified as an obstacle (e.g., with an UAV).]
51
+ Param: Grid/MapFrameProjection = "false" [Projection in map frame. On a 3D terrain and a fixed local camera transform (the cloud is created relative to ground), you may want to disable this to do the projection in robot frame instead.]
52
+ Param: Grid/MaxGroundAngle = "45" [[Grid/NormalsSegmentation=true] Maximum angle (degrees) between point's normal to ground's normal to label it as ground. Points with higher angle difference are considered as obstacles.]
53
+ Param: Grid/MaxGroundHeight = "0.0" [Maximum ground height (0=disabled). Should be set if "Grid/NormalsSegmentation" is false.]
54
+ Param: Grid/MaxObstacleHeight = "0.0" [Maximum obstacles height (0=disabled).]
55
+ Param: Grid/MinClusterSize = "10" [[Grid/NormalsSegmentation=true] Minimum cluster size to project the points.]
56
+ Param: Grid/MinGroundHeight = "0.0" [Minimum ground height (0=disabled).]
57
+ Param: Grid/NoiseFilteringMinNeighbors = "5" [Noise filtering minimum neighbors.]
58
+ Param: Grid/NoiseFilteringRadius = "0.0" [Noise filtering radius (0=disabled). Done after segmentation.]
59
+ Param: Grid/NormalK = "20" [[Grid/NormalsSegmentation=true] K neighbors to compute normals.]
60
+ Param: Grid/NormalsSegmentation = "true" [Segment ground from obstacles using point normals, otherwise a fast passthrough is used.]
61
+ Param: Grid/PreVoxelFiltering = "true" [Input cloud is downsampled by voxel filter (voxel size is "Grid/CellSize") before doing segmentation of obstacles and ground.]
62
+ Param: Grid/RangeMax = "5.0" [Maximum range from sensor. 0=inf.]
63
+ Param: Grid/RangeMin = "0.0" [Minimum range from sensor.]
64
+ Param: Grid/RayTracing = "false" [Ray tracing is done for each occupied cell, filling unknown space between the sensor and occupied cells. If Grid/3D=true, RTAB-Map should be built with OctoMap support, otherwise 3D ray tracing is ignored.]
65
+ Param: Grid/Scan2dUnknownSpaceFilled = "false" [Unknown space filled. Only used with 2D laser scans. Use Grid/RangeMax to set maximum range if laser scan max range is to set.]
66
+ Param: Grid/ScanDecimation = "1" [[Grid/Sensor=0 or 2] Decimation of the laser scan before creating cloud.]
67
+ Param: Grid/Sensor = "1" [Create occupancy grid from selected sensor: 0=laser scan, 1=depth image(s) or 2=both laser scan and depth image(s).]
68
+ Param: GridGlobal/AltitudeDelta = "0" [Assemble only nodes that have the same altitude of +-delta meters of the current pose (0=disabled). This is used to generate 2D occupancy grid based on the current altitude (e.g., multi-floor building).]
69
+ Param: GridGlobal/Eroded = "false" [Erode obstacle cells.]
70
+ Param: GridGlobal/FloodFillDepth = "0" [Flood fill filter (0=disabled), used to remove empty cells outside the map. The flood fill is done at the specified depth (between 1 and 16) of the OctoMap.]
71
+ Param: GridGlobal/FootprintRadius = "0.0" [Footprint radius (m) used to clear all obstacles under the graph.]
72
+ Param: GridGlobal/MaxNodes = "0" [Maximum nodes assembled in the map starting from the last node (0=unlimited).]
73
+ Param: GridGlobal/MinSize = "0.0" [Minimum map size (m).]
74
+ Param: GridGlobal/OccupancyThr = "0.5" [Occupancy threshold (value between 0 and 1).]
75
+ Param: GridGlobal/ProbClampingMax = "0.971" [Probability clamping maximum (value between 0 and 1).]
76
+ Param: GridGlobal/ProbClampingMin = "0.1192" [Probability clamping minimum (value between 0 and 1).]
77
+ Param: GridGlobal/ProbHit = "0.7" [Probability of a hit (value between 0.5 and 1).]
78
+ Param: GridGlobal/ProbMiss = "0.4" [Probability of a miss (value between 0 and 0.5).]
79
+ Param: GridGlobal/UpdateError = "0.01" [Graph changed detection error (m). Update map only if poses in new optimized graph have moved more than this value.]
80
+ Param: Icp/CCFilterOutFarthestPoints = "false" [If true, the algorithm will automatically ignore farthest points from the reference, for better convergence.]
81
+ Param: Icp/CCMaxFinalRMS = "0.2" [Maximum final RMS error.]
82
+ Param: Icp/CCSamplingLimit = "50000" [Maximum number of points per cloud (they are randomly resampled below this limit otherwise).]
83
+ Param: Icp/CorrespondenceRatio = "0.1" [Ratio of matching correspondences to accept the transform.]
84
+ Param: Icp/DebugExportFormat = "" [Export scans used for ICP in the specified format (a warning on terminal will be shown with the file paths used). Supported formats are "pcd", "ply" or "vtk". If logger level is debug, from and to scans will stamped, so previous files won't be overwritten.]
85
+ Param: Icp/DownsamplingStep = "1" [Downsampling step size (1=no sampling). This is done before uniform sampling.]
86
+ Param: Icp/Epsilon = "0" [Set the transformation epsilon (maximum allowable difference between two consecutive transformations) in order for an optimization to be considered as having converged to the final solution.]
87
+ Param: Icp/FiltersEnabled = "3" [Flag to enable filters: 1="from" cloud only, 2="to" cloud only, 3=both.]
88
+ Param: Icp/Force4DoF = "false" [Limit ICP to x, y, z and yaw DoF. Available if Icp/Strategy > 0.]
89
+ Param: Icp/Iterations = "30" [Max iterations.]
90
+ Param: Icp/MaxCorrespondenceDistance = "0.1" [Max distance for point correspondences.]
91
+ Param: Icp/MaxRotation = "0.78" [Maximum ICP rotation correction accepted (rad).]
92
+ Param: Icp/MaxTranslation = "0.2" [Maximum ICP translation correction accepted (m).]
93
+ Param: Icp/OutlierRatio = "0.85" [Outlier ratio used with Icp/Strategy>0. For libpointmatcher, this parameter set TrimmedDistOutlierFilter/ratio for convenience when configuration file is not set. For CCCoreLib, this parameter set the "finalOverlapRatio". The value should be between 0 and 1.]
94
+ Param: Icp/PMConfig = "" [Configuration file (*.yaml) used by libpointmatcher. Note that data filters set for libpointmatcher are done after filtering done by rtabmap (i.e., Icp/VoxelSize, Icp/DownsamplingStep), so make sure to disable those in rtabmap if you want to use only those from libpointmatcher. Parameters Icp/Iterations, Icp/Epsilon and Icp/MaxCorrespondenceDistance are also ignored if configuration file is set.]
95
+ Param: Icp/PMMatcherEpsilon = "0.0" [KDTreeMatcher/epsilon: approximation to use for the nearest-neighbor search. For convenience when configuration file is not set.]
96
+ Param: Icp/PMMatcherIntensity = "false" [KDTreeMatcher: among nearest neighbors, keep only the one with the most similar intensity. This only work with Icp/PMMatcherKnn>1.]
97
+ Param: Icp/PMMatcherKnn = "1" [KDTreeMatcher/knn: number of nearest neighbors to consider it the reference. For convenience when configuration file is not set.]
98
+ Param: Icp/PointToPlane = "true" [Use point to plane ICP.]
99
+ Param: Icp/PointToPlaneGroundNormalsUp = "0.0" [Invert normals on ground if they are pointing down (useful for ring-like 3D LiDARs). 0 means disabled, 1 means only normals perfectly aligned with -z axis. This is only done with 3D scans.]
100
+ Param: Icp/PointToPlaneK = "5" [Number of neighbors to compute normals for point to plane if the cloud doesn't have already normals.]
101
+ Param: Icp/PointToPlaneLowComplexityStrategy = "1" [If structural complexity is below Icp/PointToPlaneMinComplexity: set to 0 to so that the transform is automatically rejected, set to 1 to limit ICP correction in axes with most constraints (e.g., for a corridor-like environment, the resulting transform will be limited in y and yaw, x will taken from the guess), set to 2 to accept "as is" the transform computed by PointToPoint.]
102
+ Param: Icp/PointToPlaneMinComplexity = "0.02" [Minimum structural complexity (0.0=low, 1.0=high) of the scan to do PointToPlane registration, otherwise PointToPoint registration is done instead and strategy from Icp/PointToPlaneLowComplexityStrategy is used. This check is done only when Icp/PointToPlane=true.]
103
+ Param: Icp/PointToPlaneRadius = "0.0" [Search radius to compute normals for point to plane if the cloud doesn't have already normals.]
104
+ Param: Icp/RangeMax = "0" [Maximum range filtering (0=disabled).]
105
+ Param: Icp/RangeMin = "0" [Minimum range filtering (0=disabled).]
106
+ Param: Icp/ReciprocalCorrespondences = "true" [To be a valid correspondence, the corresponding point in target cloud to point in source cloud should be both their closest closest correspondence.]
107
+ Param: Icp/Strategy = "1" [ICP implementation: 0=Point Cloud Library, 1=libpointmatcher, 2=CCCoreLib (CloudCompare).]
108
+ Param: Icp/VoxelSize = "0.05" [Uniform sampling voxel size (0=disabled).]
109
+ Param: ImuFilter/ComplementaryBiasAlpha = "0.01" [Bias estimation gain parameter, belongs in [0, 1].]
110
+ Param: ImuFilter/ComplementaryDoAdpativeGain = "true" [Parameter whether to do adaptive gain or not.]
111
+ Param: ImuFilter/ComplementaryDoBiasEstimation = "true" [Parameter whether to do bias estimation or not.]
112
+ Param: ImuFilter/ComplementaryGainAcc = "0.01" [Gain parameter for the complementary filter, belongs in [0, 1].]
113
+ Param: ImuFilter/MadgwickGain = "0.1" [Gain of the filter. Higher values lead to faster convergence but more noise. Lower values lead to slower convergence but smoother signal, belongs in [0, 1].]
114
+ Param: ImuFilter/MadgwickZeta = "0.0" [Gyro drift gain (approx. rad/s), belongs in [-1, 1].]
115
+ Param: KAZE/Diffusivity = "1" [Diffusivity type: 0=DIFF_PM_G1, 1=DIFF_PM_G2, 2=DIFF_WEICKERT or 3=DIFF_CHARBONNIER.]
116
+ Param: KAZE/Extended = "false" [Set to enable extraction of extended (128-byte) descriptor.]
117
+ Param: KAZE/NOctaveLayers = "4" [Default number of sublevels per scale level.]
118
+ Param: KAZE/NOctaves = "4" [Maximum octave evolution of the image.]
119
+ Param: KAZE/Threshold = "0.001" [Detector response threshold to accept keypoint.]
120
+ Param: KAZE/Upright = "false" [Set to enable use of upright descriptors (non rotation-invariant).]
121
+ Param: Kp/BadSignRatio = "0.5" [Bad signature ratio (less than Ratio x AverageWordsPerImage = bad).]
122
+ Param: Kp/ByteToFloat = "false" [For Kp/NNStrategy=1, binary descriptors are converted to float by converting each byte to float instead of converting each bit to float. When converting bytes instead of bits, less memory is used and search is faster at the cost of slightly less accurate matching.]
123
+ Param: Kp/DetectorStrategy = "8" [0=SURF 1=SIFT 2=ORB 3=FAST/FREAK 4=FAST/BRIEF 5=GFTT/FREAK 6=GFTT/BRIEF 7=BRISK 8=GFTT/ORB 9=KAZE 10=ORB-OCTREE 11=SuperPoint 12=SURF/FREAK 13=GFTT/DAISY 14=SURF/DAISY 15=PyDetector 16=SuperPoint-Rpautrat]
124
+ Param: Kp/DictionaryPath = "" [Path of the pre-computed dictionary]
125
+ Param: Kp/FlannIndexSaved = "false" [Save FLANN index during localization session (when Mem/IncrementalMemory=false). The FLANN index will be saved to database after the first time localization mode is used, then on next sessions, the index is reloaded from the database instead of being rebuilt again. This can save significant loading time when the visual word dictionary is big (>1M words). Note that if the dictionary is modified (parameters or data), the index will be rebuilt and saved again on the next session.]
126
+ Param: Kp/FlannRebalancingFactor = "2.0" [Factor used when rebuilding the incremental FLANN index (see "Kp/IncrementalFlann"). Set <=1 to disable.]
127
+ Param: Kp/GridCols = "1" [Number of columns of the grid used to extract uniformly "Kp/MaxFeatures / grid cells" features from each cell.]
128
+ Param: Kp/GridRows = "1" [Number of rows of the grid used to extract uniformly "Kp/MaxFeatures / grid cells" features from each cell.]
129
+ Param: Kp/IncrementalDictionary = "true" []
130
+ Param: Kp/IncrementalFlann = "true" [When using FLANN based strategy, add/remove points to its index without always rebuilding the index (the index is built only when the dictionary increases of the factor "Kp/FlannRebalancingFactor" in size).]
131
+ Param: Kp/MaxDepth = "0" [Filter extracted keypoints by depth (0=inf).]
132
+ Param: Kp/MaxFeatures = "500" [Maximum features extracted from the images (0 means not bounded, <0 means no extraction).]
133
+ Param: Kp/MinDepth = "0" [Filter extracted keypoints by depth.]
134
+ Param: Kp/NNStrategy = "1" [kNNFlannNaive=0, kNNFlannKdTree=1, kNNFlannLSH=2, kNNBruteForce=3, kNNBruteForceGPU=4]
135
+ Param: Kp/NewWordsComparedTogether = "true" [When adding new words to dictionary, they are compared also with each other (to detect same words in the same signature).]
136
+ Param: Kp/NndrRatio = "0.8" [NNDR ratio (A matching pair is detected, if its distance is closer than X times the distance of the second nearest neighbor.)]
137
+ Param: Kp/Parallelized = "true" [If the dictionary update and signature creation were parallelized.]
138
+ Param: Kp/RoiRatios = "0.0 0.0 0.0 0.0" [Region of interest ratios [left, right, top, bottom].]
139
+ Param: Kp/SSC = "false" [If true, SSC (Suppression via Square Covering) is applied to limit keypoints.]
140
+ Param: Kp/SerializeWithChecksum = "true" [On serialization of the FLANN index, compute checksum of the data used by the FLANN index. This adds a slight overhead on serialization/deserialization to make sure that the dictionary data correspond to same data used when the index was built.]
141
+ Param: Kp/SubPixEps = "0.02" [See cv::cornerSubPix().]
142
+ Param: Kp/SubPixIterations = "0" [See cv::cornerSubPix(). 0 disables sub pixel refining.]
143
+ Param: Kp/SubPixWinSize = "3" [See cv::cornerSubPix().]
144
+ Param: Kp/TfIdfLikelihoodUsed = "true" [Use of the td-idf strategy to compute the likelihood.]
145
+ Param: Marker/CornerRefinementMethod = "0" [Corner refinement method (0: None, 1: Subpixel, 2:contour, 3: AprilTag2). For OpenCV <3.3.0, this is "doCornerRefinement" parameter: set 0 for false and 1 for true.]
146
+ Param: Marker/Dictionary = "0" [Dictionary to use: DICT_ARUCO_4X4_50=0, DICT_ARUCO_4X4_100=1, DICT_ARUCO_4X4_250=2, DICT_ARUCO_4X4_1000=3, DICT_ARUCO_5X5_50=4, DICT_ARUCO_5X5_100=5, DICT_ARUCO_5X5_250=6, DICT_ARUCO_5X5_1000=7, DICT_ARUCO_6X6_50=8, DICT_ARUCO_6X6_100=9, DICT_ARUCO_6X6_250=10, DICT_ARUCO_6X6_1000=11, DICT_ARUCO_7X7_50=12, DICT_ARUCO_7X7_100=13, DICT_ARUCO_7X7_250=14, DICT_ARUCO_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16, DICT_APRILTAG_16h5=17, DICT_APRILTAG_25h9=18, DICT_APRILTAG_36h10=19, DICT_APRILTAG_36h11=20]
147
+ Param: Marker/Length = "0" [The length (m) of the markers' side. 0 means automatic marker length estimation using the depth image (the camera should look at the marker perpendicularly for initialization).]
148
+ Param: Marker/MaxDepthError = "0.01" [Maximum depth error between all corners of a marker when estimating the marker length (when Marker/Length is 0). The smaller it is, the more perpendicular the camera should be toward the marker to initialize the length.]
149
+ Param: Marker/MaxRange = "0.0" [Maximum range in which markers will be detected. <=0 for unlimited range.]
150
+ Param: Marker/MinRange = "0.0" [Miniminum range in which markers will be detected. <=0 for unlimited range.]
151
+ Param: Marker/Priors = "" [World prior locations of the markers. The map will be transformed in marker's world frame when a tag is detected. Format is the marker's ID followed by its position (angles in rad), markers are separated by vertical line ("id1 x y z roll pitch yaw|id2 x y z roll pitch yaw"). Example: "1 0 0 1 0 0 0|2 1 0 1 0 0 1.57" (marker 2 is 1 meter forward than marker 1 with 90 deg yaw rotation).]
152
+ Param: Marker/PriorsVarianceAngular = "0.001" [Angular variance to set on marker priors.]
153
+ Param: Marker/PriorsVarianceLinear = "0.001" [Linear variance to set on marker priors.]
154
+ Param: Marker/VarianceAngular = "0.01" [Angular variance to set on marker detections. If Marker/VarianceOrientationIgnored is enabled, it is ignored with Optimizer/Strategy=1 (g2o) and it corresponds to bearing variance with Optimizer/Strategy=2 (GTSAM).]
155
+ Param: Marker/VarianceLinear = "0.001" [Linear variance to set on marker detections. If Marker/VarianceOrientationIgnored is enabled and Optimizer/Strategy=2 (GTSAM): it is the variance of the range factor, with 9999 to disable range factor and to do only bearing.]
156
+ Param: Marker/VarianceOrientationIgnored = "false" [When this setting is false, the landmark's orientation is optimized during graph optimization. When this setting is true, only the position of the landmark is optimized. This can be useful when the landmark's orientation estimation is not reliable. Note that for Optimizer/Strategy=1 (g2o), only Marker/VarianceLinear needs be set if we ignore orientation. For Optimizer/Strategy=2 (GTSAM), instead of optimizing the landmark's position directly, a bearing/range factor is used, with Marker/VarianceLinear as the variance of the range factor (with 9999 to optimize the position with only a bearing factor) and Marker/VarianceAngular as the variance of the bearing factor (pitch/yaw).]
157
+ Param: Mem/BadSignaturesIgnored = "false" [Bad signatures are ignored.]
158
+ Param: Mem/BinDataKept = "true" [Keep binary data in db.]
159
+ Param: Mem/CompressionParallelized = "true" [Compression of sensor data is multi-threaded.]
160
+ Param: Mem/CovOffDiagIgnored = "true" [Ignore off diagonal values of the covariance matrix.]
161
+ Param: Mem/DepthAsMask = "true" [Use depth image as mask when extracting features for vocabulary.]
162
+ Param: Mem/DepthCompressionFormat = ".rvl" [Depth image compression format for 16UC1 depth type. It should be ".png" or ".rvl". If depth type is 32FC1, ".png" is used.]
163
+ Param: Mem/DepthMaskFloorThr = "0.0" [Filter floor from depth mask below specified threshold (m) before extracting features. 0 means disabled, negative means remove all objects above the floor threshold instead. Ignored if Mem/DepthAsMask is false.]
164
+ Param: Mem/GenerateIds = "true" [True=Generate location IDs, False=use input image IDs.]
165
+ Param: Mem/GlobalDescriptorStrategy = "0" [Extract global descriptor from sensor data. 0=disabled, 1=PyDescriptor]
166
+ Param: Mem/ImageCompressionFormat = ".jpg" [RGB image compression format. It should be ".jpg" or ".png".]
167
+ Param: Mem/ImageKept = "false" [Keep raw images in RAM.]
168
+ Param: Mem/ImagePostDecimation = "1" [Decimation of the RGB image before saving it to database. If depth size is larger than decimated RGB size, depth is decimated to be always at most equal to RGB size. Decimation is done from the original image. If set to same value than Mem/ImagePreDecimation, data already decimated is saved (no need to re-decimate the image).]
169
+ Param: Mem/ImagePreDecimation = "1" [Decimation of the RGB image before visual feature detection. If depth size is larger than decimated RGB size, depth is decimated to be always at most equal to RGB size. If Mem/DepthAsMask is true and if depth is smaller than decimated RGB, depth may be interpolated to match RGB size for feature detection.]
170
+ Param: Mem/IncrementalMemory = "true" [SLAM mode, otherwise it is Localization mode.]
171
+ Param: Mem/InitWMWithAllNodes = "false" [Initialize the Working Memory with all nodes in Long-Term Memory. When false, it is initialized with nodes of the previous session.]
172
+ Param: Mem/IntermediateNodeDataKept = "false" [Keep intermediate node data in db.]
173
+ Param: Mem/LaserScanDownsampleStepSize = "1" [If > 1, downsample the laser scans when creating a signature.]
174
+ Param: Mem/LaserScanNormalK = "0" [If > 0 and laser scans don't have normals, normals will be computed with K search neighbors when creating a signature.]
175
+ Param: Mem/LaserScanNormalRadius = "0.0" [If > 0 m and laser scans don't have normals, normals will be computed with radius search neighbors when creating a signature.]
176
+ Param: Mem/LaserScanVoxelSize = "0.0" [If > 0 m, voxel filtering is done on laser scans when creating a signature. If the laser scan had normals, they will be removed. To recompute the normals, make sure to use "Mem/LaserScanNormalK" or "Mem/LaserScanNormalRadius" parameters.]
177
+ Param: Mem/LoadVisualLocalFeaturesOnInit = "true" [Load all local visual features (keypoints, descriptors and 3D points) in RAM when loading an existing database. This can add significant time to initialize the memory but the features will be already loaded before computing loop closure transforms. If false, the features are loaded on-demand from the database when a loop closure transformation should be estimated.]
178
+ Param: Mem/LocalizationDataSaved = "false" [Save localization data during localization session (when Mem/IncrementalMemory=false). When enabled, the database will then also grow in localization mode. This mode would be used only for debugging purpose.]
179
+ Param: Mem/MapLabelsAdded = "true" [Create map labels. The first node of a map will be labeled as "map#" where # is the map ID.]
180
+ Param: Mem/NotLinkedNodesKept = "true" [Keep not linked nodes in db (rehearsed nodes and deleted nodes).]
181
+ Param: Mem/RawDescriptorsKept = "true" [Raw descriptors kept in memory.]
182
+ Param: Mem/RecentWmRatio = "0.2" [Ratio of locations after the last loop closure in WM that cannot be transferred.]
183
+ Param: Mem/ReduceGraph = "false" [Reduce graph. Merge nodes when loop closures are added (ignoring those with user data). Note that this approach assumes that 100% of the loop closures accepted are good, so it is highly recommended to enable "RGBD/OptimizeMaxError" at the same time.]
184
+ Param: Mem/RehearsalIdUpdatedToNewOne = "false" [On merge, update to new id. When false, no copy.]
185
+ Param: Mem/RehearsalSimilarity = "0.6" [Rehearsal similarity.]
186
+ Param: Mem/RehearsalWeightIgnoredWhileMoving = "false" [When the robot is moving, weights are not updated on rehearsal.]
187
+ Param: Mem/RotateImagesUpsideUp = "false" [Rotate images so that upside is up if they are not already. This can be useful in case the robots don't have all same camera orientation but are using the same map, so that not rotation-invariant visual features can still be used across the fleet.]
188
+ Param: Mem/STMSize = "10" [Short-term memory size.]
189
+ Param: Mem/SaveDepth16Format = "false" [Save depth image into 16 bits format to reduce memory used. Warning: values over ~65 meters are ignored (maximum 65535 millimeters).]
190
+ Param: Mem/StereoFromMotion = "false" [Triangulate features without depth using stereo from motion (odometry). It would be ignored if Mem/DepthAsMask is true and the feature detector used supports masking.]
191
+ Param: Mem/TransferSortingByWeightId = "false" [On transfer, signatures are sorted by weight->ID only (i.e. the oldest of the lowest weighted signatures are transferred first). If false, the signatures are sorted by weight->Age->ID (i.e. the oldest inserted in WM of the lowest weighted signatures are transferred first). Note that retrieval updates the age, not the ID.]
192
+ Param: Mem/UseOdomFeatures = "true" [Use odometry features instead of regenerating them.]
193
+ Param: Mem/UseOdomGravity = "false" [Use odometry instead of IMU orientation to add gravity links to new nodes created. We assume that odometry is already aligned with gravity (e.g., we are using a VIO approach). Gravity constraints are used by graph optimization only if "Optimizer/GravitySigma" is not zero.]
194
+ Param: ORB/EdgeThreshold = "19" [This is size of the border where the features are not detected. It should roughly match the patchSize parameter.]
195
+ Param: ORB/FirstLevel = "0" [It should be 0 in the current implementation.]
196
+ Param: ORB/Gpu = "false" [GPU-ORB: Use GPU version of ORB. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
197
+ Param: ORB/NLevels = "3" [The number of pyramid levels. The smallest level will have linear size equal to input_image_linear_size/pow(scaleFactor, nlevels).]
198
+ Param: ORB/PatchSize = "31" [size of the patch used by the oriented BRIEF descriptor. Of course, on smaller pyramid layers the perceived image area covered by a feature will be larger.]
199
+ Param: ORB/ScaleFactor = "2" [Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor will mean that to cover certain scale range you will need more pyramid levels and so the speed will suffer.]
200
+ Param: ORB/ScoreType = "0" [The default HARRIS_SCORE=0 means that Harris algorithm is used to rank features (the score is written to KeyPoint::score and is used to retain best nfeatures features); FAST_SCORE=1 is alternative value of the parameter that produces slightly less stable keypoints, but it is a little faster to compute.]
201
+ Param: ORB/WTA_K = "2" [The number of points that produce each element of the oriented BRIEF descriptor. The default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 random points (of course, those point coordinates are random, but they are generated from the pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3).]
202
+ Param: Optimizer/Epsilon = "0.00001" [Stop optimizing when the error improvement is less than this value.]
203
+ Param: Optimizer/GravitySigma = "0.3" [Gravity sigma value (>=0, typically between 0.1 and 0.3). Optimization is done while preserving gravity orientation of the poses. This should be used only with visual/lidar inertial odometry approaches, for which we assume that all odometry poses are aligned with gravity. Set to 0 to disable gravity constraints. Currently supported only with g2o and GTSAM optimization strategies (see Optimizer/Strategy).]
204
+ Param: Optimizer/Iterations = "20" [Optimization iterations.]
205
+ Param: Optimizer/LandmarksIgnored = "false" [Ignore landmark constraints while optimizing. Currently only g2o and gtsam optimization supports this.]
206
+ Param: Optimizer/PriorsIgnored = "true" [Ignore prior constraints (global pose or GPS) while optimizing. Currently only g2o and gtsam optimization supports this.]
207
+ Param: Optimizer/Robust = "false" [Robust graph optimization using Vertigo (only work for g2o and GTSAM optimization strategies).]
208
+ Param: Optimizer/Strategy = "2" [Graph optimization strategy: 0=TORO, 1=g2o, 2=GTSAM and 3=Ceres.]
209
+ Param: Optimizer/VarianceIgnored = "false" [Ignore constraints' variance. If checked, identity information matrix is used for each constraint. Otherwise, an information matrix is generated from the variance saved in the links.]
210
+ Param: PyDescriptor/Dim = "4096" [Descriptor dimension.]
211
+ Param: PyDescriptor/Path = "" [Path to python script file (see available ones in rtabmap/corelib/src/pydescriptor/*). See the header to see where the script should be used.]
212
+ Param: PyDetector/Cuda = "true" [Use cuda.]
213
+ Param: PyDetector/Path = "" [Path to python script file (see available ones in rtabmap/corelib/src/python/*). See the header to see where the script should be copied.]
214
+ Param: PyMatcher/Cuda = "true" [Used by SuperGlue.]
215
+ Param: PyMatcher/Iterations = "20" [Sinkhorn iterations. Used by SuperGlue.]
216
+ Param: PyMatcher/Model = "indoor" [For SuperGlue, set only "indoor" or "outdoor". For OANet, set path to one of the pth file (e.g., "OANet/model/gl3d/sift-4000/model_best.pth").]
217
+ Param: PyMatcher/Path = "" [Path to python script file (see available ones in rtabmap/corelib/src/python/*). See the header to see where the script should be copied.]
218
+ Param: PyMatcher/Threshold = "0.2" [Used by SuperGlue.]
219
+ Param: RGBD/AggressiveLoopThr = "0.05" [Loop closure threshold used (overriding Rtabmap/LoopThr) when a new mapping session is not yet linked to a map of the highest loop closure hypothesis. In localization mode, this threshold is used when there are no loop closure constraints with any map in the cache (RGBD/MaxOdomCacheSize). In all cases, the goal is to aggressively loop on a previous map in the database. Only used when RGBD/Enabled is enabled. Set 1 to disable.]
220
+ Param: RGBD/AngularSpeedUpdate = "0.0" [Maximum angular speed (rad/s) to update the map (0 means not limit).]
221
+ Param: RGBD/AngularUpdate = "0.1" [Minimum angular displacement (rad) to update the map. Rehearsal is done prior to this, so weights are still updated. To update the map when not moving, both RGBD/LinearUpdate and RGBD/AngularUpdate should be set to 0.]
222
+ Param: RGBD/CreateOccupancyGrid = "true" [Create local occupancy grid maps. See "Grid" group for parameters.]
223
+ Param: RGBD/Enabled = "true" [Activate metric SLAM. If set to false, classic RTAB-Map loop closure detection is done using only images and without any metric information.]
224
+ Param: RGBD/ForceOdom3DoF = "true" [Force odometry pose to be 3DoF if Reg/Force3DoF=true.]
225
+ Param: RGBD/GoalReachedRadius = "0.5" [Goal reached radius (m).]
226
+ Param: RGBD/GoalsSavedInUserData = "false" [When a goal is received and processed with success, it is saved in user data of the location with this format: "GOAL:#".]
227
+ Param: RGBD/InvertedReg = "false" [On loop closure, do registration from the target to reference instead of reference to target.]
228
+ Param: RGBD/LinearSpeedUpdate = "0.0" [Maximum linear speed (m/s) to update the map (0 means not limit).]
229
+ Param: RGBD/LinearUpdate = "0.1" [Minimum linear displacement (m) to update the map. Rehearsal is done prior to this, so weights are still updated. To update the map when not moving, both RGBD/LinearUpdate and RGBD/AngularUpdate should be set to 0.]
230
+ Param: RGBD/LocalBundleOnLoopClosure = "false" [Do local bundle adjustment with neighborhood of the loop closure.]
231
+ Param: RGBD/LocalImmunizationRatio = "0.25" [Ratio of working memory for which local nodes are immunized from transfer.]
232
+ Param: RGBD/LocalRadius = "10" [Local radius (m) for nodes selection in the local map. This parameter is used in some approaches about the local map management.]
233
+ Param: RGBD/LocalizationPriorError = "0.001" [The corresponding variance (error x error) set to priors of the map's poses during localization (when RGBD/MaxOdomCacheSize>0).]
234
+ Param: RGBD/LocalizationSecondTryWithoutProximityLinks = "true" [When localization is rejected by graph optimization validation, try a second time without proximity links if landmark or loop closure links are also present in odometry cache (see RGBD/MaxOdomCacheSize). If it succeeds, the proximity links are removed. This assumes that global loop closure and landmark links are more accurate than proximity links.]
235
+ Param: RGBD/LocalizationSmoothing = "true" [Adjust localization constraints based on optimized odometry cache poses (when RGBD/MaxOdomCacheSize>0).]
236
+ Param: RGBD/LoopClosureIdentityGuess = "false" [Use Identity matrix as guess when computing loop closure transform, otherwise no guess is used, thus assuming that registration strategy selected (Reg/Strategy) can deal with transformation estimation without guess.]
237
+ Param: RGBD/LoopClosureReextractFeatures = "false" [Extract features even if there are some already in the nodes. Raw features are not saved in database.]
238
+ Param: RGBD/LoopCovLimited = "false" [Limit covariance of non-neighbor links to minimum covariance of neighbor links. In other words, if covariance of a loop closure link is smaller than the minimum covariance of odometry links, its covariance is set to minimum covariance of odometry links.]
239
+ Param: RGBD/MarkerDetection = "false" [Detect static markers to be added as landmarks for graph optimization. If input data have already landmarks, this will be ignored. See "Marker" group for parameters.]
240
+ Param: RGBD/MaxLocalRetrieved = "2" [Maximum local locations retrieved (0=disabled) near the current pose in the local map or on the current planned path (those on the planned path have priority).]
241
+ Param: RGBD/MaxLoopClosureDistance = "0.0" [Reject loop closures/localizations if the distance from the map is over this distance (0=disabled).]
242
+ Param: RGBD/MaxOdomCacheSize = "10" [Maximum odometry cache size. Used only in localization mode (when Mem/IncrementalMemory=false). This is used to get smoother localizations and to verify localization transforms (when RGBD/OptimizeMaxError!=0) to make sure we don't teleport to a location very similar to one we previously localized on. Set 0 to disable caching.]
243
+ Param: RGBD/NeighborLinkRefining = "false" [When a new node is added to the graph, the transformation of its neighbor link to the previous node is refined using registration approach selected (Reg/Strategy).]
244
+ Param: RGBD/NewMapOdomChangeDistance = "0" [A new map is created if a change of odometry translation greater than X m is detected (0 m = disabled).]
245
+ Param: RGBD/OptimizeFromGraphEnd = "false" [Optimize graph from the newest node. If false, the graph is optimized from the oldest node of the current graph (this adds an overhead computation to detect to oldest node of the current graph, but it can be useful to preserve the map referential from the oldest node). Warning when set to false: when some nodes are transferred, the first referential of the local map may change, resulting in momentary changes in robot/map position (which are annoying in teleoperation).]
246
+ Param: RGBD/OptimizeMaxError = "3.0" [Reject loop closures if optimization error ratio is greater than this value (0=disabled). Ratio is computed as absolute error over standard deviation of each link. This will help to detect when a wrong loop closure is added to the graph. If used with "Optimizer/Robust", the disabled loop closure links will be removed.]
247
+ Param: RGBD/PlanAngularVelocity = "0" [Angular velocity (rad/sec) used to compute path weights.]
248
+ Param: RGBD/PlanLinearVelocity = "0" [Linear velocity (m/sec) used to compute path weights.]
249
+ Param: RGBD/PlanStuckIterations = "0" [Mark the current goal node on the path as unreachable if it is not updated after X iterations (0=disabled). If all upcoming nodes on the path are unreachabled, the plan fails.]
250
+ Param: RGBD/ProximityAngle = "45" [Maximum angle (degrees) for one-to-one proximity detection.]
251
+ Param: RGBD/ProximityBySpace = "true" [Detection over locations (in Working Memory) near in space.]
252
+ Param: RGBD/ProximityByTime = "false" [Detection over all locations in STM.]
253
+ Param: RGBD/ProximityGlobalScanMap = "false" [Create a global assembled map from laser scans for one-to-many proximity detection, replacing the original one-to-many proximity detection (i.e., detection against local paths). Only used in localization mode (Mem/IncrementalMemory=false), otherwise original one-to-many proximity detection is done. Note also that if graph is modified (i.e., memory management is enabled or robot jumps from one disjoint session to another in same database), the global scan map is cleared and one-to-many proximity detection is reverted to original approach.]
254
+ Param: RGBD/ProximityMaxGraphDepth = "50" [Maximum depth from the current/last loop closure location and the local loop closure hypotheses. Set 0 to ignore.]
255
+ Param: RGBD/ProximityMaxPaths = "3" [Maximum paths compared (from the most recent) for proximity detection. 0 means no limit.]
256
+ Param: RGBD/ProximityMergedScanCovFactor = "100.0" [Covariance factor for one-to-many proximity detection (when RGBD/ProximityPathMaxNeighbors>0 and scans are used).]
257
+ Param: RGBD/ProximityOdomGuess = "false" [Use odometry as motion guess for one-to-one proximity detection.]
258
+ Param: RGBD/ProximityPathFilteringRadius = "1" [Path filtering radius to reduce the number of nodes to compare in a path in one-to-many proximity detection. The nearest node in a path should be inside that radius to be considered for one-to-one proximity detection.]
259
+ Param: RGBD/ProximityPathMaxNeighbors = "0" [Maximum neighbor nodes compared on each path for one-to-many proximity detection. Set to 0 to disable one-to-many proximity detection (by merging the laser scans).]
260
+ Param: RGBD/ProximityPathRawPosesUsed = "true" [When comparing to a local path for one-to-many proximity detection, merge the scans using the odometry poses (with neighbor link optimizations) instead of the ones in the optimized local graph.]
261
+ Param: RGBD/ScanMatchingIdsSavedInLinks = "true" [Save scan matching IDs from one-to-many proximity detection in link's user data.]
262
+ Param: RGBD/StartAtOrigin = "false" [If true, rtabmap will assume the robot is starting from origin of the map. If false, rtabmap will assume the robot is restarting from the last saved localization pose from previous session (the place where it shut down previously). Used only in localization mode (Mem/IncrementalMemory=false).]
263
+ Param: Reg/Force3DoF = "false" [Force 3 degrees-of-freedom transform (3Dof: x,y and yaw). Parameters z, roll and pitch will be set to 0.]
264
+ Param: Reg/RepeatOnce = "true" [Do a second registration with the output of the first registration as guess. Only done if no guess was provided for the first registration (like on loop closure). It can be useful if the registration approach used can use a guess to get better matches.]
265
+ Param: Reg/Strategy = "0" [0=Vis, 1=Icp, 2=VisIcp]
266
+ Param: Rtabmap/ComputeRMSE = "true" [Compute root mean square error (RMSE) and publish it in statistics, if ground truth is provided.]
267
+ Param: Rtabmap/CreateIntermediateNodes = "false" [Create intermediate nodes between loop closure detection. Only used when Rtabmap/DetectionRate>0.]
268
+ Param: Rtabmap/DetectionRate = "1" [Detection rate (Hz). RTAB-Map will filter input images to satisfy this rate.]
269
+ Param: Rtabmap/ImageBufferSize = "1" [Data buffer size (0 min inf).]
270
+ Param: Rtabmap/ImagesAlreadyRectified = "true" [Images are already rectified. By default RTAB-Map assumes that received images are rectified. If they are not, they can be rectified by RTAB-Map if this parameter is false.]
271
+ Param: Rtabmap/LoopGPS = "true" [Use GPS to filter likelihood (if GPS is recorded). Only locations inside the local radius "RGBD/LocalRadius" of the current GPS location are considered for loop closure detection.]
272
+ Param: Rtabmap/LoopRatio = "0" [The loop closure hypothesis must be over LoopRatio x lastHypothesisValue.]
273
+ Param: Rtabmap/LoopThr = "0.11" [Loop closing threshold.]
274
+ Param: Rtabmap/MaxRepublished = "2" [Maximum nodes republished when requesting missing data. When RGBD/Enabled=false, only loop closure data is republished, otherwise the closest nodes from the current localization are republished first. Ignored if Rtabmap/PublishLastSignature=false.]
275
+ Param: Rtabmap/MaxRetrieved = "2" [Maximum nodes retrieved at the same time from LTM.]
276
+ Param: Rtabmap/MemoryThr = "0" [Maximum nodes in the Working Memory (0 means infinity). Similar to "Rtabmap/TimeThr", when the number of nodes in Working Memory (WM) exceeds this treshold, some nodes are transferred to Long-Term Memory to keep WM size fixed.]
277
+ Param: Rtabmap/PublishLastSignature = "true" [Publishing last signature.]
278
+ Param: Rtabmap/PublishLikelihood = "true" [Publishing likelihood.]
279
+ Param: Rtabmap/PublishPdf = "true" [Publishing pdf.]
280
+ Param: Rtabmap/PublishRAMUsage = "false" [Publishing RAM usage in statistics (may add a small overhead to get info from the system).]
281
+ Param: Rtabmap/PublishStats = "true" [Publishing statistics.]
282
+ Param: Rtabmap/RectifyOnlyFeatures = "false" [If "Rtabmap/ImagesAlreadyRectified" is false and this parameter is true, the whole RGB image will not be rectified, only the features. Warning: As projection of RGB-D image to point cloud is assuming that images are rectified, the generated point cloud map will have wrong colors if this parameter is true.]
283
+ Param: Rtabmap/SaveWMState = "false" [Save working memory state after each update in statistics.]
284
+ Param: Rtabmap/StartNewMapOnGoodSignature = "false" [Start a new map only if the first signature is not bad (i.e., has enough features, see Kp/BadSignRatio).]
285
+ Param: Rtabmap/StartNewMapOnLoopClosure = "false" [Start a new map only if there is a global loop closure with a previous map.]
286
+ Param: Rtabmap/StatisticLogged = "false" [Logging enabled.]
287
+ Param: Rtabmap/StatisticLoggedHeaders = "true" [Add column header description to log files.]
288
+ Param: Rtabmap/StatisticLogsBufferedInRAM = "true" [Statistic logs buffered in RAM instead of written to hard drive after each iteration.]
289
+ Param: Rtabmap/TimeThr = "0" [Maximum time allowed for map update (ms) (0 means infinity). When map update time exceeds this fixed time threshold, some nodes in Working Memory (WM) are transferred to Long-Term Memory to limit the size of the WM and decrease the update time.]
290
+ Param: Rtabmap/VirtualPlaceLikelihoodRatio = "0" [Likelihood ratio for virtual place (for no loop closure hypothesis): 0=Mean / StdDev, 1=StdDev / (Max-Mean)]
291
+ Param: Rtabmap/WorkingDirectory = "/home/jaco/.ros" [Working directory.]
292
+ Param: SIFT/ContrastThreshold = "0.04" [The contrast threshold used to filter out weak features in semi-uniform (low-contrast) regions. The larger the threshold, the less features are produced by the detector. Not used by CudaSift (see SIFT/GaussianThreshold instead).]
293
+ Param: SIFT/EdgeThreshold = "10" [The threshold used to filter out edge-like features. Note that the its meaning is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are filtered out (more features are retained).]
294
+ Param: SIFT/GaussianThreshold = "2.0" [CudaSift: Threshold on difference of Gaussians for feature pruning. The higher the threshold, the less features are produced by the detector.]
295
+ Param: SIFT/Gpu = "false" [CudaSift: Use GPU version of SIFT. This option is enabled only if RTAB-Map is built with CudaSift dependency and GPUs are detected.]
296
+ Param: SIFT/NOctaveLayers = "3" [The number of layers in each octave. 3 is the value used in D. Lowe paper. The number of octaves is computed automatically from the image resolution. Not used by CudaSift, the number of octaves is still computed automatically.]
297
+ Param: SIFT/PreciseUpscale = "false" [Whether to enable precise upscaling in the scale pyramid (OpenCV >= 4.8).]
298
+ Param: SIFT/RootSIFT = "false" [Apply RootSIFT normalization of the descriptors.]
299
+ Param: SIFT/Sigma = "1.6" [The sigma of the Gaussian applied to the input image at the octave #0. If your image is captured with a weak camera with soft lenses, you might want to reduce the number.]
300
+ Param: SIFT/Upscale = "false" [CudaSift: Whether to enable upscaling.]
301
+ Param: SURF/Extended = "false" [Extended descriptor flag (true - use extended 128-element descriptors; false - use 64-element descriptors).]
302
+ Param: SURF/GpuKeypointsRatio = "0.01" [Used with SURF GPU.]
303
+ Param: SURF/GpuVersion = "false" [GPU-SURF: Use GPU version of SURF. This option is enabled only if OpenCV is built with CUDA and GPUs are detected.]
304
+ Param: SURF/HessianThreshold = "500" [Threshold for hessian keypoint detector used in SURF.]
305
+ Param: SURF/OctaveLayers = "2" [Number of octave layers within each octave.]
306
+ Param: SURF/Octaves = "4" [Number of pyramid octaves the keypoint detector will use.]
307
+ Param: SURF/Upright = "false" [Up-right or rotated features flag (true - do not compute orientation of features; false - compute orientation).]
308
+ Param: Stereo/DenseStrategy = "0" [0=cv::StereoBM, 1=cv::StereoSGBM]
309
+ Param: Stereo/Eps = "0.01" [[Stereo/OpticalFlow=true] Epsilon stop criterion.]
310
+ Param: Stereo/Gpu = "false" [[Stereo/OpticalFlow=true] Enable GPU version of the optical flow approach (only available if OpenCV is built with CUDA).]
311
+ Param: Stereo/Iterations = "30" [Maximum iterations.]
312
+ Param: Stereo/MaxDisparity = "128.0" [Maximum disparity.]
313
+ Param: Stereo/MaxLevel = "5" [Maximum pyramid level.]
314
+ Param: Stereo/MinDisparity = "0.5" [Minimum disparity.]
315
+ Param: Stereo/OpticalFlow = "true" [Use optical flow to find stereo correspondences, otherwise a simple block matching approach is used.]
316
+ Param: Stereo/SSD = "true" [[Stereo/OpticalFlow=false] Use Sum of Squared Differences (SSD) window, otherwise Sum of Absolute Differences (SAD) window is used.]
317
+ Param: Stereo/WinHeight = "3" [Window height.]
318
+ Param: Stereo/WinWidth = "15" [Window width.]
319
+ Param: StereoBM/BlockSize = "15" [See cv::StereoBM]
320
+ Param: StereoBM/Disp12MaxDiff = "-1" [See cv::StereoBM]
321
+ Param: StereoBM/MinDisparity = "0" [See cv::StereoBM]
322
+ Param: StereoBM/NumDisparities = "128" [See cv::StereoBM]
323
+ Param: StereoBM/PreFilterCap = "31" [See cv::StereoBM]
324
+ Param: StereoBM/PreFilterSize = "9" [See cv::StereoBM]
325
+ Param: StereoBM/SpeckleRange = "4" [See cv::StereoBM]
326
+ Param: StereoBM/SpeckleWindowSize = "100" [See cv::StereoBM]
327
+ Param: StereoBM/TextureThreshold = "10" [See cv::StereoBM]
328
+ Param: StereoBM/UniquenessRatio = "15" [See cv::StereoBM]
329
+ Param: StereoSGBM/BlockSize = "15" [See cv::StereoSGBM]
330
+ Param: StereoSGBM/Disp12MaxDiff = "1" [See cv::StereoSGBM]
331
+ Param: StereoSGBM/MinDisparity = "0" [See cv::StereoSGBM]
332
+ Param: StereoSGBM/Mode = "2" [See cv::StereoSGBM]
333
+ Param: StereoSGBM/NumDisparities = "128" [See cv::StereoSGBM]
334
+ Param: StereoSGBM/P1 = "2" [See cv::StereoSGBM]
335
+ Param: StereoSGBM/P2 = "5" [See cv::StereoSGBM]
336
+ Param: StereoSGBM/PreFilterCap = "31" [See cv::StereoSGBM]
337
+ Param: StereoSGBM/SpeckleRange = "4" [See cv::StereoSGBM]
338
+ Param: StereoSGBM/SpeckleWindowSize = "100" [See cv::StereoSGBM]
339
+ Param: StereoSGBM/UniquenessRatio = "20" [See cv::StereoSGBM]
340
+ Param: SuperPoint/Cuda = "true" [Use Cuda device for Torch, otherwise CPU device is used by default.]
341
+ Param: SuperPoint/ModelPath = "" [[Required] Path to pre-trained weights Torch file of SuperPoint (*.pt).]
342
+ Param: SuperPoint/NMS = "true" [If true, non-maximum suppression is applied to detected keypoints.]
343
+ Param: SuperPoint/NMSRadius = "4" [[SuperPoint/NMS=true] Minimum distance (pixels) between keypoints.]
344
+ Param: SuperPoint/Threshold = "0.010" [Detector response threshold to accept keypoint.]
345
+ Param: SuperPointRpautrat/Cuda = "true" [Use Cuda device for Torch, otherwise CPU device is used by default.]
346
+ Param: SuperPointRpautrat/ModelPath = "" [[Required] SuperPoint python model file (superpoint_pytorch.py).]
347
+ Param: SuperPointRpautrat/NMS = "true" [If true, non-maximum suppression is applied to detected keypoints.]
348
+ Param: SuperPointRpautrat/NMSRadius = "4" [[SuperPointRpautrat/NMS=true] Minimum distance (pixels) between keypoints.]
349
+ Param: SuperPointRpautrat/Threshold = "0.005" [Detector response threshold to accept keypoint.]
350
+ Param: SuperPointRpautrat/WeightsPath = "" [[Required] SuperPoint weights file (*.pth).]
351
+ Param: VhEp/Enabled = "false" [Verify visual loop closure hypothesis by computing a fundamental matrix. This is done prior to transformation computation when RGBD/Enabled is enabled.]
352
+ Param: VhEp/MatchCountMin = "8" [Minimum of matching visual words pairs to accept the loop hypothesis.]
353
+ Param: VhEp/RansacParam1 = "3" [Fundamental matrix (see cvFindFundamentalMat()): Max distance (in pixels) from the epipolar line for a point to be inlier.]
354
+ Param: VhEp/RansacParam2 = "0.99" [Fundamental matrix (see cvFindFundamentalMat()): Performance of RANSAC.]
355
+ Param: Vis/BundleAdjustment = "1" [Optimization with bundle adjustment: 0=disabled, 1=g2o, 2=cvsba, 3=Ceres.]
356
+ Param: Vis/CorFlowEps = "0.01" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
357
+ Param: Vis/CorFlowGpu = "false" [[Vis/CorType=1] Enable GPU version of the optical flow approach (only available if OpenCV is built with CUDA).]
358
+ Param: Vis/CorFlowIterations = "30" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
359
+ Param: Vis/CorFlowMaxLevel = "3" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
360
+ Param: Vis/CorFlowWinSize = "16" [[Vis/CorType=1] See cv::calcOpticalFlowPyrLK(). Used for optical flow approach.]
361
+ Param: Vis/CorGuessMatchToProjection = "false" [[Vis/CorType=0] Match frame's corners to source's projected points (when guess transform is provided) instead of projected points to frame's corners.]
362
+ Param: Vis/CorGuessWinSize = "40" [[Vis/CorType=0] Matching window size (pixels) around projected points when a guess transform is provided to find correspondences. 0 means disabled.]
363
+ Param: Vis/CorNNDR = "0.8" [[Vis/CorType=0] NNDR: nearest neighbor distance ratio. Used for knn features matching approach.]
364
+ Param: Vis/CorNNType = "1" [[Vis/CorType=0] kNNFlannNaive=0, kNNFlannKdTree=1, kNNFlannLSH=2, kNNBruteForce=3, kNNBruteForceGPU=4, BruteForceCrossCheck=5, SuperGlue=6, GMS=7. Used for features matching approach.]
365
+ Param: Vis/CorType = "0" [Correspondences computation approach: 0=Features Matching, 1=Optical Flow]
366
+ Param: Vis/DepthAsMask = "true" [Use depth image as mask when extracting features.]
367
+ Param: Vis/DepthMaskFloorThr = "0.0" [Filter floor from depth mask below specified threshold (m) before extracting features. 0 means disabled, negative means remove all objects above the floor threshold instead. Ignored if Vis/DepthAsMask is false.]
368
+ Param: Vis/EpipolarGeometryVar = "0.1" [[Vis/EstimationType = 2] Epipolar geometry maximum variance to accept the transformation.]
369
+ Param: Vis/EstimationType = "1" [Motion estimation approach: 0:3D->3D, 1:3D->2D (PnP), 2:2D->2D (Epipolar Geometry)]
370
+ Param: Vis/FeatureType = "8" [0=SURF 1=SIFT 2=ORB 3=FAST/FREAK 4=FAST/BRIEF 5=GFTT/FREAK 6=GFTT/BRIEF 7=BRISK 8=GFTT/ORB 9=KAZE 10=ORB-OCTREE 11=SuperPoint 12=SURF/FREAK 13=GFTT/DAISY 14=SURF/DAISY 15=PyDetector 16=SuperPoint-Rpautrat]
371
+ Param: Vis/GridCols = "1" [Number of columns of the grid used to extract uniformly "Vis/MaxFeatures / grid cells" features from each cell.]
372
+ Param: Vis/GridRows = "1" [Number of rows of the grid used to extract uniformly "Vis/MaxFeatures / grid cells" features from each cell.]
373
+ Param: Vis/InlierDistance = "0.1" [[Vis/EstimationType = 0] Maximum distance for feature correspondences. Used by 3D->3D estimation approach.]
374
+ Param: Vis/Iterations = "300" [Maximum iterations to compute the transform.]
375
+ Param: Vis/MaxDepth = "0" [Max depth of the features (0 means no limit).]
376
+ Param: Vis/MaxFeatures = "1000" [0 no limits.]
377
+ Param: Vis/MeanInliersDistance = "0.0" [Maximum distance (m) of the mean distance of inliers from the camera to accept the transformation. 0 means disabled.]
378
+ Param: Vis/MinDepth = "0" [Min depth of the features (0 means no limit).]
379
+ Param: Vis/MinInliers = "20" [Minimum feature correspondences to compute/accept the transformation.]
380
+ Param: Vis/MinInliersDistribution = "0.0" [Minimum distribution value of the inliers in the image to accept the transformation. The distribution is the second eigen value of the PCA (Principal Component Analysis) on the keypoints of the normalized image [-0.5, 0.5]. The value would be between 0 and 0.5. 0 means disabled.]
381
+ Param: Vis/PnPFlags = "0" [[Vis/EstimationType = 1] PnP flags: 0=Iterative, 1=EPNP, 2=P3P]
382
+ Param: Vis/PnPMaxVariance = "0.0" [[Vis/EstimationType = 1] Max linear variance between 3D point correspondences after PnP. 0 means disabled.]
383
+ Param: Vis/PnPRefineIterations = "0" [[Vis/EstimationType = 1] Refine iterations. Set to 0 if "Vis/BundleAdjustment" is also used.]
384
+ Param: Vis/PnPReprojError = "2" [[Vis/EstimationType = 1] PnP reprojection error.]
385
+ Param: Vis/PnPSamplingPolicy = "1" [[Vis/EstimationType = 1] Multi-camera random sampling policy: 0=AUTO, 1=ANY, 2=HOMOGENEOUS. With HOMOGENEOUS policy, RANSAC will be done uniformly against all cameras, so at least 2 matches per camera are required. With ANY policy, RANSAC is not constraint to sample on all cameras at the same time. AUTO policy will use HOMOGENEOUS if there are at least 2 matches per camera, otherwise it will fallback to ANY policy.]
386
+ Param: Vis/PnPSplitLinearCovComponents = "false" [[Vis/EstimationType = 1] Compute variance for each linear component instead of using the combined XYZ variance for all linear components.]
387
+ Param: Vis/PnPVarianceMedianRatio = "4" [[Vis/EstimationType = 1] Ratio used to compute variance of the estimated transformation if 3D correspondences are provided (should be > 1). The higher it is, the smaller the covariance will be. With accurate depth estimation, this could be set to 2. For depth estimated by stereo, 4 or more maybe used to ignore large errors of very far points.]
388
+ Param: Vis/RefineIterations = "5" [[Vis/EstimationType = 0] Number of iterations used to refine the transformation found by RANSAC. 0 means that the transformation is not refined.]
389
+ Param: Vis/RoiRatios = "0.0 0.0 0.0 0.0" [Region of interest ratios [left, right, top, bottom].]
390
+ Param: Vis/SSC = "false" [If true, SSC (Suppression via Square Covering) is applied to limit keypoints.]
391
+ Param: Vis/SubPixEps = "0.02" [See cv::cornerSubPix().]
392
+ Param: Vis/SubPixIterations = "0" [See cv::cornerSubPix(). 0 disables sub pixel refining.]
393
+ Param: Vis/SubPixWinSize = "3" [See cv::cornerSubPix().]
394
+ Param: g2o/Baseline = "0.075" [When doing bundle adjustment with RGB-D data, we can set a fake baseline (m) to do stereo bundle adjustment (if 0, mono bundle adjustment is done). For stereo data, the baseline in the calibration is used directly.]
395
+ Param: g2o/Optimizer = "0" [0=Levenberg 1=GaussNewton]
396
+ Param: g2o/PixelVariance = "1.0" [Pixel variance used for bundle adjustment.]
397
+ Param: g2o/RobustKernelDelta = "8" [Robust kernel delta used for bundle adjustment (0 means don't use robust kernel). Observations with chi2 over this threshold will be ignored in the second optimization pass.]
398
+ Param: g2o/Solver = "0"
experiments/rtabmap/params/u_route.yaml ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ waypoints:
2
+ - pose:
3
+ orientation:
4
+ theta: 1.5707963267948966
5
+ position:
6
+ x: 0.0
7
+ y: 0.0
8
+ - pose:
9
+ orientation:
10
+ theta: 1.5707963267948966
11
+ position:
12
+ x: 0.0
13
+ y: 1.0
14
+ - pose:
15
+ orientation:
16
+ theta: 1.5707963267948966
17
+ position:
18
+ x: 0.0
19
+ y: 2.0
20
+ - pose:
21
+ orientation:
22
+ theta: 1.5707963267948966
23
+ position:
24
+ x: 0.0
25
+ y: 3.0
26
+ - pose:
27
+ orientation:
28
+ theta: 1.5707963267948966
29
+ position:
30
+ x: 0.0
31
+ y: 4.0
32
+ - pose:
33
+ orientation:
34
+ theta: 1.5707963267948966
35
+ position:
36
+ x: 0.0
37
+ y: 5.0
38
+ - pose:
39
+ orientation:
40
+ theta: 1.5707963267948966
41
+ position:
42
+ x: 0.0
43
+ y: 6.0
44
+ - pose:
45
+ orientation:
46
+ theta: 1.5707963267948966
47
+ position:
48
+ x: 0.0
49
+ y: 7.0
50
+ - pose:
51
+ orientation:
52
+ theta: 1.5707963267948966
53
+ position:
54
+ x: 0.0
55
+ y: 8.0
56
+ - pose:
57
+ orientation:
58
+ theta: 1.5707963267948966
59
+ position:
60
+ x: 0.0
61
+ y: 9.0
62
+ - pose:
63
+ orientation:
64
+ theta: 1.5393804002589992
65
+ position:
66
+ x: 0.0
67
+ y: 10.0
68
+ - pose:
69
+ orientation:
70
+ theta: 1.476548547187204
71
+ position:
72
+ x: 0.0049331789293209916
73
+ y: 10.156976298823283
74
+ - pose:
75
+ orientation:
76
+ theta: 1.4137166941154056
77
+ position:
78
+ x: 0.019713246713805255
79
+ y: 10.313333083910761
80
+ - pose:
81
+ orientation:
82
+ theta: 1.3508848410436105
83
+ position:
84
+ x: 0.044281873178278364
85
+ y: 10.468453286464312
86
+ - pose:
87
+ orientation:
88
+ theta: 1.288052987971813
89
+ position:
90
+ x: 0.07854209717842231
91
+ y: 10.621724717912137
92
+ - pose:
93
+ orientation:
94
+ theta: 1.2252211349000226
95
+ position:
96
+ x: 0.12235870926211634
97
+ y: 10.772542485937368
98
+ - pose:
99
+ orientation:
100
+ theta: 1.162389281828224
101
+ position:
102
+ x: 0.1755587852793714
103
+ y: 10.920311381711695
104
+ - pose:
105
+ orientation:
106
+ theta: 1.0995574287564258
107
+ position:
108
+ x: 0.23793236883495084
109
+ y: 11.064448228912681
110
+ - pose:
111
+ orientation:
112
+ theta: 1.0367255756846356
113
+ position:
114
+ x: 0.3092332998903409
115
+ y: 11.204384185254288
116
+ - pose:
117
+ orientation:
118
+ theta: 0.9738937226128352
119
+ position:
120
+ x: 0.3891801862449622
121
+ y: 11.339566987447492
122
+ - pose:
123
+ orientation:
124
+ theta: 0.911061869541035
125
+ position:
126
+ x: 0.47745751406263137
127
+ y: 11.469463130731183
128
+ - pose:
129
+ orientation:
130
+ theta: 0.8482300164692473
131
+ position:
132
+ x: 0.573716893060527
133
+ y: 11.593559974371724
134
+ - pose:
135
+ orientation:
136
+ theta: 0.7853981633974523
137
+ position:
138
+ x: 0.677578431446471
139
+ y: 11.711367764821722
140
+ - pose:
141
+ orientation:
142
+ theta: 0.7225663103256436
143
+ position:
144
+ x: 0.7886322351782784
145
+ y: 11.82242156855353
146
+ - pose:
147
+ orientation:
148
+ theta: 0.6597344572538605
149
+ position:
150
+ x: 0.9064400256282756
151
+ y: 11.926283106939472
152
+ - pose:
153
+ orientation:
154
+ theta: 0.5969026041820613
155
+ position:
156
+ x: 1.0305368692688168
157
+ y: 12.022542485937368
158
+ - pose:
159
+ orientation:
160
+ theta: 0.5340707511102645
161
+ position:
162
+ x: 1.1604330125525086
163
+ y: 12.110819813755038
164
+ - pose:
165
+ orientation:
166
+ theta: 0.4712388980384715
167
+ position:
168
+ x: 1.2956158147457122
169
+ y: 12.19076670010966
170
+ - pose:
171
+ orientation:
172
+ theta: 0.4084070449666747
173
+ position:
174
+ x: 1.4355517710873182
175
+ y: 12.26206763116505
176
+ - pose:
177
+ orientation:
178
+ theta: 0.34557519189487457
179
+ position:
180
+ x: 1.5796886182883048
181
+ y: 12.324441214720629
182
+ - pose:
183
+ orientation:
184
+ theta: 0.2827433388230792
185
+ position:
186
+ x: 1.7274575140626314
187
+ y: 12.377641290737884
188
+ - pose:
189
+ orientation:
190
+ theta: 0.21991148575128946
191
+ position:
192
+ x: 1.8782752820878632
193
+ y: 12.421457902821578
194
+ - pose:
195
+ orientation:
196
+ theta: 0.15707963267948274
197
+ position:
198
+ x: 2.031546713535688
199
+ y: 12.455718126821722
200
+ - pose:
201
+ orientation:
202
+ theta: 0.0942477796077017
203
+ position:
204
+ x: 2.186666916089239
205
+ y: 12.480286753286194
206
+ - pose:
207
+ orientation:
208
+ theta: 0.0314159265358944
209
+ position:
210
+ x: 2.3430237011767163
211
+ y: 12.49506682107068
212
+ - pose:
213
+ orientation:
214
+ theta: -0.0314159265358944
215
+ position:
216
+ x: 2.5
217
+ y: 12.5
218
+ - pose:
219
+ orientation:
220
+ theta: -0.09424777960770223
221
+ position:
222
+ x: 2.6569762988232837
223
+ y: 12.49506682107068
224
+ - pose:
225
+ orientation:
226
+ theta: -0.1570796326794823
227
+ position:
228
+ x: 2.81333308391076
229
+ y: 12.480286753286194
230
+ - pose:
231
+ orientation:
232
+ theta: -0.21991148575128824
233
+ position:
234
+ x: 2.9684532864643116
235
+ y: 12.455718126821722
236
+ - pose:
237
+ orientation:
238
+ theta: -0.2827433388230816
239
+ position:
240
+ x: 3.1217247179121372
241
+ y: 12.421457902821578
242
+ - pose:
243
+ orientation:
244
+ theta: -0.34557519189487507
245
+ position:
246
+ x: 3.2725424859373677
247
+ y: 12.377641290737884
248
+ - pose:
249
+ orientation:
250
+ theta: -0.4084070449666719
251
+ position:
252
+ x: 3.420311381711694
253
+ y: 12.324441214720629
254
+ - pose:
255
+ orientation:
256
+ theta: -0.47123889803846963
257
+ position:
258
+ x: 3.5644482289126818
259
+ y: 12.26206763116505
260
+ - pose:
261
+ orientation:
262
+ theta: -0.5340707511102638
263
+ position:
264
+ x: 3.7043841852542885
265
+ y: 12.19076670010966
266
+ - pose:
267
+ orientation:
268
+ theta: -0.5969026041820669
269
+ position:
270
+ x: 3.8395669874474923
271
+ y: 12.110819813755038
272
+ - pose:
273
+ orientation:
274
+ theta: -0.659734457253857
275
+ position:
276
+ x: 3.9694631307311825
277
+ y: 12.022542485937368
278
+ - pose:
279
+ orientation:
280
+ theta: -0.722566310325653
281
+ position:
282
+ x: 4.093559974371725
283
+ y: 11.926283106939472
284
+ - pose:
285
+ orientation:
286
+ theta: -0.7853981633974483
287
+ position:
288
+ x: 4.211367764821722
289
+ y: 11.822421568553528
290
+ - pose:
291
+ orientation:
292
+ theta: -0.8482300164692357
293
+ position:
294
+ x: 4.322421568553528
295
+ y: 11.711367764821722
296
+ - pose:
297
+ orientation:
298
+ theta: -0.9110618695410441
299
+ position:
300
+ x: 4.426283106939473
301
+ y: 11.593559974371725
302
+ - pose:
303
+ orientation:
304
+ theta: -0.9738937226128376
305
+ position:
306
+ x: 4.522542485937368
307
+ y: 11.469463130731183
308
+ - pose:
309
+ orientation:
310
+ theta: -1.0367255756846308
311
+ position:
312
+ x: 4.610819813755037
313
+ y: 11.339566987447492
314
+ - pose:
315
+ orientation:
316
+ theta: -1.0995574287564307
317
+ position:
318
+ x: 4.690766700109659
319
+ y: 11.204384185254288
320
+ - pose:
321
+ orientation:
322
+ theta: -1.1623892818282213
323
+ position:
324
+ x: 4.762067631165048
325
+ y: 11.064448228912681
326
+ - pose:
327
+ orientation:
328
+ theta: -1.2252211349000173
329
+ position:
330
+ x: 4.824441214720628
331
+ y: 10.920311381711695
332
+ - pose:
333
+ orientation:
334
+ theta: -1.2880529879718159
335
+ position:
336
+ x: 4.877641290737884
337
+ y: 10.772542485937368
338
+ - pose:
339
+ orientation:
340
+ theta: -1.3508848410436078
341
+ position:
342
+ x: 4.921457902821578
343
+ y: 10.621724717912137
344
+ - pose:
345
+ orientation:
346
+ theta: -1.4137166941154138
347
+ position:
348
+ x: 4.955718126821722
349
+ y: 10.468453286464312
350
+ - pose:
351
+ orientation:
352
+ theta: -1.4765485471871944
353
+ position:
354
+ x: 4.980286753286194
355
+ y: 10.313333083910761
356
+ - pose:
357
+ orientation:
358
+ theta: -1.5393804002590024
359
+ position:
360
+ x: 4.9950668210706795
361
+ y: 10.156976298823285
362
+ - pose:
363
+ orientation:
364
+ theta: -1.5707963267948966
365
+ position:
366
+ x: 5.0
367
+ y: 10.0
368
+ - pose:
369
+ orientation:
370
+ theta: -1.5707963267948966
371
+ position:
372
+ x: 5.0
373
+ y: 9.0
374
+ - pose:
375
+ orientation:
376
+ theta: -1.5707963267948966
377
+ position:
378
+ x: 5.0
379
+ y: 8.0
380
+ - pose:
381
+ orientation:
382
+ theta: -1.5707963267948966
383
+ position:
384
+ x: 5.0
385
+ y: 7.0
386
+ - pose:
387
+ orientation:
388
+ theta: -1.5707963267948966
389
+ position:
390
+ x: 5.0
391
+ y: 6.0
392
+ - pose:
393
+ orientation:
394
+ theta: -1.5707963267948966
395
+ position:
396
+ x: 5.0
397
+ y: 5.0
398
+ - pose:
399
+ orientation:
400
+ theta: -1.5707963267948966
401
+ position:
402
+ x: 5.0
403
+ y: 4.0
404
+ - pose:
405
+ orientation:
406
+ theta: -1.5707963267948966
407
+ position:
408
+ x: 5.0
409
+ y: 3.0
410
+ - pose:
411
+ orientation:
412
+ theta: -1.5707963267948966
413
+ position:
414
+ x: 5.0
415
+ y: 2.0
416
+ - pose:
417
+ orientation:
418
+ theta: -1.5707963267948966
419
+ position:
420
+ x: 5.0
421
+ y: 1.0
experiments/rtabmap/rtab_odom.launch.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from launch import LaunchDescription
3
+ from launch_ros.actions import Node
4
+ from launch.actions import DeclareLaunchArgument
5
+
6
+ def generate_launch_description():
7
+
8
+ # Parâmetros comuns para Simulação
9
+ use_sim_time = {'use_sim_time': True}
10
+
11
+ # 1. Sincronizador RGB-D
12
+ sync_node = Node(
13
+ package='rtabmap_sync',
14
+ executable='rgbd_sync',
15
+ name='rgbd_sync',
16
+ parameters=[{
17
+ 'approx_sync': True,
18
+ 'approx_sync_max_interval': 0.125,
19
+ 'queue_size': 10,
20
+ **use_sim_time
21
+ }],
22
+ remappings=[
23
+ ('rgb/image', '/camera_front/rgb'),
24
+ ('depth/image', '/camera_front/depth'),
25
+ ('rgb/camera_info', '/camera_front/camera_info'),
26
+ ('rgbd_image', '/camera_front/rgbd_image')
27
+ ],
28
+ output='screen'
29
+ )
30
+
31
+ # 2. Visual Odometry Node
32
+ # This node computes odometry from the RGB-D stream
33
+ odom_node = Node(
34
+ package='rtabmap_odom',
35
+ executable='rgbd_odometry',
36
+ name='rgbd_odometry',
37
+ output='screen',
38
+ parameters=[{
39
+ 'frame_id': 'base_footprint',
40
+ 'odom_frame_id': 'odom',
41
+ 'publish_tf': False,
42
+ 'subscribe_rgbd': True,
43
+ 'queue_size': 10,
44
+ 'wait_for_transform': 0.2,
45
+ # 'wait_imu_to_init': True,
46
+ **use_sim_time,
47
+ 'Vis/FeatureType': '2',
48
+ 'Vis/RoiRatios': '0.0, 0.0, 0.0, 0.05',
49
+ 'Odom/ResetCountdown': '1', # Automatically reset odom when lost (prevents total freeze)
50
+ 'Odom/Strategy': '0', # 0=Frame-to-Map (more stable), 1=Frame-to-Frame
51
+ 'Vis/MinInliers': '10', # Minimum features to accept a transformation
52
+ 'Vis/MaxFeatures': '1000', # Increase the search space for features
53
+ }],
54
+ remappings=[
55
+ ('rgbd_image', '/camera_front/rgbd_image'),
56
+ ('odom', '/rtabmap_odom')
57
+ ]
58
+ )
59
+
60
+ # 3. Nó Principal do RTAB-Map (SLAM)
61
+ rtabmap_node = Node(
62
+ package='rtabmap_slam',
63
+ executable='rtabmap',
64
+ name='rtabmap',
65
+ output='screen',
66
+ parameters=[{
67
+ 'subscribe_rgbd': True,
68
+ 'subscribe_depth': False,
69
+ 'subscribe_rgb': False,
70
+ 'frame_id': 'base_footprint',
71
+ 'map_frame_id': 'map',
72
+ 'publish_tf': False, # RTAB-Map publishes map -> odom
73
+ 'odom_frame_id': 'odom',
74
+ 'Reg/Strategy': '0', # 0=Visual, 1=ICP, 2=Visual+ICP
75
+ 'RGBD/ProximityBySpace': 'true',
76
+ 'queue_size': 10,
77
+ **use_sim_time,
78
+ 'Grid/FromDepth': 'true',
79
+ 'Vis/RoiRatios': '0.0, 0.0, 0.0, 0.2',
80
+ 'Grid/DepthRoiRatios': '0.0, 0.0, 0.0, 0.2',
81
+ }],
82
+ remappings=[
83
+ ('rgbd_image', '/camera_front/rgbd_image'),
84
+ ('odom', '/rtabmap_odom'),
85
+ ],
86
+ arguments=['--delete_db_on_start']
87
+ )
88
+
89
+ # 4. Visualização Opcional (RTAB-Map Viz)
90
+ rtabmap_viz = Node(
91
+ package='rtabmap_viz',
92
+ executable='rtabmap_viz',
93
+ name='rtabmap_viz',
94
+ parameters=[{
95
+ 'subscribe_rgbd': True,
96
+ 'frame_id': 'base_footprint',
97
+ **use_sim_time
98
+ }],
99
+ remappings=[
100
+ ('rgbd_image', '/camera_front/rgbd_image')
101
+ ],
102
+ output='screen'
103
+ )
104
+
105
+ return LaunchDescription([
106
+ sync_node,
107
+ odom_node,
108
+ rtabmap_node,
109
+ # rtabmap_viz
110
+ ])
experiments/rtabmap/scripts/follow_route.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import rclpy
2
+ from rclpy.node import Node
3
+ from NAME_OF_YOUR_PKG.navigator import Navigator, TaskResult
4
+ from geometry_msgs.msg import PoseStamped
5
+ from visualization_msgs.msg import Marker, MarkerArray
6
+ from rclpy.qos import QoSProfile, DurabilityPolicy
7
+ import yaml
8
+ import math
9
+ import time
10
+ from ament_index_python.packages import get_package_share_directory
11
+ import os
12
+
13
+ def euler_to_quaternion(yaw, pitch, roll):
14
+ """Converte ângulos Euler para quaternião."""
15
+ cy = math.cos(yaw * 0.5)
16
+ sy = math.sin(yaw * 0.5)
17
+ cp = math.cos(pitch * 0.5)
18
+ sp = math.sin(pitch * 0.5)
19
+ cr = math.cos(roll * 0.5)
20
+ sr = math.sin(roll * 0.5)
21
+
22
+ q = [0.0] * 4
23
+ q[0] = cy * cp * sr - sy * sp * cr # x
24
+ q[1] = sy * cp * sr + cy * sp * cr # y
25
+ q[2] = sy * cp * cr - cy * sp * sr # z
26
+ q[3] = cy * cp * cr + sy * sp * sr # w
27
+ return q
28
+
29
+ class WaypointFollower(Node):
30
+ """
31
+ Nó para carregar uma rota de um arquivo YAML e usar o ScoutNavigator para executá-la.
32
+ """
33
+ def __init__(self):
34
+ super().__init__('waypoint_follower')
35
+ self.navigator = ScoutNavigator()
36
+
37
+ # Define o perfil de QoS para "latched"
38
+ qos_profile = QoSProfile(
39
+ depth=1,
40
+ durability=DurabilityPolicy.TRANSIENT_LOCAL)
41
+
42
+ # Publisher para os marcadores dos waypoints
43
+ self.marker_publisher = self.create_publisher(MarkerArray, 'waypoints', qos_profile)
44
+
45
+ # Ativa os nós do Nav2 usando o método simplificado do ScoutNavigator
46
+ self.navigator.startup()
47
+
48
+ # Pequena pausa para garantir que os tópicos estejam prontos após a ativação
49
+ self.get_logger().info('Aguardando 2 segundos para a inicialização dos tópicos...')
50
+ time.sleep(2)
51
+
52
+ self.get_logger().info('ScoutNavigator está pronto para uso.')
53
+
54
+ def publish_waypoint_markers(self, waypoints):
55
+ """
56
+ Publica os waypoints como uma MarkerArray para visualização no RViz.
57
+ """
58
+ marker_array = MarkerArray()
59
+ for i, waypoint in enumerate(waypoints):
60
+ marker = Marker()
61
+ marker.header.frame_id = 'map'
62
+ marker.header.stamp = self.get_clock().now().to_msg()
63
+ marker.ns = "waypoints"
64
+ marker.id = i
65
+ marker.type = Marker.ARROW
66
+ marker.action = Marker.ADD
67
+ marker.pose = waypoint.pose
68
+ marker.scale.x = 0.5 # Comprimento da seta
69
+ marker.scale.y = 0.1 # Largura da seta
70
+ marker.scale.z = 0.1 # Altura da seta
71
+ marker.color.a = 1.0 # Alpha
72
+ marker.color.r = 0.0 # Red
73
+ marker.color.g = 1.0 # Green
74
+ marker.color.b = 0.0 # Blue
75
+ marker_array.markers.append(marker)
76
+
77
+ self.get_logger().info(f'Publicando {len(waypoints)} marcadores de waypoint.')
78
+ self.marker_publisher.publish(marker_array)
79
+
80
+ def follow_route_from_yaml(self, yaml_path):
81
+ """
82
+ Carrega waypoints de um arquivo YAML e os envia para o Nav2.
83
+ """
84
+ self.get_logger().info(f"Carregando rota do arquivo: {yaml_path}")
85
+
86
+ try:
87
+ with open(yaml_path, 'r') as file:
88
+ route_data = yaml.safe_load(file)
89
+ except (IOError, yaml.YAMLError) as e:
90
+ self.get_logger().error(f"Erro ao ler ou processar o arquivo YAML: {e}")
91
+ return
92
+
93
+ if not route_data or 'waypoints' not in route_data:
94
+ self.get_logger().error("Arquivo YAML não contém a chave 'waypoints' ou está vazio.")
95
+ return
96
+
97
+ waypoints = []
98
+ for wp_data in route_data['waypoints']:
99
+ pose_data = wp_data.get('pose', {})
100
+ position = pose_data.get('position', {})
101
+ orientation = pose_data.get('orientation', {})
102
+
103
+ waypoint = PoseStamped()
104
+ waypoint.header.frame_id = 'map'
105
+ waypoint.header.stamp = self.get_clock().now().to_msg()
106
+
107
+ waypoint.pose.position.x = float(position.get('x', 0.0))
108
+ waypoint.pose.position.y = float(position.get('y', 0.0))
109
+
110
+ if 'theta' in orientation:
111
+ q = euler_to_quaternion(orientation['theta'], 0, 0)
112
+ waypoint.pose.orientation.x = q[0]
113
+ waypoint.pose.orientation.y = q[1]
114
+ waypoint.pose.orientation.z = q[2]
115
+ waypoint.pose.orientation.w = q[3]
116
+ else:
117
+ waypoint.pose.orientation.x = float(orientation.get('x', 0.0))
118
+ waypoint.pose.orientation.y = float(orientation.get('y', 0.0))
119
+ waypoint.pose.orientation.z = float(orientation.get('z', 0.0))
120
+ waypoint.pose.orientation.w = float(orientation.get('w', 1.0))
121
+
122
+ waypoints.append(waypoint)
123
+
124
+ if not waypoints:
125
+ self.get_logger().info("Nenhum waypoint encontrado para seguir.")
126
+ return
127
+
128
+ # Publica os marcadores dos waypoints
129
+ self.publish_waypoint_markers(waypoints)
130
+
131
+ self.get_logger().info(f"Enviando {len(waypoints)} waypoints para o Nav2.")
132
+ self.navigator.goThroughPoses(waypoints)
133
+
134
+ # Verifica o status da tarefa
135
+ while not self.navigator.isTaskComplete():
136
+ feedback = self.navigator.getFeedback()
137
+ if feedback:
138
+ self.get_logger().info(f'Poses restantes: {feedback.number_of_poses_remaining}')
139
+ time.sleep(1)
140
+
141
+ result = self.navigator.getResult()
142
+ if result == TaskResult.SUCCEEDED:
143
+ self.get_logger().info("Rota concluída com sucesso!")
144
+ elif result == TaskResult.CANCELED:
145
+ self.get_logger().warn("A rota foi cancelada.")
146
+ elif result == TaskResult.FAILED:
147
+ self.get_logger().error("A rota falhou.")
148
+ else:
149
+ self.get_logger().error("Resultado da rota desconhecido!")
150
+
151
+ def main(args=None):
152
+ rclpy.init(args=args)
153
+
154
+ share_dir = get_package_share_directory('NAME_OF_YOUR_PKG')
155
+ route_yaml_path = os.path.join(share_dir, 'params', 'route.yaml')
156
+
157
+ waypoint_follower = WaypointFollower()
158
+ waypoint_follower.follow_route_from_yaml(route_yaml_path)
159
+
160
+ rclpy.shutdown()
161
+
162
+ if __name__ == '__main__':
163
+ main()
experiments/rtabmap/scripts/generate_route.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import yaml
3
+ import argparse
4
+ import numpy as np
5
+
6
+ def calculate_orientations(points):
7
+ """Calculate orientations for a list of points."""
8
+
9
+ # Remove consecutive duplicate points
10
+ unique_points = [points[0]] if points else []
11
+ for p in points[1:]:
12
+ # Use a tolerance for float comparison
13
+ if not np.allclose(p, unique_points[-1]):
14
+ unique_points.append(p)
15
+ points = unique_points
16
+
17
+ waypoints = []
18
+ thetas = []
19
+ for i in range(len(points) - 1):
20
+ p1 = points[i]
21
+ p2 = points[i+1]
22
+ thetas.append(np.arctan2(p2[1] - p1[1], p2[0] - p1[0]))
23
+ if len(points) > 1:
24
+ thetas.append(thetas[-1]) # Last point orientation
25
+ elif len(points) == 1:
26
+ thetas.append(0)
27
+
28
+ for i in range(len(points)):
29
+ waypoints.append({'pose': {'position': {'x': float(points[i][0]), 'y': float(points[i][1])}, 'orientation': {'theta': float(thetas[i])}}})
30
+ return waypoints
31
+
32
+ def generate_square_route(size=5, step=1):
33
+ """Generate a square route."""
34
+ points = []
35
+ # side 1: from (0,0) to (size,0)
36
+ points.extend([(x, 0.0) for x in np.arange(0, size, step)])
37
+ # side 2: from (size,0) to (size,size)
38
+ points.extend([(size, y) for y in np.arange(0, size, step)])
39
+ # side 3: from (size,size) to (0,size)
40
+ points.extend([(x, size) for x in np.arange(size, 0, -step)])
41
+ # side 4: from (0,size) to (0,0)
42
+ points.extend([(0.0, y) for y in np.arange(size, 0, -step)])
43
+
44
+ # Close the loop
45
+ points.append(points[0])
46
+
47
+ return calculate_orientations(points)
48
+
49
+ def generate_u_route(width=5, length=10, step=1, num_points=20):
50
+ """Generate a U-shaped route with a smooth curve, starting in the X direction."""
51
+ points = []
52
+ # Leg 1: along X axis
53
+ for x in np.arange(0, length, step):
54
+ points.append((x, 0.0))
55
+
56
+ # Smooth curve (half-circle)
57
+ radius = width / 2.0
58
+ center_x = length
59
+ center_y = radius
60
+ for i in range(num_points + 1):
61
+ angle = -np.pi/2 + np.pi * i / num_points # angle from -pi/2 to pi/2
62
+ x = center_x + radius * np.cos(angle)
63
+ y = center_y + radius * np.sin(angle)
64
+ points.append((x, y))
65
+
66
+ # Leg 2: along X axis (reversed)
67
+ for x in np.arange(length, 0, -step):
68
+ points.append((x, width))
69
+
70
+ return calculate_orientations(points)
71
+
72
+ def generate_eighth_route(radius=5, num_points=50):
73
+ """Generate a figure-eight route."""
74
+ points = []
75
+ t = np.linspace(0, 2 * np.pi, num_points)
76
+ x = radius * np.sin(t)
77
+ y = radius * np.sin(t) * np.cos(t)
78
+ for i in range(len(x)):
79
+ points.append((x[i], y[i]))
80
+ return calculate_orientations(points)
81
+
82
+ def generate_sinusoidal_route(length=20, amplitude=5, num_points=50):
83
+ """Generate a sinusoidal route."""
84
+ points = []
85
+ x = np.linspace(0, length, num_points)
86
+ y = amplitude * np.sin(x)
87
+ for i in range(len(x)):
88
+ points.append((x[i], y[i]))
89
+ return calculate_orientations(points)
90
+
91
+ def main():
92
+ parser = argparse.ArgumentParser(description="Generate a route for robot navigation.")
93
+ parser.add_argument('shape', choices=['square', 'u', 'eighth', 'sinusoidal'], help="The shape of the route to generate.")
94
+ parser.add_argument('-o', '--output', default='params/new_route.yaml', help="The output file name.")
95
+ parser.add_argument('--size', type=float, default=5, help="Size parameter for the shape (e.g., side length for square).")
96
+ parser.add_argument('--step', type=float, default=1, help="Step size for generating points.")
97
+ parser.add_argument('--width', type=float, default=5, help="Width for U-shape.")
98
+ parser.add_argument('--length', type=float, default=10, help="Length for U-shape or sinusoidal.")
99
+ parser.add_argument('--amplitude', type=float, default=5, help="Amplitude for sinusoidal.")
100
+ parser.add_argument('--radius', type=float, default=5, help="Radius for figure-eight.")
101
+ parser.add_argument('--num_points', type=int, default=50, help="Number of points for curves.")
102
+
103
+ args = parser.parse_args()
104
+
105
+ waypoints = []
106
+ if args.shape == 'square':
107
+ waypoints = generate_square_route(args.size, args.step)
108
+ elif args.shape == 'u':
109
+ waypoints = generate_u_route(args.width, args.length, args.step, args.num_points)
110
+ elif args.shape == 'eighth':
111
+ waypoints = generate_eighth_route(args.radius, args.num_points)
112
+ elif args.shape == 'sinusoidal':
113
+ waypoints = generate_sinusoidal_route(args.length, args.amplitude, args.num_points)
114
+
115
+ with open(args.output, 'w') as f:
116
+ yaml.dump({'waypoints': waypoints}, f, default_flow_style=False)
117
+
118
+ print(f"Generated {args.shape} route with {len(waypoints)} waypoints in {args.output}")
119
+
120
+ if __name__ == '__main__':
121
+ main()
experiments/rtabmap/scripts/navigator.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from enum import Enum
3
+
4
+ from action_msgs.msg import GoalStatus
5
+ from geometry_msgs.msg import PoseStamped
6
+ from nav2_msgs.action import NavigateThroughPoses
7
+ from nav2_msgs.srv import ManageLifecycleNodes
8
+
9
+ import rclpy
10
+ from rclpy.action import ActionClient
11
+ from rclpy.node import Node
12
+
13
+
14
+ class TaskResult(Enum):
15
+ """Enum for task result."""
16
+ UNKNOWN = 0
17
+ SUCCEEDED = 1
18
+ CANCELED = 2
19
+ FAILED = 3
20
+
21
+
22
+ class Navigator(Node):
23
+ """
24
+ Um navegador simplificado para enviar uma lista de poses para o Nav2.
25
+ Focado para setups sem mapa e sem AMCL.
26
+ """
27
+
28
+ def __init__(self, node_name='navigator', namespace=''):
29
+ super().__init__(node_name=node_name, namespace=namespace)
30
+ self.goal_handle = None
31
+ self.result_future = None
32
+ self.feedback = None
33
+ self.status = None
34
+
35
+ # Clientes essenciais
36
+ self.nav_through_poses_client = ActionClient(
37
+ self, NavigateThroughPoses, 'navigate_through_poses')
38
+ self.lifecycle_manager_client = self.create_client(
39
+ ManageLifecycleNodes, 'lifecycle_manager_navigation/manage_nodes')
40
+
41
+ def destroy_node(self):
42
+ self.info('Destruindo o Navigator.')
43
+ self.nav_through_poses_client.destroy()
44
+ self.lifecycle_manager_client.destroy()
45
+ super().destroy_node()
46
+
47
+ def startup(self):
48
+ """
49
+ Ativa os nós de ciclo de vida do Nav2 enviando um único comando
50
+ para o gerenciador de ciclo de vida.
51
+ """
52
+ self.info('Enviando comando STARTUP para o lifecycle_manager_navigation...')
53
+
54
+ while not self.lifecycle_manager_client.wait_for_service(timeout_sec=1.0):
55
+ self.info('Serviço do lifecycle_manager_navigation não disponível, aguardando...')
56
+
57
+ req = ManageLifecycleNodes.Request()
58
+ req.command = ManageLifecycleNodes.Request.STARTUP
59
+
60
+ future = self.lifecycle_manager_client.call_async(req)
61
+ rclpy.spin_until_future_complete(self, future)
62
+
63
+ if future.result() and future.result().success:
64
+ self.info('Nós do Nav2 ativados com sucesso.')
65
+ else:
66
+ self.error('Falha ao ativar os nós do Nav2.')
67
+ return
68
+
69
+ def goThroughPoses(self, poses, behavior_tree=''):
70
+ """
71
+ Envia uma lista de poses para o Nav2 seguir.
72
+ """
73
+ self.info("Aguardando o servidor de ação 'navigate_through_poses'...")
74
+ while not self.nav_through_poses_client.wait_for_server(timeout_sec=1.0):
75
+ self.info("'navigate_through_poses' não disponível, aguardando...")
76
+
77
+ goal_msg = NavigateThroughPoses.Goal()
78
+ goal_msg.poses = poses
79
+ goal_msg.behavior_tree = behavior_tree
80
+
81
+ self.info(f'Enviando {len(goal_msg.poses)} waypoints para o Nav2...')
82
+ send_goal_future = self.nav_through_poses_client.send_goal_async(
83
+ goal_msg, self._feedbackCallback)
84
+
85
+ rclpy.spin_until_future_complete(self, send_goal_future)
86
+ self.goal_handle = send_goal_future.result()
87
+
88
+ if not self.goal_handle.accepted:
89
+ self.error('O objetivo de seguir os waypoints foi rejeitado!')
90
+ return False
91
+
92
+ self.result_future = self.goal_handle.get_result_async()
93
+ self.info('Objetivo aceito, iniciando a navegação...')
94
+ return True
95
+
96
+ def cancelTask(self):
97
+ """Cancela a tarefa atual."""
98
+ self.info('Cancelando a tarefa atual.')
99
+ if self.result_future:
100
+ future = self.goal_handle.cancel_goal_async()
101
+ rclpy.spin_until_future_complete(self, future)
102
+ return
103
+
104
+ def isTaskComplete(self):
105
+ """Verifica se a tarefa foi concluída."""
106
+ if not self.result_future:
107
+ return True
108
+
109
+ rclpy.spin_until_future_complete(self, self.result_future, timeout_sec=0.10)
110
+
111
+ if self.result_future.result():
112
+ self.status = self.result_future.result().status
113
+ if self.status != GoalStatus.STATUS_SUCCEEDED:
114
+ return True
115
+ else:
116
+ return False
117
+
118
+ return True
119
+
120
+ def getFeedback(self):
121
+ """Retorna o feedback da ação atual."""
122
+ return self.feedback
123
+
124
+ def getResult(self):
125
+ """Retorna o resultado final da tarefa."""
126
+ if self.status == GoalStatus.STATUS_SUCCEEDED:
127
+ return TaskResult.SUCCEEDED
128
+ elif self.status == GoalStatus.STATUS_ABORTED:
129
+ return TaskResult.FAILED
130
+ elif self.status == GoalStatus.STATUS_CANCELED:
131
+ return TaskResult.CANCELED
132
+ else:
133
+ return TaskResult.UNKNOWN
134
+
135
+ def _feedbackCallback(self, msg):
136
+ self.feedback = msg.feedback
137
+ return
138
+
139
+ # Funções de logging
140
+ def info(self, msg):
141
+ self.get_logger().info(msg)
142
+
143
+ def warn(self, msg):
144
+ self.get_logger().warn(msg)
145
+
146
+ def error(self, msg):
147
+ self.get_logger().error(msg)
148
+
149
+ def debug(self, msg):
150
+ self.get_logger().debug(msg)
experiments/semantic_segmentation/inference_2d_semantic.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for 2D Semantic Segmentation using the trained U-Net model.
3
+ This script loads RGB images, performs inference, and visualizes the predictions
4
+ in a compact grid format optimized for scientific papers.
5
+ """
6
+ import os
7
+ import torch
8
+ import torch.nn as nn
9
+ import torchvision.transforms.functional as TF
10
+ import numpy as np
11
+ import cv2
12
+ import segmentation_models_pytorch as smp
13
+ import matplotlib.pyplot as plt
14
+
15
+ # --- CONFIGURATION ---
16
+ CONFIG = {
17
+ 'num_classes': 5, # Must match training configuration
18
+ 'class_names': {0: "ground", 1: "leaf", 2: "branch", 3: "weed", 4: "obstacle"},
19
+ 'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
20
+ 'model_path': 'unet_efficientnetb3_semantic.pth',
21
+ 'input_image_path': 'rosario/',
22
+ 'output_image_path': 'semantic_results/',
23
+ 'inference_size': (480, 640),
24
+ }
25
+
26
+ # --- IMAGE LOADING AND PREPROCESSING ---
27
+ def load_and_preprocess_image(image_path, device):
28
+ if not os.path.exists(image_path):
29
+ raise FileNotFoundError(f"Input image not found at: {image_path}")
30
+
31
+ rgb_img = cv2.imread(image_path)
32
+ if rgb_img is None:
33
+ raise IOError(f"Could not read image at: {image_path}")
34
+
35
+ rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)
36
+
37
+ h, w = CONFIG['inference_size']
38
+ original_img_for_viz = rgb_img.copy()
39
+ rgb_img = cv2.resize(rgb_img, (w, h), interpolation=cv2.INTER_AREA)
40
+
41
+ rgb_tensor = TF.to_tensor(rgb_img)
42
+ rgb_tensor = rgb_tensor.unsqueeze(0).to(device)
43
+
44
+ return rgb_tensor, original_img_for_viz
45
+
46
+ # --- MAIN INFERENCE FUNCTION ---
47
+ def main():
48
+ print(f"Using device: {CONFIG['device']}")
49
+
50
+ # --- 1. Load Model ---
51
+ print("Loading U-Net model with EfficientNet-B3 encoder...")
52
+ model = smp.Unet(
53
+ encoder_name="efficientnet-b3",
54
+ encoder_weights=None,
55
+ in_channels=3,
56
+ classes=CONFIG['num_classes'],
57
+ )
58
+ model = model.to(CONFIG['device'])
59
+
60
+ if not os.path.exists(CONFIG['model_path']):
61
+ raise FileNotFoundError(f"Trained model weights not found at: {CONFIG['model_path']}")
62
+
63
+ model.load_state_dict(torch.load(CONFIG['model_path'], map_location=CONFIG['device']))
64
+ model.eval()
65
+ print(f"Model weights loaded from {CONFIG['model_path']}")
66
+
67
+ # --- 2. Gather Images ---
68
+ # Coleta e ordena as imagens para garantir consistência
69
+ image_files = sorted([f for f in os.listdir(CONFIG['input_image_path'])
70
+ if f.endswith(('.jpg', '.png'))])
71
+
72
+ # Limita a 6 imagens como solicitado
73
+ image_files = image_files[:6]
74
+ num_images = len(image_files)
75
+
76
+ if num_images == 0:
77
+ print("Nenhuma imagem encontrada no diretório.")
78
+ return
79
+
80
+ # Listas para armazenar os pares de resultados
81
+ results_rgb = []
82
+ results_mask = []
83
+
84
+ # --- 3. Perform Inference on All Images ---
85
+ for image in image_files:
86
+ img_path = os.path.join(CONFIG['input_image_path'], image)
87
+ print(f"Processing: {image}...")
88
+
89
+ input_tensor, original_rgb_img = load_and_preprocess_image(img_path, CONFIG['device'])
90
+
91
+ with torch.no_grad():
92
+ output = model(input_tensor)
93
+
94
+ pred_mask = torch.argmax(output, dim=1).squeeze(0).cpu().numpy()
95
+
96
+ orig_h, orig_w, _ = original_rgb_img.shape
97
+ pred_mask = cv2.resize(pred_mask.astype(np.uint8), (orig_w, orig_h), interpolation=cv2.INTER_NEAREST)
98
+
99
+ results_rgb.append(original_rgb_img)
100
+ results_mask.append(pred_mask)
101
+
102
+ # --- 4. Visualize and Save Full Grid for Paper ---
103
+ print("Generating paper-ready figure...")
104
+
105
+ # Define a figura: 2 linhas, N colunas. figsize ajustável dependendo da proporção da imagem
106
+ # wspace e hspace em 0.02 garantem que quase não haja espaço perdido entre as imagens
107
+ fig, axes = plt.subplots(2, num_images, figsize=(2.5 * num_images, 4.5), dpi=300,
108
+ gridspec_kw={'wspace': 0.02, 'hspace': 0.02})
109
+
110
+ cmap = plt.get_cmap('tab10', CONFIG['num_classes'])
111
+
112
+ for i in range(num_images):
113
+ # Linha 0: Imagens RGB de Entrada
114
+ axes[0, i].imshow(results_rgb[i])
115
+ axes[0, i].axis('off') # Remove eixos para economizar espaço
116
+
117
+ # Linha 1: Máscaras Preditas
118
+ im = axes[1, i].imshow(results_mask[i], cmap=cmap, vmin=0, vmax=CONFIG['num_classes']-1)
119
+ axes[1, i].axis('off')
120
+
121
+ # Ajusta o layout principal e adiciona a barra de cores (Colorbar)
122
+ # A barra é posicionada na parte inferior (horizontal) para não gastar espaço lateral valioso do artigo
123
+ plt.subplots_adjust(bottom=0.15)
124
+ cbar_ax = fig.add_axes([0.15, 0.05, 0.7, 0.03]) # [left, bottom, width, height]
125
+
126
+ cbar = fig.colorbar(im, cax=cbar_ax, orientation='horizontal', ticks=np.arange(CONFIG['num_classes']))
127
+
128
+ # Configura os nomes das classes na barra de cores
129
+ class_labels = [CONFIG['class_names'][i] for i in range(CONFIG['num_classes'])]
130
+ cbar.ax.set_xticklabels(class_labels, fontsize=10)
131
+ cbar.outline.set_visible(False) # Deixa a barra mais "limpa" visualmente
132
+
133
+ # Cria diretório se não existir e salva
134
+ os.makedirs(CONFIG['output_image_path'], exist_ok=True)
135
+ final_output_path = os.path.join(CONFIG['output_image_path'], "paper_figure_semantic_grid.png")
136
+
137
+ # bbox_inches='tight' arranca margens em branco excedentes
138
+ # pad_inches controla o "respiro" nas bordas da imagem final
139
+ plt.savefig(final_output_path, dpi=300, bbox_inches='tight', pad_inches=0.01)
140
+ print(f"Final figure saved successfully at: {final_output_path}")
141
+
142
+ if __name__ == '__main__':
143
+ main()
experiments/semantic_segmentation/rosario/01.jpg ADDED

Git LFS Details

  • SHA256: 3a1f5bbc2cb49284e63c33cd6618e84b82282fce6fa94de1adcf42c9f19e6838
  • Pointer size: 131 Bytes
  • Size of remote file: 177 kB
experiments/semantic_segmentation/rosario/02.jpg ADDED

Git LFS Details

  • SHA256: 2c4e30ee6c5ba88e45cd7507fd1c108b2b2a341cc7c742e815067bcb7783d354
  • Pointer size: 131 Bytes
  • Size of remote file: 172 kB
experiments/semantic_segmentation/rosario/03.jpg ADDED

Git LFS Details

  • SHA256: a0752718e0bedc1639fa9f5932c3fcdcef526dfbbda12d138043a8fdd6e92816
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
experiments/semantic_segmentation/rosario/04.jpg ADDED

Git LFS Details

  • SHA256: 610a636f55b425c754b231dec60905ec60235e44c4ab380fedbb65ec3a1f3d1d
  • Pointer size: 131 Bytes
  • Size of remote file: 116 kB
experiments/semantic_segmentation/rosario/05.jpg ADDED

Git LFS Details

  • SHA256: 0f28ebc380fe33bffea9c4dfbfbc5d9f1479b8ce8766f72e7a08eaf4388120ad
  • Pointer size: 131 Bytes
  • Size of remote file: 149 kB
experiments/semantic_segmentation/rosario/06.jpg ADDED

Git LFS Details

  • SHA256: 73ea4b3736fa2e61cac3a4405048616130e254f58f5807e80d6129b0de4f881c
  • Pointer size: 131 Bytes
  • Size of remote file: 168 kB
experiments/semantic_segmentation/train_2d_semantic.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for 2D Semantic Segmentation using only RGB and Semantic masks.
3
+ This script uses a pre-trained DeepLabV3 model for a more direct 2D approach.
4
+ """
5
+ import os
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.utils.data import Dataset, DataLoader
9
+ import torchvision.transforms as T
10
+ import torchvision.transforms.functional as TF
11
+ import numpy as np
12
+ import cv2
13
+ import glob
14
+ import segmentation_models_pytorch as smp
15
+ from tqdm import tqdm
16
+ import matplotlib.pyplot as plt
17
+
18
+ # --- CONFIGURATION ---
19
+ CONFIG = {
20
+ 'data_dir': 'data/dataset/soybean',
21
+ 'num_classes': 5, # ground, leaf, branch, weed, obstacle
22
+ 'class_names': {0: "ground", 1: "leaf", 2: "branch", 3: "weed", 4: "obstacle"},
23
+ 'batch_size': 4,
24
+ 'epochs': 50,
25
+ 'learning_rate': 1e-4,
26
+ 'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
27
+ 'ignore_index': -1, # Value in the semantic mask to be ignored during loss calculation
28
+ 'data_augmentation': True, # Enable/disable data augmentation
29
+ 'model_save_path': 'unet_efficientnetb3_semantic.pth',
30
+ }
31
+
32
+ # --- DATASET ---
33
+ class ImageSemanticDataset(Dataset):
34
+ """
35
+ A simplified dataset that loads only RGB images and their corresponding
36
+ 2D semantic segmentation masks.
37
+ """
38
+ def __init__(self, root_dir, num_classes=5, transform=None, data_augmentation=False):
39
+ self.root_dir = root_dir
40
+ self.transform = transform
41
+ self.num_classes = num_classes
42
+ self.data_augmentation = data_augmentation
43
+ self.rgb_files = sorted(glob.glob(os.path.join(root_dir, 'rgb', '*.png')))
44
+ if not self.rgb_files:
45
+ self.rgb_files = sorted(glob.glob(os.path.join(root_dir, 'rgb', '*.jpg')))
46
+
47
+ if not self.rgb_files:
48
+ raise ValueError(f"No images found in {os.path.join(root_dir, 'rgb')}")
49
+
50
+ def __len__(self):
51
+ return len(self.rgb_files)
52
+
53
+ def __getitem__(self, idx):
54
+ rgb_path = self.rgb_files[idx]
55
+ base_name = os.path.splitext(os.path.basename(rgb_path))[0]
56
+
57
+ # Construct path to semantic mask
58
+ # The folder name in the original dataset is 'camera_semantic'
59
+ semantic_path = os.path.join(self.root_dir, 'camera_semantic', f"{base_name}.png")
60
+
61
+ # Load RGB Image
62
+ rgb_img = cv2.imread(rgb_path)
63
+ rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)
64
+ rgb_tensor = TF.to_tensor(rgb_img)
65
+
66
+ # Load Semantic Mask
67
+ semantic_mask = cv2.imread(semantic_path, cv2.IMREAD_UNCHANGED)
68
+ if semantic_mask is None:
69
+ raise FileNotFoundError(f"Semantic mask not found: {semantic_path}")
70
+
71
+ # Ensure mask is single channel
72
+ if semantic_mask.ndim == 3:
73
+ semantic_mask = semantic_mask[:, :, 0]
74
+
75
+ semantic_tensor = torch.from_numpy(semantic_mask.astype(np.int64))
76
+
77
+ # Apply transformations if any
78
+ if self.transform:
79
+ rgb_tensor, semantic_tensor = self.transform(rgb_tensor, semantic_tensor)
80
+
81
+ # Apply data augmentation if enabled
82
+ if self.data_augmentation:
83
+ # Random horizontal flip
84
+ if torch.rand(1) > 0.5:
85
+ rgb_tensor = TF.hflip(rgb_tensor)
86
+ semantic_tensor = TF.hflip(semantic_tensor)
87
+
88
+ # Color Jitter (only on RGB)
89
+ if torch.rand(1) > 0.5:
90
+ color_jitter = T.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.1)
91
+ rgb_tensor = color_jitter(rgb_tensor)
92
+
93
+ # Noise
94
+ if torch.rand(1) > 0.5:
95
+ noise = torch.randn_like(rgb_tensor) * 0.1
96
+ rgb_tensor = torch.clamp(rgb_tensor + noise, 0, 1)
97
+
98
+ # Blur
99
+ if torch.rand(1) > 0.5:
100
+ rgb_tensor = TF.gaussian_blur(rgb_tensor, kernel_size=5, sigma=(0.1, 2.0))
101
+
102
+
103
+
104
+ return {'rgb': rgb_tensor, 'semantic': semantic_tensor, 'frame_id': base_name}
105
+
106
+ # --- METRICS ---
107
+ def compute_metrics(pred, target, num_classes):
108
+ """Computes Pixel Accuracy and Mean IoU, ignoring -1 labels."""
109
+ pred = pred.cpu().numpy()
110
+ target = target.cpu().numpy()
111
+
112
+ # Create a mask to ignore pixels with the ignore_index value
113
+ valid_mask = (target != CONFIG['ignore_index'])
114
+
115
+ # Pixel Accuracy
116
+ correct = np.sum((pred == target) & valid_mask)
117
+ total = np.sum(valid_mask)
118
+ pixel_acc = correct / total
119
+
120
+ # Mean IoU
121
+ iou_list = []
122
+ for c in range(num_classes):
123
+ tp = np.sum((pred == c) & (target == c))
124
+ fp = np.sum((pred == c) & (target != c))
125
+ fn = np.sum((pred != c) & (target == c) & valid_mask) # Only count valid target pixels as false negatives
126
+
127
+ union = tp + fp + fn
128
+ if union == 0:
129
+ iou = 0.0 # Or float('nan')
130
+ else:
131
+ iou = tp / union
132
+ iou_list.append(iou)
133
+
134
+ miou = np.nanmean(iou_list)
135
+ return pixel_acc, miou
136
+
137
+ # --- TRAINING AND VALIDATION ---
138
+ def train_one_epoch(model, dataloader, criterion, optimizer, device, num_classes):
139
+ model.train()
140
+ total_loss = 0.0
141
+ total_acc = 0.0
142
+ total_miou = 0.0
143
+
144
+ for batch in tqdm(dataloader, desc="Training"):
145
+ rgb = batch['rgb'].to(device)
146
+ semantic = batch['semantic'].to(device)
147
+
148
+ optimizer.zero_grad()
149
+
150
+ # DeepLabV3 returns a dictionary
151
+ output = model(rgb)
152
+ loss = criterion(output, semantic)
153
+
154
+ loss.backward()
155
+ optimizer.step()
156
+
157
+ total_loss += loss.item()
158
+
159
+ preds = torch.argmax(output, dim=1)
160
+ acc, miou = compute_metrics(preds, semantic, num_classes)
161
+ total_acc += acc
162
+ total_miou += miou
163
+
164
+ return total_loss / len(dataloader), total_acc / len(dataloader), total_miou / len(dataloader)
165
+
166
+ def validate_one_epoch(model, dataloader, criterion, device, num_classes):
167
+ model.eval()
168
+ total_loss = 0.0
169
+ total_acc = 0.0
170
+ total_miou = 0.0
171
+
172
+ with torch.no_grad():
173
+ for batch in tqdm(dataloader, desc="Validating"):
174
+ rgb = batch['rgb'].to(device)
175
+ semantic = batch['semantic'].to(device)
176
+
177
+ output = model(rgb)
178
+ loss = criterion(output, semantic)
179
+
180
+ total_loss += loss.item()
181
+
182
+ preds = torch.argmax(output, dim=1)
183
+ acc, miou = compute_metrics(preds, semantic, num_classes)
184
+ total_acc += acc
185
+ total_miou += miou
186
+
187
+ return total_loss / len(dataloader), total_acc / len(dataloader), total_miou / len(dataloader)
188
+
189
+
190
+ def main():
191
+ print(f"Using device: {CONFIG['device']}")
192
+
193
+ # --- DATA ---
194
+ # Create separate datasets for training and validation
195
+ # Augmentation should only be applied to the training set.
196
+ train_dataset = ImageSemanticDataset(
197
+ CONFIG['data_dir'],
198
+ num_classes=CONFIG['num_classes'],
199
+ data_augmentation=CONFIG['data_augmentation']
200
+ )
201
+ val_dataset = ImageSemanticDataset(
202
+ CONFIG['data_dir'],
203
+ num_classes=CONFIG['num_classes'],
204
+ data_augmentation=False # No augmentation for validation
205
+ )
206
+
207
+ # Create a random split of indices, then create subsets
208
+ indices = torch.randperm(len(train_dataset)).tolist()
209
+ train_indices = indices[:int(0.8 * len(train_dataset))]
210
+ val_indices = indices[int(0.8 * len(train_dataset)):]
211
+
212
+ train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
213
+ val_dataset = torch.utils.data.Subset(val_dataset, val_indices)
214
+
215
+ train_loader = DataLoader(train_dataset, batch_size=CONFIG['batch_size'], shuffle=True, num_workers=2)
216
+ val_loader = DataLoader(val_dataset, batch_size=CONFIG['batch_size'], shuffle=False, num_workers=2)
217
+
218
+ print(f"Training on {len(train_dataset)} samples, validating on {len(val_dataset)} samples.")
219
+
220
+ # --- MODEL ---
221
+ # Load a U-Net model with a pre-trained EfficientNet encoder
222
+ print("Loading U-Net with EfficientNet encoder...")
223
+ model = smp.Unet(
224
+ encoder_name="efficientnet-b3",
225
+ encoder_weights="imagenet",
226
+ in_channels=3,
227
+ classes=CONFIG['num_classes'],
228
+ )
229
+ model = model.to(CONFIG['device'])
230
+
231
+ # --- LOSS & OPTIMIZER ---
232
+ # CrossEntropyLoss is standard for multi-class segmentation
233
+ criterion = nn.CrossEntropyLoss(ignore_index=CONFIG['ignore_index'])
234
+ optimizer = torch.optim.Adam(model.parameters(), lr=CONFIG['learning_rate'])
235
+
236
+ # --- TRAINING LOOP ---
237
+ best_val_miou = 0.0
238
+
239
+ for epoch in range(CONFIG['epochs']):
240
+ print(f"\n--- Epoch {epoch+1}/{CONFIG['epochs']} ---")
241
+
242
+ train_loss, train_acc, train_miou = train_one_epoch(
243
+ model, train_loader, criterion, optimizer, CONFIG['device'], CONFIG['num_classes']
244
+ )
245
+ print(f"Train -> Loss: {train_loss:.4f}, Accuracy: {train_acc:.4f}, mIoU: {train_miou:.4f}")
246
+
247
+ val_loss, val_acc, val_miou = validate_one_epoch(
248
+ model, val_loader, criterion, CONFIG['device'], CONFIG['num_classes']
249
+ )
250
+ print(f"Validation -> Loss: {val_loss:.4f}, Accuracy: {val_acc:.4f}, mIoU: {val_miou:.4f}")
251
+
252
+ # Save the best model based on validation mIoU
253
+ if val_miou > best_val_miou:
254
+ best_val_miou = val_miou
255
+ torch.save(model.state_dict(), CONFIG['model_save_path'])
256
+ print(f"✨ New best model saved to {CONFIG['model_save_path']} (mIoU: {best_val_miou:.4f})")
257
+
258
+ print("\n--- Training Complete ---")
259
+ print(f"Best validation mIoU: {best_val_miou:.4f}")
260
+ print(f"Model saved to {CONFIG['model_save_path']}")
261
+
262
+ # --- VISUALIZE A PREDICTION ---
263
+ model.load_state_dict(torch.load(CONFIG['model_save_path']))
264
+ model.eval()
265
+ sample = val_dataset[np.random.randint(len(val_dataset))]
266
+ rgb_tensor = sample['rgb'].unsqueeze(0).to(CONFIG['device'])
267
+
268
+ with torch.no_grad():
269
+ pred_mask = model(rgb_tensor)
270
+ pred_mask = torch.argmax(pred_mask, dim=1).squeeze(0).cpu().numpy()
271
+
272
+ rgb_img = sample['rgb'].permute(1, 2, 0).numpy()
273
+ true_mask = sample['semantic'].numpy()
274
+
275
+ fig, axes = plt.subplots(1, 3, figsize=(18, 6))
276
+ axes[0].imshow(rgb_img)
277
+ axes[0].set_title("Input RGB")
278
+ axes[0].axis('off')
279
+
280
+ axes[1].imshow(true_mask, cmap='tab10', vmin=0, vmax=CONFIG['num_classes']-1)
281
+ axes[1].set_title("Ground Truth Mask")
282
+ axes[1].axis('off')
283
+
284
+ axes[2].imshow(pred_mask, cmap='tab10', vmin=0, vmax=CONFIG['num_classes']-1)
285
+ axes[2].set_title("Predicted Mask")
286
+ axes[2].axis('off')
287
+
288
+ plt.tight_layout()
289
+ plt.savefig('2d_semantic_prediction_example.png')
290
+ print("\nSaved a sample prediction to '2d_semantic_prediction_example.png'")
291
+
292
+
293
+ if __name__ == '__main__':
294
+ main()
experiments/semantic_segmentation/unet_efficientnetb3_semantic.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84fcd96ca56f1c8c5bd8936529387cf7b28a552820aea95c5ee97b559b4ab66a
3
+ size 53237515