oValach commited on
Commit
d9af556
·
verified ·
1 Parent(s): 0130094

Upload 2 files

Browse files
Files changed (2) hide show
  1. TheDistanceAssessor.py +916 -0
  2. app.py +30 -0
TheDistanceAssessor.py ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import time
4
+ import json
5
+ import torch
6
+ import numpy as np
7
+ from skimage import morphology
8
+ import albumentations as A
9
+ import torch.nn.functional as F
10
+ import torch.nn as nn
11
+ from albumentations.pytorch import ToTensorV2
12
+ import matplotlib.pyplot as plt
13
+ from sklearn.linear_model import LinearRegression
14
+ import matplotlib.path as mplPath
15
+ import matplotlib.patches as patches
16
+ from ultralyticsplus import YOLO
17
+
18
+ def image_morpho(mask_prediction):
19
+ selem2 = morphology.disk(2)
20
+ closed = morphology.closing(mask_prediction, selem2)
21
+
22
+ return closed
23
+
24
+ def get_segformer_img(image_in, input_size=[224,224]):
25
+ transform_img = A.Compose([
26
+ A.Resize(height=input_size[0], width=input_size[1], interpolation=cv2.INTER_NEAREST),
27
+ A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
28
+ ToTensorV2(p=1.0),
29
+ ])
30
+
31
+ image_in = cv2.resize(image_in, (1920, 1080))
32
+
33
+ image_tr = transform_img(image=image_in)['image']
34
+ image_tr = image_tr.unsqueeze(0)
35
+ image_tr = image_tr.cpu()
36
+
37
+ return image_tr, image_in
38
+
39
+ def load_segformer(path_model):
40
+
41
+ model = torch.load(path_model, map_location=torch.device('cpu'))
42
+ model = model.cpu()
43
+ model.eval()
44
+ return model
45
+
46
+ def load_yolo(PATH_model):
47
+ model = YOLO(PATH_model)
48
+
49
+ model.overrides['conf'] = 0.25 # NMS confidence threshold
50
+ model.overrides['iou'] = 0.45 # NMS IoU threshold
51
+ model.overrides['agnostic_nms'] = False # NMS class-agnostic
52
+ model.overrides['max_det'] = 1000 # maximum number of detections per image
53
+ return model
54
+
55
+ def find_extreme_y_values(arr, values=[0, 6]):
56
+ """
57
+ Optimized function to find the lowest and highest y-values (row indices) in a 2D array where 0 or 6 appears.
58
+
59
+ Parameters:
60
+ - arr: The input 2D NumPy array.
61
+ - values: The values to search for (default is [0, 6]).
62
+
63
+ Returns:
64
+ A tuple (lowest_y, highest_y) representing the lowest and highest y-values. If values are not found, returns None.
65
+ """
66
+ mask = np.isin(arr, values)
67
+ rows_with_values = np.any(mask, axis=1)
68
+
69
+ y_indices = np.nonzero(rows_with_values)[0] # Directly finding non-zero (True) indices
70
+
71
+ if y_indices.size == 0:
72
+ return None, None # Early return if values not found
73
+
74
+ return y_indices[0], y_indices[-1]
75
+
76
+ def find_nearest_pairs(arr1, arr2):
77
+ # Convert lists to numpy arrays for vectorized operations
78
+ arr1_np = np.array(arr1)
79
+ arr2_np = np.array(arr2)
80
+
81
+ # Determine which array is shorter
82
+ if len(arr1_np) < len(arr2_np):
83
+ base_array, compare_array = arr1_np, arr2_np
84
+ else:
85
+ base_array, compare_array = arr2_np, arr1_np
86
+
87
+ paired_base = []
88
+ paired_compare = []
89
+
90
+ # Mask to keep track of paired elements
91
+ paired_mask = np.zeros(len(compare_array), dtype=bool)
92
+
93
+ for item in base_array:
94
+ # Calculate distances from the current item to all items in the compare_array
95
+ distances = np.linalg.norm(compare_array - item, axis=1)
96
+ nearest_index = np.argmin(distances)
97
+ paired_base.append(item)
98
+ paired_compare.append(compare_array[nearest_index])
99
+ # Mark the paired element to exclude it from further pairing
100
+ paired_mask[nearest_index] = True
101
+
102
+ # Check if all elements from the compare_array have been paired
103
+ if paired_mask.all():
104
+ break
105
+
106
+ paired_base = np.array(paired_base)
107
+ paired_compare = compare_array[paired_mask]
108
+
109
+ return (paired_base, paired_compare) if len(arr1_np) < len(arr2_np) else (paired_compare, paired_base)
110
+
111
+ def filter_crossings(image, edges_dict):
112
+ filtered_edges = {}
113
+ for key, values in edges_dict.items():
114
+ merged = [values[0]]
115
+ for start, end in values[1:]:
116
+ if start - merged[-1][1] < 50:
117
+
118
+ key_up = max([0, key-10])
119
+ key_down = min([image.shape[0]-1, key+10])
120
+ if key_up == 0:
121
+ key_up = key+20
122
+ if key_down == image.shape[0]-1:
123
+ key_down = key-20
124
+
125
+ edges_to_test_slope1 = robust_edges(image, [key_up], values=[0, 6], min_width=19)
126
+ edges_to_test_slope2 = robust_edges(image, [key_down], values=[0, 6], min_width=19)
127
+
128
+ values1, edges_to_test_slope1 = find_nearest_pairs(values, edges_to_test_slope1)
129
+ values2, edges_to_test_slope2 = find_nearest_pairs(values, edges_to_test_slope2)
130
+
131
+ differences_y = []
132
+ for i, value in enumerate(values1):
133
+ if start in value:
134
+ idx = list(value).index(start)
135
+ try:
136
+ differences_y.append(abs(start-edges_to_test_slope1[i][idx]))
137
+ except:
138
+ pass
139
+ if merged[-1][1] in value:
140
+ idx = list(value).index(merged[-1][1])
141
+ try:
142
+ differences_y.append(abs(merged[-1][1]-edges_to_test_slope1[i][idx]))
143
+ except:
144
+ pass
145
+ for i, value in enumerate(values2):
146
+ if start in value:
147
+ idx = list(value).index(start)
148
+ try:
149
+ differences_y.append(abs(start-edges_to_test_slope2[i][idx]))
150
+ except:
151
+ pass
152
+ if merged[-1][1] in value:
153
+ idx = list(value).index(merged[-1][1])
154
+ try:
155
+ differences_y.append(abs(merged[-1][1]-edges_to_test_slope2[i][idx]))
156
+ except:
157
+ pass
158
+
159
+ if any(element > 30 for element in differences_y):
160
+ merged[-1] = (merged[-1][0], end)
161
+ else:
162
+ merged.append((start, end))
163
+ else:
164
+ merged.append((start, end))
165
+ filtered_edges[key] = merged
166
+
167
+ return filtered_edges
168
+
169
+ def robust_edges(image, y_levels, values=[0, 6], min_width=19):
170
+
171
+ for y in y_levels:
172
+ row = image[y, :]
173
+ mask = np.isin(row, values).astype(int)
174
+ padded_mask = np.pad(mask, (1, 1), 'constant', constant_values=0)
175
+ diff = np.diff(padded_mask)
176
+ starts = np.where(diff == 1)[0]
177
+ ends = np.where(diff == -1)[0] - 1
178
+
179
+ # Filter sequences based on the minimum width criteria
180
+ filtered_edges = [(start, end) for start, end in zip(starts, ends) if end - start + 1 >= min_width]
181
+ filtered_edges = [(start, end) for start, end in filtered_edges if 0 not in (start, end) and 1919 not in (start, end)]
182
+
183
+ return filtered_edges
184
+
185
+ def find_edges(image, y_levels, values=[0, 6], min_width=19):
186
+ """
187
+ Find start and end positions of continuous sequences of specified values at given y-levels in a 2D array,
188
+ filtering for sequences that meet or exceed a specified minimum width.
189
+
190
+ Parameters:
191
+ - arr: 2D NumPy array to search within.
192
+ - y_levels: List of y-levels (row indices) to examine.
193
+ - values: Values to search for (default is [0, 6]).
194
+ - min_width: Minimum width of sequences to be included in the results.
195
+
196
+ Returns:
197
+ A dict with y-levels as keys and lists of (start, end) tuples for each sequence found in that row that meets the width criteria.
198
+ """
199
+ edges_dict = {}
200
+ for y in y_levels:
201
+ row = image[y, :]
202
+ mask = np.isin(row, values).astype(int)
203
+ padded_mask = np.pad(mask, (1, 1), 'constant', constant_values=0)
204
+ diff = np.diff(padded_mask)
205
+ starts = np.where(diff == 1)[0]
206
+ ends = np.where(diff == -1)[0] - 1
207
+
208
+ # Filter sequences based on the minimum width criteria
209
+ filtered_edges = [(start, end) for start, end in zip(starts, ends) if end - start + 1 >= min_width]
210
+ filtered_edges = [(start, end) for start, end in filtered_edges if 0 not in (start, end) and 1919 not in (start, end)]
211
+
212
+ edges_with_guard_rails = []
213
+ for edge in filtered_edges:
214
+ cutout_left = image[y,edge[0]-50:edge[0]][::-1]
215
+ cutout_right = image[y,edge[1]:edge[1]+50]
216
+
217
+ not_ones = np.where(cutout_left != 1)[0]
218
+ if len(not_ones) > 0 and not_ones[0] > 0:
219
+ last_one_index = not_ones[0] - 1
220
+ edge = (edge[0] - last_one_index,) + edge[1:]
221
+ else:
222
+ last_one_index = None if len(not_ones) == 0 else not_ones[-1] - 1
223
+
224
+ not_ones = np.where(cutout_right != 1)[0]
225
+ if len(not_ones) > 0 and not_ones[0] > 0:
226
+ last_one_index = not_ones[0] - 1
227
+ edge = (edge[0], edge[1] - last_one_index) + edge[2:]
228
+ else:
229
+ last_one_index = None if len(not_ones) == 0 else not_ones[-1] - 1
230
+
231
+ edges_with_guard_rails.append(edge)
232
+
233
+ edges_dict[y] = edges_with_guard_rails
234
+
235
+ edges_dict = {k: v for k, v in edges_dict.items() if v}
236
+
237
+ edges_dict = filter_crossings(image, edges_dict)
238
+
239
+ return edges_dict
240
+
241
+ def find_rails(arr, y_levels, values=[9, 10], min_width=5):
242
+ edges_all = []
243
+ for y in y_levels:
244
+ row = arr[y, :]
245
+ mask = np.isin(row, values).astype(int)
246
+ padded_mask = np.pad(mask, (1, 1), 'constant', constant_values=0)
247
+ diff = np.diff(padded_mask)
248
+ starts = np.where(diff == 1)[0]
249
+ ends = np.where(diff == -1)[0] - 1
250
+
251
+ # Filter sequences based on the minimum width criteria
252
+ filtered_edges = [(start, end) for start, end in zip(starts, ends) if end - start + 1 >= min_width]
253
+ filtered_edges = [(start, end) for start, end in filtered_edges if 0 not in (start, end) and 1919 not in (start, end)]
254
+ edges_all = filtered_edges
255
+
256
+ return edges_all
257
+
258
+ def mark_edges(arr, edges_dict, mark_value=30):
259
+ """
260
+ Marks a 5x5 zone around the edges found in the array with a specific value.
261
+
262
+ Parameters:
263
+ - arr: The original 2D NumPy array.
264
+ - edges_dict: A dictionary with y-levels as keys and lists of (start, end) tuples for edges.
265
+ - mark_value: The value used to mark the edges.
266
+
267
+ Returns:
268
+ The modified array with marked zones.
269
+ """
270
+ marked_arr = np.copy(arr) # Create a copy of the array to avoid modifying the original
271
+ offset = 2 # To mark a 5x5 area, we go 2 pixels in each direction from the center
272
+
273
+ for y, edges in edges_dict.items():
274
+ for start, end in edges:
275
+ # Mark a 5x5 zone around the start and end positions
276
+ for dy in range(-offset, offset + 1):
277
+ for dx in range(-offset, offset + 1):
278
+ # Check array bounds before marking
279
+ if 0 <= y + dy < marked_arr.shape[0] and 0 <= start + dx < marked_arr.shape[1]:
280
+ marked_arr[y + dy, start + dx] = mark_value
281
+ if 0 <= y + dy < marked_arr.shape[0] and 0 <= end + dx < marked_arr.shape[1]:
282
+ marked_arr[y + dy, end + dx] = mark_value
283
+
284
+ return marked_arr
285
+
286
+ def find_rail_sides(img, edges_dict):
287
+ left_border = []
288
+ right_border = []
289
+ for y,xs in edges_dict.items():
290
+ rails = find_rails(img, [y], values=[9,10], min_width=5)
291
+ left_border_actual = [min(xs)[0],y]
292
+ right_border_actual = [max(xs)[1],y]
293
+
294
+ for zone in rails:
295
+ if abs(zone[1]-left_border_actual[0]) < y*0.04: # dynamic treshold
296
+ left_border_actual[0] = zone[0]
297
+ if abs(zone[0]-right_border_actual[0]) < y*0.04:
298
+ right_border_actual[0] = zone[1]
299
+
300
+ left_border.append(left_border_actual)
301
+ right_border.append(right_border_actual)
302
+
303
+ # removing detected uncontioussness
304
+ left_border, flags_l, _ = robust_rail_sides(left_border) # filter outliers
305
+ right_border, flags_r, _ = robust_rail_sides(right_border)
306
+
307
+ return left_border, right_border, flags_l, flags_r
308
+
309
+ def robust_rail_sides(border, threshold=7):
310
+ border = np.array(border)
311
+ if border.size > 0:
312
+ # delete borders found on the bottom side of the image
313
+ border = border[border[:, 1] != 1079]
314
+
315
+ steps_x = np.diff(border[:, 0])
316
+ median_step = np.median(np.abs(steps_x))
317
+
318
+ threshold_step = np.abs(threshold*np.abs(median_step))
319
+ treshold_overcommings = abs(steps_x) > abs(threshold_step)
320
+
321
+ flags = []
322
+
323
+ if True not in treshold_overcommings:
324
+ return border, flags, []
325
+ else:
326
+ overcommings_indices = [i for i, element in enumerate(treshold_overcommings) if element == True]
327
+ if overcommings_indices and np.all(np.diff(overcommings_indices) == 1):
328
+ overcommings_indices = [overcommings_indices[0]]
329
+
330
+ filtered_border = border
331
+
332
+ previously_deleted = []
333
+ for i in overcommings_indices:
334
+ for item in previously_deleted:
335
+ if item[0] < i:
336
+ i -= item[1]
337
+ first_part = filtered_border[:i+1]
338
+ second_part = filtered_border[i+1:]
339
+ if len(second_part)<2:
340
+ filtered_border = first_part
341
+ previously_deleted.append([i,len(second_part)])
342
+ elif len(first_part)<2:
343
+ filtered_border = second_part
344
+ previously_deleted.append([i,len(first_part)])
345
+ else:
346
+ first_b, _, deleted_first = robust_rail_sides(first_part)
347
+ second_b, _, _ = robust_rail_sides(second_part)
348
+ filtered_border = np.concatenate((first_b,second_b), axis=0)
349
+
350
+ if deleted_first:
351
+ for deleted_item in deleted_first:
352
+ if deleted_item[0]<=i:
353
+ i -= deleted_item[1]
354
+
355
+ flags.append(i)
356
+ return filtered_border, flags, previously_deleted
357
+ else:
358
+ return border, [], []
359
+
360
+ def find_dist_from_edges(id_map, image, edges_dict, left_border, right_border, real_life_width_mm, real_life_target_mm, mark_value=30):
361
+ """
362
+ Mark regions representing a real-life distance (e.g., 2 meters) to the left and right from the furthest edges.
363
+
364
+ Parameters:
365
+ - arr: 2D NumPy array representing the id_map.
366
+ - edges_dict: Dictionary with y-levels as keys and lists of (start, end) tuples for edges.
367
+ - real_life_width_mm: The real-world width in millimeters that the average sequence width represents.
368
+ - real_life_target_mm: The real-world distance in millimeters to mark from the edges.
369
+
370
+ Returns:
371
+ - A NumPy array with the marked regions.
372
+ """
373
+ # Calculate the rail widths
374
+ diffs_widths = {k: sum(e-s for s, e in v) / len(v) for k, v in edges_dict.items() if v}
375
+ diffs_width = {k: max(e-s for s, e in v) for k, v in edges_dict.items() if v}
376
+
377
+ # Pixel to mm scale factor
378
+ scale_factors = {k: real_life_width_mm / v for k, v in diffs_width.items()}
379
+ # Converting the real-life target distance to pixels
380
+ target_distances_px = {k: int(real_life_target_mm / v) for k, v in scale_factors.items()}
381
+
382
+ # Mark the regions representing the target distance to the left and right from the furthest edges
383
+ end_points_left = {}
384
+ region_levels_left = []
385
+ for point in left_border:
386
+ min_edge = point[0]
387
+
388
+ # Ensure we stay within the image bounds
389
+ #left_mark_start = max(0, min_edge - int(target_distances_px[point[1]]))
390
+ left_mark_start = min_edge - int(target_distances_px[point[1]])
391
+ end_points_left[point[1]] = left_mark_start
392
+
393
+ # Left region points
394
+ if left_mark_start < min_edge:
395
+ y_values = np.arange(left_mark_start, min_edge)
396
+ x_values = np.full_like(y_values, point[1])
397
+ region_line = np.column_stack((x_values, y_values))
398
+ region_levels_left.append(region_line)
399
+
400
+ end_points_right = {}
401
+ region_levels_right = []
402
+ for point in right_border:
403
+ max_edge = point[0]
404
+
405
+ # Ensure we stay within the image bounds
406
+ right_mark_end = min(id_map.shape[1], max_edge + int(target_distances_px[point[1]]))
407
+ if right_mark_end != id_map.shape[1]:
408
+ end_points_right[point[1]] = right_mark_end
409
+
410
+ # Right region points
411
+ if max_edge < right_mark_end:
412
+ y_values = np.arange(max_edge, right_mark_end)
413
+ x_values = np.full_like(y_values, point[1])
414
+ region_line = np.column_stack((x_values, y_values))
415
+ region_levels_right.append(region_line)
416
+
417
+ return id_map, end_points_left, end_points_right, region_levels_left, region_levels_right
418
+
419
+ def bresenham_line(x0, y0, x1, y1):
420
+ """
421
+ Generate the coordinates of a line from (x0, y0) to (x1, y1) using Bresenham's algorithm.
422
+ """
423
+ line = []
424
+ dx = abs(x1 - x0)
425
+ dy = -abs(y1 - y0)
426
+ sx = 1 if x0 < x1 else -1
427
+ sy = 1 if y0 < y1 else -1
428
+ err = dx + dy # error value e_xy
429
+
430
+ while True:
431
+ line.append((x0, y0)) # Add the current point to the line
432
+ if x0 == x1 and y0 == y1:
433
+ break
434
+ e2 = 2 * err
435
+ if e2 >= dy: # e_xy+e_x > 0
436
+ err += dy
437
+ x0 += sx
438
+ if e2 <= dx: # e_xy+e_y < 0
439
+ err += dx
440
+ y0 += sy
441
+
442
+ return line
443
+
444
+ def interpolate_end_points(end_points_dict, flags):
445
+ line_arr = []
446
+ ys = list(end_points_dict.keys())
447
+ xs = list(end_points_dict.values())
448
+
449
+ if flags and len(flags) == 1:
450
+ pass
451
+ elif flags and np.all(np.diff(flags) == 1):
452
+ flags = [flags[0]]
453
+
454
+ for i in range(0, len(ys) - 1):
455
+ if i in flags:
456
+ continue
457
+ y1, y2 = ys[i], ys[i + 1]
458
+ x1, x2 = xs[i], xs[i + 1]
459
+ line = np.array(bresenham_line(x1, y1, x2, y2))
460
+ if np.any(line[:, 0] < 0):
461
+ line = line[line[:, 0] > 0]
462
+ line_arr = line_arr + list(line)
463
+
464
+ return line_arr
465
+
466
+ def extrapolate_line(pixels, image, min_y=None, extr_pixels=10):
467
+ """
468
+ Extrapolate a line based on the last segment using linear regression.
469
+
470
+ Parameters:
471
+ - pixels: List of (x, y) tuples representing line pixel coordinates.
472
+ - image: 2D numpy array representing the image.
473
+ - min_y: Minimum y-value to extrapolate to (optional).
474
+
475
+ Returns:
476
+ - A list of new extrapolated (x, y) pixel coordinates.
477
+ """
478
+ if len(pixels) < extr_pixels:
479
+ print("Not enough pixels to perform extrapolation.")
480
+ return []
481
+
482
+ recent_pixels = np.array(pixels[-extr_pixels:])
483
+
484
+ X = recent_pixels[:, 0].reshape(-1, 1) # Reshape for sklearn
485
+ y = recent_pixels[:, 1]
486
+
487
+ model = LinearRegression()
488
+ model.fit(X, y)
489
+
490
+ slope = model.coef_[0]
491
+ intercept = model.intercept_
492
+
493
+ extrapolate = lambda x: slope * x + intercept
494
+
495
+ # Calculate direction based on last two pixels
496
+ dx, dy = 0, 0 # Default values
497
+
498
+ x_diffs = []
499
+ y_diffs = []
500
+ for i in range(1,extr_pixels-1):
501
+ x_diffs.append(pixels[-i][0] - pixels[-(i+1)][0])
502
+ y_diffs.append(pixels[-i][1] - pixels[-(i+1)][1])
503
+
504
+ x_diff = x_diffs[np.argmax(np.abs(x_diffs))]
505
+ y_diff = y_diffs[np.argmax(np.abs(y_diffs))]
506
+
507
+ if abs(int(x_diff)) >= abs(int(y_diff)):
508
+ dx = 1 if x_diff >= 0 else -1
509
+ else:
510
+ dy = 1 if y_diff >= 0 else -1
511
+
512
+ last_pixel = pixels[-1]
513
+ new_pixels = []
514
+ x, y = last_pixel
515
+
516
+ min_y = min_y if min_y is not None else image.shape[0] - 1
517
+
518
+ while 0 <= x < image.shape[1] and min_y <= y < image.shape[0]:
519
+ if dx != 0: # Horizontal or diagonal movement
520
+ x += dx
521
+ y = int(extrapolate(x))
522
+ elif dy != 0: # Vertical movement
523
+ y += dy
524
+ # For vertical lines, approximate x based on the last known value
525
+ x = int(x)
526
+
527
+ if 0 <= y < image.shape[0] and 0 <= x < image.shape[1]:
528
+ new_pixels.append((x, y))
529
+ else:
530
+ break
531
+
532
+ return new_pixels
533
+
534
+ def extrapolate_borders(dist_marked_id_map, border_l, border_r, lowest_y):
535
+
536
+ #border_extrapolation_l1 = extrapolate_line(border_l, dist_marked_id_map, lowest_y)
537
+ border_extrapolation_l2 = extrapolate_line(border_l[::-1], dist_marked_id_map, lowest_y)
538
+
539
+ #border_extrapolation_r1 = extrapolate_line(border_r, dist_marked_id_map, lowest_y)
540
+ border_extrapolation_r2 = extrapolate_line(border_r[::-1], dist_marked_id_map, lowest_y)
541
+
542
+ #border_l = border_extrapolation_l2[::-1] + border_l + border_extrapolation_l1
543
+ #border_r = border_extrapolation_r2[::-1] + border_r + border_extrapolation_r1
544
+
545
+ border_l = border_extrapolation_l2[::-1] + border_l
546
+ border_r = border_extrapolation_r2[::-1] + border_r
547
+
548
+ return border_l, border_r
549
+
550
+ def find_zone_border(id_map, image, edges, irl_width_mm=1435, irl_target_mm=1000, lowest_y = 0):
551
+
552
+ left_border, right_border, flags_l, flags_r = find_rail_sides(id_map, edges)
553
+
554
+ dist_marked_id_map, end_points_left, end_points_right, left_region, right_region = find_dist_from_edges(id_map, image, edges, left_border, right_border, irl_width_mm, irl_target_mm)
555
+
556
+ border_l = interpolate_end_points(end_points_left, flags_l)
557
+ border_r = interpolate_end_points(end_points_right, flags_r)
558
+
559
+ border_l, border_r = extrapolate_borders(dist_marked_id_map, border_l, border_r, lowest_y)
560
+
561
+ return [border_l, border_r],[left_region, right_region]
562
+
563
+ def get_clues(segmentation_mask, number_of_clues):
564
+
565
+ lowest, highest = find_extreme_y_values(segmentation_mask)
566
+ if lowest is not None and highest is not None:
567
+ clue_step = int((highest - lowest) / number_of_clues+1)
568
+ clues = []
569
+ for i in range(number_of_clues):
570
+ clues.append(highest - (i*clue_step))
571
+ clues.append(lowest+int(0.5*clue_step))
572
+
573
+ return clues
574
+ else:
575
+ return []
576
+
577
+ def border_handler(id_map, image, edges, target_distances):
578
+
579
+ lowest, _ = find_extreme_y_values(id_map)
580
+ borders = []
581
+ regions = []
582
+ for target in target_distances:
583
+ borders_regions = find_zone_border(id_map, image, edges, irl_target_mm=target, lowest_y = lowest)
584
+ borders.append(borders_regions[0])
585
+ regions.append(borders_regions[1])
586
+
587
+ return borders, id_map, regions
588
+
589
+ def segment(input_image, model_seg, image_size):
590
+ image_norm, image = get_segformer_img(input_image, image_size)
591
+
592
+ outputs = model_seg(image_norm)
593
+
594
+ logits = outputs.logits
595
+ upsampled_logits = nn.functional.interpolate(
596
+ logits,
597
+ size=image_norm.shape[-2:],
598
+ mode="bilinear",
599
+ align_corners=False
600
+ )
601
+
602
+ output = upsampled_logits.float()
603
+
604
+ confidence_scores = F.softmax(output, dim=1).cpu().detach().numpy().squeeze()
605
+ id_map = np.argmax(confidence_scores, axis=0).astype(np.uint8)
606
+ id_map = image_morpho(id_map)
607
+
608
+ id_map = cv2.resize(id_map, [1920,1080], interpolation=cv2.INTER_NEAREST)
609
+ return id_map, image
610
+
611
+ def detect(model_det, image):
612
+
613
+ results = model_det.predict(image)
614
+
615
+ return results, model_det, image
616
+
617
+ def manage_detections(results, model):
618
+ bbox = results[0].boxes.xywh.tolist()
619
+ cls = results[0].boxes.cls.tolist()
620
+ accepted_stationary = np.array([24,25,28,36])
621
+ accepted_moving = np.array([0,1,2,3,7,15,16,17,18,19])
622
+ boxes_moving = {}
623
+ boxes_stationary = {}
624
+ if len(bbox) > 0:
625
+ for xywh, clss in zip(bbox, cls):
626
+ if clss in accepted_moving:
627
+ if clss in boxes_moving.keys() and len(boxes_moving[clss]) > 0:
628
+ boxes_moving[clss].append(xywh)
629
+ else:
630
+ boxes_moving[clss] = [xywh]
631
+ if clss in accepted_stationary:
632
+ if clss in boxes_stationary.keys() and len(boxes_stationary[clss]) > 0:
633
+ boxes_stationary[clss].append(xywh)
634
+ else:
635
+ boxes_stationary[clss] = [xywh]
636
+
637
+ return boxes_moving, boxes_stationary
638
+
639
+ def compute_detection_borders(borders, output_dims=[1080,1920]):
640
+ det_height = output_dims[0]-1
641
+ det_width = output_dims[1]-1
642
+
643
+ for i,border in enumerate(borders):
644
+ border_l = np.array(border[0])
645
+
646
+ if list(border_l):
647
+ pass
648
+ else:
649
+ border_l=np.array([[0,0],[0,0]])
650
+
651
+ endpoints_l = [border_l[0],border_l[-1]]
652
+
653
+ border_r = np.array(border[1])
654
+ if list(border_r):
655
+ pass
656
+ else:
657
+ border_r=np.array([[0,0],[0,0]])
658
+
659
+ endpoints_r = [border_r[0],border_r[-1]]
660
+
661
+ if np.array_equal(np.array([[0,0],[0,0]]), endpoints_l):
662
+ endpoints_l = [[0,endpoints_r[0][1]],[0,endpoints_r[1][1]]]
663
+
664
+ if np.array_equal(np.array([[0,0],[0,0]]), endpoints_r):
665
+ endpoints_r = [[det_width,endpoints_l[0][1]],[det_width,endpoints_l[1][1]]]
666
+
667
+ interpolated_top = bresenham_line(endpoints_l[1][0],endpoints_l[1][1],endpoints_r[1][0],endpoints_r[1][1])
668
+
669
+ zero_range = [0,1,2,3]
670
+ height_range = [det_height,det_height-1,det_height-2,det_height-3]
671
+ width_range = [det_width,det_width-1,det_width-2,det_width-3]
672
+
673
+ if (endpoints_l[0][0] in zero_range and endpoints_r[0][1] in height_range):
674
+ y_values = np.arange(endpoints_l[0][1], det_height)
675
+ x_values = np.full_like(y_values, 0)
676
+ bottom1 = np.column_stack((x_values, y_values))
677
+
678
+ x_values = np.arange(0, endpoints_r[0][0])
679
+ y_values = np.full_like(x_values, det_height)
680
+ bottom2 = np.column_stack((x_values, y_values))
681
+
682
+ interpolated_bottom = np.vstack((bottom1, bottom2))
683
+
684
+ elif (endpoints_l[0][1] in height_range and endpoints_r[0][0] in width_range):
685
+ y_values = np.arange(endpoints_r[0][1], det_height)
686
+ x_values = np.full_like(y_values, det_width)
687
+ bottom1 = np.column_stack((x_values, y_values))
688
+
689
+ x_values = np.arange(endpoints_l[0][0], det_width)
690
+ y_values = np.full_like(x_values, det_height)
691
+ bottom2 = np.column_stack((x_values, y_values))
692
+
693
+ interpolated_bottom = np.vstack((bottom1, bottom2))
694
+
695
+ elif endpoints_l[0][0] in zero_range and endpoints_r[0][0] in width_range:
696
+ y_values = np.arange(endpoints_l[0][1], det_height)
697
+ x_values = np.full_like(y_values, 0)
698
+ bottom1 = np.column_stack((x_values, y_values))
699
+
700
+ y_values = np.arange(endpoints_r[0][1], det_height)
701
+ x_values = np.full_like(y_values, det_width)
702
+ bottom2 = np.column_stack((x_values, y_values))
703
+
704
+ bottom3_mid = bresenham_line(bottom1[-1][0],bottom1[-1][1],bottom2[-1][0],bottom2[-1][1])
705
+
706
+ interpolated_bottom = np.vstack((bottom1, bottom2, bottom3_mid))
707
+
708
+
709
+ else:
710
+ interpolated_bottom = bresenham_line(endpoints_l[0][0],endpoints_l[0][1],endpoints_r[0][0],endpoints_r[0][1])
711
+
712
+ borders[i].append(interpolated_bottom)
713
+ borders[i].append(interpolated_top)
714
+
715
+ return borders
716
+
717
+ def get_bounding_box_points(cx, cy, w, h):
718
+ top_left = (cx - w / 2, cy - h / 2)
719
+ top_right = (cx + w / 2, cy - h / 2)
720
+ bottom_right = (cx + w / 2, cy + h / 2)
721
+ bottom_left = (cx - w / 2, cy + h / 2)
722
+
723
+ corners = [top_left, top_right, bottom_right, bottom_left]
724
+
725
+ def interpolate(point1, point2, fraction):
726
+ """Interpolate between two points at a given fraction of the distance."""
727
+ return (point1[0] + fraction * (point2[0] - point1[0]),
728
+ point1[1] + fraction * (point2[1] - point1[1]))
729
+
730
+ points = []
731
+ for i in range(4):
732
+ next_i = (i + 1) % 4
733
+ points.append(corners[i])
734
+ points.append(interpolate(corners[i], corners[next_i], 1 / 3))
735
+ points.append(interpolate(corners[i], corners[next_i], 2 / 3))
736
+
737
+ return points
738
+
739
+ def classify_detections(boxes_moving, boxes_stationary, borders, img_dims, output_dims=[1080,1920]):
740
+ img_h, img_w, _ = img_dims
741
+ img_h_scaletofullHD = output_dims[1]/img_w
742
+ img_w_scaletofullHD = output_dims[0]/img_h
743
+ colors = ["yellow","orange","red","green","blue"]
744
+
745
+ borders = compute_detection_borders(borders,output_dims)
746
+
747
+ boxes_info = []
748
+
749
+ if boxes_moving or boxes_stationary:
750
+ if boxes_moving:
751
+ for item, coords in boxes_moving.items():
752
+ for coord in coords:
753
+ x = coord[0]*img_w_scaletofullHD
754
+ y = coord[1]*img_h_scaletofullHD
755
+ w = coord[2]*img_w_scaletofullHD
756
+ h = coord[3]*img_h_scaletofullHD
757
+
758
+ points_to_test = get_bounding_box_points(x, y, w, h)
759
+
760
+ complete_border = []
761
+ criticality = -1
762
+ color = None
763
+ for i,border in enumerate(reversed(borders)):
764
+ border_nonempty = [np.array(arr) for arr in border if np.array(arr).size > 0]
765
+ complete_border = np.vstack((border_nonempty))
766
+ instance_border_path = mplPath.Path(np.array(complete_border))
767
+
768
+ is_inside_borders = False
769
+ for point in points_to_test:
770
+ is_inside = instance_border_path.contains_point(point)
771
+ if is_inside:
772
+ is_inside_borders = True
773
+
774
+ if is_inside_borders:
775
+ criticality = i
776
+ color = colors[i]
777
+
778
+ if criticality == -1:
779
+ color = colors[3]
780
+
781
+ boxes_info.append([item, criticality, color, [x, y], [w, h], 1])
782
+
783
+ if boxes_stationary:
784
+ for item, coords in boxes_stationary.items():
785
+ for coord in coords:
786
+ x = coord[0]*img_w_scaletofullHD
787
+ y = coord[1]*img_h_scaletofullHD
788
+ w = coord[2]*img_w_scaletofullHD
789
+ h = coord[3]*img_h_scaletofullHD
790
+
791
+ points_to_test = get_bounding_box_points(x, y, w, h)
792
+
793
+ complete_border = []
794
+ criticality = -1
795
+ color = None
796
+ is_inside_borders = 0
797
+ for i,border in enumerate(reversed(borders), start=len(borders) - 1):
798
+ border_nonempty = [np.array(arr) for arr in border if np.array(arr).size > 0]
799
+ complete_border = np.vstack(border_nonempty)
800
+ instance_border_path = mplPath.Path(np.array(complete_border))
801
+
802
+ is_inside_borders = False
803
+ for point in points_to_test:
804
+ is_inside = instance_border_path.contains_point(point)
805
+ if is_inside:
806
+ is_inside_borders = True
807
+
808
+ if is_inside_borders:
809
+ criticality = i
810
+ color = colors[4]
811
+
812
+ if criticality == -1:
813
+ color = colors[3]
814
+
815
+ boxes_info.append([item, criticality, color, [x, y], [w, h], 0])
816
+
817
+ return boxes_info
818
+
819
+ else:
820
+ print("No accepted detections in this image.")
821
+ return []
822
+
823
+ def draw_classification(classification, id_map):
824
+ if classification:
825
+ for box in classification:
826
+ x,y = box[3]
827
+ mark_value = 30
828
+
829
+ x_start = int(max(x - 2, 0))
830
+ x_end = int(min(x + 3, id_map.shape[1]))
831
+ y_start = int(max(y - 2, 0))
832
+ y_end = int(min(y + 3, id_map.shape[0]))
833
+
834
+ id_map[y_start:y_end, x_start:x_end] = mark_value
835
+ else:
836
+ return
837
+
838
+ def get_result(classification, id_map, names, borders, image, regions):
839
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
840
+ image = cv2.resize(image, (id_map.shape[1], id_map.shape[0]), interpolation = cv2.INTER_LINEAR)
841
+ fig = plt.figure(figsize=(16, 9), dpi=100)
842
+ plt.imshow(image, cmap='gray')
843
+
844
+ if classification:
845
+ for box in classification:
846
+
847
+ boxes = True
848
+ cx,cy = box[3]
849
+ name = names[box[0]]
850
+ if boxes:
851
+ w,h = box[4]
852
+ x = cx - w / 2
853
+ y = cy - h / 2
854
+ rect = patches.Rectangle((x, y), w, h, linewidth=2, edgecolor=box[2], facecolor='none')
855
+
856
+ ax = plt.gca()
857
+ ax.add_patch(rect)
858
+ plt.text(x, y-17, name, color='black', fontsize=10, ha='center', va='center', fontweight='bold', bbox=dict(facecolor=box[2], edgecolor='none', alpha=1))
859
+ else:
860
+ plt.imshow(id_map, cmap='gray')
861
+ plt.text(cx, cy+10, name, color=box[2], fontsize=10, ha='center', va='center', fontweight='bold')
862
+
863
+ for region in regions:
864
+ for side in region:
865
+ for line in side:
866
+ line = np.array(line)
867
+ plt.plot(line[:,1], line[:,0] ,'-', color='lightgrey', marker=None, linewidth=0.5)
868
+ plt.ylim(0, 1080)
869
+ plt.xlim(0, 1920)
870
+ plt.gca().invert_yaxis()
871
+
872
+ colors = ['yellow','orange','red']
873
+ borders.reverse()
874
+ for i,border in enumerate(borders):
875
+ for side in border:
876
+ side = np.array(side)
877
+ if side.size > 0:
878
+ plt.plot(side[:,0],side[:,1] ,'-', color=colors[i], marker=None, linewidth=0.6) #color=colors[i]
879
+ plt.ylim(0, 1080)
880
+ plt.xlim(0, 1920)
881
+ plt.gca().invert_yaxis()
882
+
883
+ plt.show()
884
+
885
+ def run(input_image, model_seg, model_det, image_size, target_distances, num_ys = 10):
886
+
887
+ segmentation_mask, image = segment(input_image, model_seg, image_size)
888
+
889
+ # Border search
890
+ clues = get_clues(segmentation_mask, num_ys)
891
+ edges = find_edges(segmentation_mask, clues, min_width=0)
892
+ borders, id_map, regions = border_handler(segmentation_mask, image, edges, target_distances)
893
+
894
+ # Detection
895
+ results, model, image = detect(model_det, input_image)
896
+ boxes_moving, boxes_stationary = manage_detections(results, model)
897
+
898
+ classification = classify_detections(boxes_moving, boxes_stationary, borders, image.shape, output_dims=segmentation_mask.shape)
899
+
900
+ output_image = get_result(classification, id_map, model.names, borders, image, regions)
901
+
902
+ return output_image
903
+
904
+ if __name__ == "__main__":
905
+
906
+ image_size = [1024,1024]
907
+ target_distances = [650,1000,2000]
908
+ num_ys = 10
909
+
910
+ PATH_model_seg = 'SegFormer_B3_1024_finetuned.pth'
911
+ PATH_model_det = 'yolov8s.pt'
912
+ input_image = cv2.imread('rs00006.jpg') #TO CO VLOZI UZIVATEL
913
+ model_seg = load_segformer(PATH_model_seg)
914
+ model_det = load_yolo(PATH_model_det)
915
+ run(input_image, model_seg, model_det, image_size, target_distances, num_ys=num_ys)
916
+
app.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
+ from PIL import Image
5
+ from TheDistanceAssessor import run, load_segformer, load_yolo
6
+
7
+ def process_image(input_image):
8
+ image_size = [1024,1024]
9
+ target_distances = [650,1000,2000]
10
+ num_ys = 10
11
+
12
+ PATH_model_seg = 'SegFormer_B3_1024_finetuned.pth'
13
+ PATH_model_det = 'yolov8s.pt'
14
+ model_seg = load_segformer(PATH_model_seg)
15
+ model_det = load_yolo(PATH_model_det)
16
+ output_image = run(input_image, model_seg, model_det, image_size, target_distances, num_ys = num_ys)
17
+ return output_image
18
+
19
+ # Create the Gradio interface
20
+ iface = gr.Interface(
21
+ fn=process_image, # The function to be called
22
+ inputs=gr.Image(type="pil"), # Input type
23
+ outputs=gr.Image(type="numpy"), # Output type
24
+ title="Image Processor", # Title of the interface
25
+ description="Upload an image and get a processed image as output." # Description of the interface
26
+ )
27
+
28
+ # Launch the interface
29
+ if __name__ == "__main__":
30
+ iface.launch()