fft_structure_extraction.py
Go to the documentation of this file.
1 import math
2 import os
3 import time
4 
5 import matplotlib.patches as patches
6 import matplotlib.pyplot as plt
7 import numpy as np
8 import png
9 import scipy.stats as stats
10 import skimage.draw as sk_draw
11 from scipy import ndimage
12 from scipy.signal import find_peaks
13 from skimage.filters import threshold_yen
14 from skimage.segmentation import flood_fill
15 from skimage.morphology import binary_dilation
16 from sklearn import mixture
17 from sklearn.cluster import DBSCAN
18 from sklearn.neighbors import KernelDensity
19 import rospy
20 import rose_v1_repo.segment_handling as sh
21 import rose_v1_repo.helpers as he
22 
24  slices_lines = []
25  for s in slices:
26  slices_lines.append([s[0][0][0], s[1][0][0], s[0][0][-1], s[1][0][-1]])
27  return slices_lines
28 
29 
30 def save_simple_map(name, map_to_save, shape):
31  with open(name, "wb") as out:
32  png_writer = png.Writer(shape[1], shape[0], greyscale=True, alpha=False, bitdepth=1)
33  img = map_to_save[:shape[0], :shape[1]]
34  png_writer.write(out, img)
35 
36 
38  def __init__(self, grid_map, ang_tr=0.1, amp_tr=0.8, peak_height=0.5, par=200, smooth=False, sigma=3):
39  self.main_directions = [] #added
41  self.slice_v_lines = []
42  self.slice_h_lines = []
44  self.all_lines = []
47  self.segments_h = []
48  self.segments_v = []
49  self.slices_h_dir = []
50  self.slices_v_dir = []
51  self.slices_v_ids = []
52  self.slices_h_ids = []
53  self.slices_v = []
54  self.slices_h = []
58  self.lines = []
59  self.lines_long_h = []
60  self.lines_long_v = []
67  self.d_row_h = []
68  self.d_row_v = []
69  self.part_mask = []
70  self.part_score = []
71 
72  self.ang_tr = ang_tr # rad
73  self.amp_tr = amp_tr # ratio
74  self.peak_height = peak_height
75  self.par = par
76  self.smooth = smooth
77  self.sigma = sigma
78  self.grid_map = []
79  self.binary_map = None
80  self.analysed_map = None
81  self.smooth = smooth
82 
86 
87  self.line_parameters = []
88  self.norm_ft_image = None
89  self.pol = []
90  self.angles = []
91  self.pol_h = []
92  self.peak_indices = []
93  self.rads = []
94  self.comp = []
95  self.mask_ft_image = []
97  self.map_scored_good = []
98  self.map_scored_bad = []
99  self.map_scored_diff = []
100  self.map_split_good = []
101  self.ft_image_split = []
102  self.ft_image = []
104  self.shape = None
105 
106  self.load_map(grid_map)
107 
108  def load_map(self, grid_map):
109  rospy.loginfo("[ROSE] Load Map.....")
110  ti = time.time()
111  if len(grid_map.shape) == 3:
112  grid_map = grid_map[:, :, 1]
113  thresh = threshold_yen(grid_map)
114  self.binary_map = grid_map <= thresh
115  self.binary_map = self.binary_map
116  if self.binary_map.shape[0] % 2 != 0:
117  t = np.zeros((self.binary_map.shape[0] + 1, self.binary_map.shape[1]), dtype=bool)
118  t[:-1, :] = self.binary_map
119  self.binary_map = t
120  if self.binary_map.shape[1] % 2 != 0:
121  t = np.zeros((self.binary_map.shape[0], self.binary_map.shape[1] + 1), dtype=bool)
122  t[:, :-1] = self.binary_map
123  self.binary_map = t
124  # pad with zeros to square
125  self.shape = self.binary_map.shape
126  square_map = np.zeros((np.max(self.binary_map.shape), np.max(self.binary_map.shape)), dtype=bool)
127  square_map[:self.binary_map.shape[0], :self.binary_map.shape[1]] = self.binary_map
128  self.binary_map = square_map
129  self.analysed_map = self.binary_map.copy()
130  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - ti))
131 
132  def compute_fft(self):
133  rospy.loginfo("[ROSE] Compute FFT.....")
134  t = time.time()
135  self.ft_image = np.fft.fftshift(np.fft.fft2(self.binary_map * 1))
136 
137  self.norm_ft_image = (np.abs(self.ft_image) / np.max(np.abs(self.ft_image))) * 255.0
138  self.norm_ft_image = self.norm_ft_image.astype(int)
139 
140  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
141 
142  def generate_mask(self, x1_1, y1_1, x2_1, y2_1, x1_2, y1_2, x2_2, y2_2, y_org):
143  mask_1 = np.zeros(self.norm_ft_image.shape, dtype=np.uint8)
144  # c_1 = np.array([Y1_1, Y2_1, self.norm_ft_image.shape[1], self.norm_ft_image.shape[1]])
145  c_1 = np.array([y1_1, y2_1, self.norm_ft_image.shape[0], self.norm_ft_image.shape[0]])
146  r_1 = np.array([x1_1, x2_1, self.norm_ft_image.shape[0], 0])
147  if np.abs(y_org) > 3 * np.max(self.binary_map.shape):
148  # c_1 = np.array([Y1_1, Y2_1, self.norm_ft_image.shape[1], 0])
149  c_1 = np.array([y1_1, y2_1, self.norm_ft_image.shape[0], 0])
150  r_1 = np.array([x1_1, x2_1, 0, 0])
151  rr, cc = he.generate_mask(r_1, c_1, self.norm_ft_image.shape)
152  mask_1[rr, cc] = 1
153  mask_1 = np.flipud(mask_1)
154 
155  mask_2 = np.zeros(self.norm_ft_image.shape, dtype=np.uint8)
156  c_2 = np.array([y1_2, y2_2, 0, 0])
157  r_2 = np.array([x1_2, x2_2, self.norm_ft_image.shape[0], 0])
158  if np.abs(y_org) > 3 * np.max(self.binary_map.shape):
159  # c_2 = np.array([Y1_2, Y2_2, self.norm_ft_image.shape[1], 0])
160  c_2 = np.array([y1_2, y2_2, self.norm_ft_image.shape[0], 0])
161  r_2 = np.array([x1_2, x2_2, self.norm_ft_image.shape[0], self.norm_ft_image.shape[0]])
162  rr, cc = he.generate_mask(r_2, c_2, self.norm_ft_image.shape)
163  mask_2[rr, cc] = 1
164  mask_2 = np.flipud(mask_2)
165 
166  mask_l = np.logical_and(mask_1, mask_2)
167  return mask_l
168 
169  def process_map(self):
170  self.compute_fft()
171 
172  rospy.loginfo("[ROSE] Find Dominant directions.....")
173  t = time.time()
174  self.pol, (self.rads, self.angles) = he.topolar(self.norm_ft_image, order=3)
175  pol_l = self.pol.shape[1]
176  self.pol = np.concatenate((self.pol, self.pol[:, 1:], self.pol[:, 1:]), axis=1)
177  self.angles = np.concatenate(
178  (self.angles, self.angles[1:] + np.max(self.angles), self.angles[1:] + np.max(self.angles[1:] +
179  np.max(self.angles))), axis=0)
180 
181  if self.smooth:
182  self.angles = ndimage.gaussian_filter1d(self.angles, self.sigma)
183  self.pol = ndimage.gaussian_filter1d(self.pol, self.sigma)
184 
185  self.pol_h = np.array([sum(x) for x in zip(*self.pol)])
186 
187  self.peak_indices, _ = find_peaks(self.pol_h,
188  prominence=(np.max(self.pol_h) - np.min(self.pol_h)) * self.peak_height)
189 
190  self.pol = self.pol[:, 0:pol_l]
191  self.angles = self.angles[0:pol_l]
192  self.pol_h = self.pol_h[0:pol_l]
193  self.peak_indices = self.peak_indices[np.logical_and(self.peak_indices >= pol_l - 1,
194  self.peak_indices < 2 * pol_l - 2)] - pol_l + 1
195 
196  pairs = list()
197  # angle_dist_mat = list()
198  for aind in self.peak_indices:
199  # row = list()
200  for bind in self.peak_indices:
201  a = self.angles[aind]
202  b = self.angles[bind]
203  if np.abs(np.pi - he.ang_dist(a, b)) < self.ang_tr:
204  pairs.append([aind, bind])
205 
206  if pairs:
207  pairs = np.array(pairs)
208  pairs = np.unique(np.sort(pairs), axis=0)
209 
210  amp = np.max(self.pol_h) - np.min(self.pol_h)
211  self.comp = list()
212  for p in pairs:
213  a = self.pol_h[p[0]]
214  b = self.pol_h[p[1]]
215  if np.abs(a - b) / amp < self.amp_tr:
216  self.comp.append(p)
217  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
218  rospy.loginfo("[ROSE] Found directions.....{}".format(len(self.comp)))
219 
220  for p in self.comp:
221  p0 = self.angles[p[0]]
222  p1 = self.angles[p[1]]
223  p0 += np.pi / 2
224  p1 += np.pi / 2
225  p0 = p0 % (2 * np.pi)
226  p1 = p1 % (2 * np.pi)
227  p0 = np.pi - p0
228  p1 = np.pi - p1
229  self.main_directions.append(p0)
230  self.main_directions.append(p1)
231  rospy.loginfo("[ROSE] Score map.....")
232  t = time.time()
233  if not self.comp or len(self.comp) == 1:
234  pass
235  else:
236  diag = 10
237  mask_all = np.zeros(self.norm_ft_image.shape)
238 
239  min_l = (self.binary_map.shape[0] if self.binary_map.shape[0] < self.binary_map.shape[1] else
240  self.binary_map.shape[1]) / 2 - (self.binary_map.shape[0] if self.binary_map.shape[0] >
241  self.binary_map.shape[1] else
242  self.binary_map.shape[1])
243  max_l = (self.binary_map.shape[0] if self.binary_map.shape[0] > self.binary_map.shape[1] else
244  self.binary_map.shape[1]) / 2 + (self.binary_map.shape[0] if self.binary_map.shape[0] >
245  self.binary_map.shape[1] else
246  self.binary_map.shape[1])
247 
248  for p in self.comp:
249  x1, y1 = he.pol2cart(diag, self.angles[p[0]] + np.pi / 2.0)
250  x2, y2 = he.pol2cart(diag, self.angles[p[1]] + np.pi / 2.0)
251 
252  x1 = x1 + self.binary_map.shape[0] / 2.0
253  x2 = x2 + self.binary_map.shape[0] / 2.0
254 
255  y1 = y1 + self.binary_map.shape[1] / 2.0
256  y2 = y2 + self.binary_map.shape[1] / 2.0
257 
258  a = y2 - y1
259  b = x1 - x2
260  c = a * x1 + b * y1
261  c1 = c + self.par
262  c2 = c - self.par
263 
264 
265  X1_l = min_l
266  Y1_l = (c - a * X1_l) / b
267  X2_l = max_l
268  Y2_l = (c - a * X2_l) / b
269 
270  X1 = 0
271  Y1 = (c - a * X1) / b
272  X2 = self.binary_map.shape[0]
273  Y2 = (c - a * X2) / b
274 
275  X1_1 = 0
276  Y1_1 = (c1 - a * X1_1) / b
277  X2_1 = self.binary_map.shape[0]
278  Y2_1 = (c1 - a * X2_1) / b
279 
280  X1_2 = 0
281  Y1_2 = (c2 - a * X1_2) / b
282  X2_2 = self.binary_map.shape[0]
283  Y2_2 = (c2 - a * X2_2) / b
284 
285 
286  Y_org = Y1
287 
288  if np.abs(Y_org) > 3 * np.max(self.binary_map.shape):
289 
290  Y1_l = min_l
291  X1_l = (c - b * Y1_l) / a
292  Y2_l = max_l
293  X2_l = (c - b * Y2_l) / a
294 
295  Y1 = 0
296  X1 = (c - b * Y1) / a
297  Y2 = self.binary_map.shape[1]
298  X2 = (c - b * Y2) / a
299 
300  Y1_1 = 0
301  X1_1 = (c1 - b * Y1_1) / a
302  Y2_1 = self.binary_map.shape[1]
303  X2_1 = (c1 - b * Y2_1) / a
304 
305  Y1_2 = 0
306  X1_2 = (c2 - b * Y1_2) / a
307  Y2_2 = self.binary_map.shape[1]
308  X2_2 = (c2 - b * Y2_2) / a
309 
310  if max(X1_l, X2_l) < max(Y1_l, Y2_l):
311  self.lines_long_v.append([X1_l, Y1_l, X2_l, Y2_l])
312 
313  else:
314  self.lines_long_h.append([X1_l, Y1_l, X2_l, Y2_l])
315 
316  self.lines.append([X1, Y1, X2, Y2])
317 
318  mask_l = self.generate_mask(X1_1, Y1_1, X2_1, Y2_1, X1_2, Y1_2, X2_2, Y2_2, Y_org)
319 
320  if not np.any(mask_l == 1):
321  mask_l = self.generate_mask(X1_2, Y1_2, X2_2, Y2_2, X1_1, Y1_1, X2_1, Y2_1, Y_org)
322 
323  self.part_mask.append(mask_l)
324  l_mask_ftimage = self.ft_image * mask_l
325  l_mask_iftimage = np.fft.ifft2(l_mask_ftimage)
326  self.part_reconstruction.append(np.abs(l_mask_iftimage))
327  l_map_scored_good = np.abs(l_mask_iftimage) * (self.binary_map * 1)
328  self.part_score.append(l_map_scored_good)
329 
330  mask_all = np.logical_or(mask_all, mask_l)
331  mask_ftimage_l = self.ft_image * mask_l
332  mask_iftimage_l = np.fft.ifft2(mask_ftimage_l)
333  sm_l = np.abs(mask_iftimage_l) * (self.binary_map * 1)
334  sm_l = sm_l / np.max(sm_l)
335 
336  mask_all = np.flipud(mask_all)
337  mask_all_inv = np.ones(mask_all.shape)
338  mask_all_inv[mask_all == 1] = 0
339  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
340 
341  self.mask_ft_image = self.ft_image * mask_all
342  mask_iftimage = np.fft.ifft2(self.mask_ft_image)
343 
344  self.mask_inv_ft_image = self.ft_image * mask_all_inv
345  mask_inv_iftimage = np.fft.ifft2(self.mask_inv_ft_image)
346 
347  self.map_scored_good = np.abs(mask_iftimage) * (self.binary_map * 1)
348  self.map_scored_bad = np.abs(mask_inv_iftimage) * (self.binary_map * 1)
349 
351 
352  self.map_split_good_t = np.zeros(self.binary_map.shape)
353  self.map_split_good_t[self.map_scored_good > self.map_scored_bad] = 1
354  self.map_split_good = np.zeros(self.binary_map.shape)
355  self.map_split_good[self.binary_map] = self.map_split_good_t[self.binary_map]
356 
357  self.ft_image_split = np.fft.fftshift(np.fft.fft2(self.map_split_good))
358 
359  def simple_filter_map(self, tr):
360  rospy.loginfo("[ROSE] Simple filter map.....")
361  t = time.time()
362  l_map = np.array(np.abs(self.map_scored_good) / np.max(np.abs(self.map_scored_good)))
364  self.analysed_map = self.binary_map.copy()
365  self.analysed_map[l_map < self.quality_threshold] = 0.0
366  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
367 
369  rospy.loginfo("[ROSE] Histogram filter map.....")
370  t = time.time()
371  pixels = np.abs(self.map_scored_good[self.binary_map > 0])
372 
373  clf = mixture.GaussianMixture(n_components=2)
374  clf.fit(pixels.ravel().reshape(-1, 1))
375  self.pixel_quality_gmm = {"means": clf.means_, "weights": clf.weights_, "covariances": clf.covariances_}
376 
377  bins, edges = np.histogram(pixels.ravel(), density=True)
378  self.pixel_quality_histogram = {"bins": bins, "edges": edges,
379  "centers": [(a + b) / 2 for a, b in zip(edges[:-1], edges[1:])],
380  "width": [(a - b) for a, b in zip(edges[:-1], edges[1:])]}
381 
382  x = np.arange(np.min(self.pixel_quality_histogram["edges"]), np.max(self.pixel_quality_histogram["edges"]), (
383  np.max(self.pixel_quality_histogram["edges"]) - np.min(
384  self.pixel_quality_histogram["edges"])) / 1000)
385  if self.pixel_quality_gmm["means"][0] < self.pixel_quality_gmm["means"][1]:
386  y_b = stats.norm.pdf(x, self.pixel_quality_gmm["means"][0],
387  math.sqrt(self.pixel_quality_gmm["covariances"][0])) * \
388  self.pixel_quality_gmm["weights"][0]
389  y_g = stats.norm.pdf(x, self.pixel_quality_gmm["means"][1],
390  math.sqrt(self.pixel_quality_gmm["covariances"][1])) * \
391  self.pixel_quality_gmm["weights"][1]
392  else:
393  y_g = stats.norm.pdf(x, self.pixel_quality_gmm["means"][0],
394  math.sqrt(self.pixel_quality_gmm["covariances"][0])) * \
395  self.pixel_quality_gmm["weights"][0]
396  y_b = stats.norm.pdf(x, self.pixel_quality_gmm["means"][1],
397  math.sqrt(self.pixel_quality_gmm["covariances"][1])) * \
398  self.pixel_quality_gmm["weights"][1]
399 
400  ind = np.argmax(y_g > y_b)
401  self.cluster_quality_threshold = x[ind]
402 
403  self.analysed_map = self.binary_map.copy()
404  self.analysed_map[np.abs(self.map_scored_good) < self.cluster_quality_threshold] = 0.0
405  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
406 
407  def generate_initial_hypothesis_direction_with_kde(self, lines_long, max_len, bandwidth, cutoff_percent, cell_tr,
408  V):
409  d_row_ret = []
410  slices_ids = []
411  slices = []
412  cell_hypothesis = []
413  lines_hypothesis = []
414  kde_hypothesis = []
415  kde_hypothesis_cut = []
416  slices_dir = []
417 
418  for l in lines_long:
419  temp_slice = []
420  for s in np.arange(-1 * max_len, max_len, 1):
421  if V:
422  rr, cc = sk_draw.line(int(round(l[0] + s)), int(round(l[3])), int(round(l[2] + s)),
423  int(round(l[1])))
424  elif not V:
425  rr, cc = sk_draw.line(int(round(l[0])), int(round(l[3] + s)), int(round(l[2])),
426  int(round(l[1] + s)))
427 
428  else:
429  rospy.loginfo("[ROSE] ERROR")
430 
431  rr_flag = (np.logical_or(rr < 0, rr >= self.analysed_map.shape[1]))
432  cc_flag = (np.logical_or(cc < 0, cc >= self.analysed_map.shape[0]))
433  flag = np.logical_not(np.logical_or(rr_flag, cc_flag))
434  new_row = True
435  if np.sum(self.analysed_map[cc[flag], rr[flag]] * 1) > 1:
436  # adavnced hypothesisi generation
437  row = self.analysed_map[cc[flag], rr[flag]] * 1
438 
439  t_row = np.ones(row.shape) - row
440  d_row = ndimage.distance_transform_cdt(t_row)
441  d_row = max_len - d_row
442  d_row = d_row.reshape(-1, 1)
443  # self.d_row_v.append(d_row)
444  d_row_ret.append(d_row)
445  kde = KernelDensity(kernel='gaussian', bandwidth=bandwidth).fit(d_row)
446  # cut the gaps
447  temp_row_full = np.exp(kde.score_samples(d_row))
448  temp_row_cut = temp_row_full.copy()
449  temp_row_cut[temp_row_full < cutoff_percent * min(np.exp(kde.score_samples(d_row)))] = 0
450 
451  l_slice_ids = []
452  pt = 0
453  for i, t in enumerate(temp_row_cut):
454  if t == 0 and pt == 0:
455  pt = t
456  elif pt == 0 and t != 0:
457  ts = []
458  ts.append(i)
459  pt = t
460  elif pt != 0 and t != 0:
461  ts.append(i)
462  pt = t
463  elif t == 0 and pt != 0:
464  l_slice_ids.append(ts)
465  ts = []
466  pt = t
467 
468  cc_f = cc[flag]
469  rr_f = rr[flag]
470 
471  cc_slices = []
472  rr_slices = []
473 
474  for tslice in l_slice_ids:
475  if len(tslice) > cell_tr:
476  cc_s = []
477  rr_s = []
478  for i in tslice:
479  cc_s.append(cc_f[i])
480  rr_s.append(rr_f[i])
481  cc_slices.append(cc_s)
482  rr_slices.append(rr_s)
483 
484  temp_slice.append((cc_slices, rr_slices))
485 
486  slices_ids.append((cc_slices, rr_slices))
487 
488  slices.append((cc_slices, rr_slices))
489  if new_row:
490 
491  cell_hypothesis.append((cc[flag], rr[flag]))
492  if V:
493  lines_hypothesis.append([l[0] + s, l[1], l[2] + s, l[3]])
494  elif not V:
495  lines_hypothesis.append([l[0], l[1] + s, l[2], l[3] + s])
496  else:
497  rospy.loginfo("[ROSE] ERROR")
498  kde_hypothesis.append(temp_row_full)
499  kde_hypothesis_cut.append(temp_row_cut)
500  new_row = False
501 
502  slices_dir.append(temp_slice)
503  return d_row_ret, slices_ids, slices, cell_hypothesis, lines_hypothesis, kde_hypothesis, kde_hypothesis_cut, slices_dir
504 
505  def generate_initial_hypothesis_direction_simple(self, lines_long, max_len, padding, cell_tr, V):
506  d_row_ret = []
507  slices_ids = []
508  slices = []
509  cell_hypothesis = []
510  lines_hypothesis = []
511  kde_hypothesis = []
512  kde_hypothesis_cut = []
513  slices_dir = []
514 
515  for l in lines_long:
516  temp_slice = []
517  for s in np.arange(-1 * max_len, max_len, 1):
518  if V:
519  rr, cc = sk_draw.line(int(round(l[0] + s)), int(round(l[3])), int(round(l[2] + s)),
520  int(round(l[1])))
521  elif not V:
522  rr, cc = sk_draw.line(int(round(l[0])), int(round(l[3] + s)), int(round(l[2])),
523  int(round(l[1] + s)))
524 
525  else:
526  rospy.loginfo("[ROSE] ERROR")
527 
528  rr_flag = (np.logical_or(rr < 0, rr >= self.analysed_map.shape[1]))
529  cc_flag = (np.logical_or(cc < 0, cc >= self.analysed_map.shape[0]))
530  flag = np.logical_not(np.logical_or(rr_flag, cc_flag))
531  new_row = True
532  if np.sum(self.analysed_map[cc[flag], rr[flag]] * 1) > 1:
533  # adavnced hypothesisi generation
534 
535 
536  row = self.analysed_map[cc[flag], rr[flag]]
537  row.shape = (row.shape[0], 1)
538  temp_row_full = binary_dilation(row, footprint=np.ones((padding, padding)))
539  temp_row_full = temp_row_full * 1
540  temp_row_cut = temp_row_full.copy()
541 
542  # t_row = np.ones(row.shape) - row
543  # d_row = ndimage.distance_transform_cdt(t_row)
544  # d_row = max_len - d_row
545  # d_row = d_row.reshape(-1, 1)
546  # # self.d_row_v.append(d_row)
547  # d_row_ret.append(d_row)
548  # kde = KernelDensity(kernel='gaussian', bandwidth=bandwidth).fit(d_row)
549  # # cut the gaps
550  # temp_row_full = np.exp(kde.score_samples(d_row))
551  # temp_row_cut = temp_row_full.copy()
552  # temp_row_cut[temp_row_full < cutoff_percent * min(np.exp(kde.score_samples(d_row)))] = 0
553 
554  l_slice_ids = []
555  pt = 0
556  for i, t in enumerate(temp_row_cut):
557  if t == 0 and pt == 0:
558  pt = t
559  elif pt == 0 and t != 0:
560  ts = []
561  ts.append(i)
562  pt = t
563  elif pt != 0 and t != 0:
564  ts.append(i)
565  pt = t
566  elif t == 0 and pt != 0:
567  l_slice_ids.append(ts)
568  ts = []
569  pt = t
570 
571  cc_f = cc[flag]
572  rr_f = rr[flag]
573 
574  cc_slices = []
575  rr_slices = []
576 
577  for tslice in l_slice_ids:
578  if len(tslice) > cell_tr:
579  cc_s = []
580  rr_s = []
581  for i in tslice:
582  cc_s.append(cc_f[i])
583  rr_s.append(rr_f[i])
584  cc_slices.append(cc_s)
585  rr_slices.append(rr_s)
586 
587  temp_slice.append((cc_slices, rr_slices))
588 
589  slices_ids.append((cc_slices, rr_slices))
590 
591  slices.append((cc_slices, rr_slices))
592  if new_row:
593 
594  cell_hypothesis.append((cc[flag], rr[flag]))
595  if V:
596  lines_hypothesis.append([l[0] + s, l[1], l[2] + s, l[3]])
597  elif not V:
598  lines_hypothesis.append([l[0], l[1] + s, l[2], l[3] + s])
599  else:
600  rospy.loginfo("[ROSE] ERROR")
601  kde_hypothesis.append(temp_row_full)
602  kde_hypothesis_cut.append(temp_row_cut)
603  new_row = False
604 
605  slices_dir.append(temp_slice)
606  return d_row_ret, slices_ids, slices, cell_hypothesis, lines_hypothesis, kde_hypothesis, kde_hypothesis_cut, slices_dir
607 
609  rospy.loginfo("[ROSE] Generate initial hypothesis with kde.....")
610  t = time.time()
611  max_len = 5000
612  bandwidth = 0.00005
613  cutoff_percent = 15
614  cell_tr = 20 # 5
616  self.lines_long_v, max_len, bandwidth, cutoff_percent, cell_tr, True)
618  self.lines_long_h, max_len, bandwidth, cutoff_percent, cell_tr, False)
619  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
620 
622  rospy.loginfo("[ROSE] Generate initial hypothesis simple.....")
623  t = time.time()
624  max_len = 5000
625  padding = 1
626 
627  cell_tr = 10 # 5
629  self.lines_long_v, max_len, padding, cell_tr, True)
631  self.lines_long_h, max_len, padding, cell_tr, False)
632  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
633 
635  rospy.loginfo("[ROSE] Find Walls with flood filing.....")
636  t = time.time()
637  self.labeled_map = np.zeros(self.binary_map.shape)
638  id = 2
639  for s in self.slices_v_dir:
640  local_segments = []
641  temp_map = np.zeros(self.binary_map.shape)
642  for p in s:
643  for q in zip(p[0], p[1]):
644  temp_map[q[0], q[1]] = 1
645 
646  temp_map_fill = temp_map.copy()
647  filled = False
648  while not filled:
649  seed = np.argwhere(temp_map_fill == 1)
650 
651  if seed.size != 0:
652  temp_map_fill = flood_fill(temp_map_fill, (seed[0][0], seed[0][1]), id)
653  id = id + 1
654  else:
655  filled = True
656 
657  local_segment = sh.Segment()
658  cluster = np.where(temp_map_fill == id - 1)
659  cluster = np.column_stack((cluster[0], cluster[1]))
660  local_segment.add_cells(cluster)
661  local_segment.compute_hull()
662  local_segment.compute_mbb()
663  local_segment.id = id
664  local_segments.append(local_segment)
665  self.segments_v.append(local_segments)
666  self.labeled_map = self.labeled_map + temp_map_fill
667  local_mbb_lines = []
668  for l_segment in local_segments:
669  x1, y1 = l_segment.center
670  x2, y2 = l_segment.center[0] + l_segment.rectangle_direction[0], l_segment.center[1] + \
671  l_segment.rectangle_direction[1]
672  a = y2 - y1
673  b = x1 - x2
674  c = a * (x1) + b * (y1)
675  if not b == 0:
676  X1 = 0
677  Y1 = (c - a * X1) / b
678  X2 = self.binary_map.shape[0]
679  Y2 = (c - a * X2) / b
680  if np.abs(Y1) > 3 * np.max(self.binary_map.shape) or b == 0:
681 
682  Y1 = 0
683  X1 = (c - b * Y1) / a
684  Y2 = self.binary_map.shape[1]
685  X2 = (c - b * Y2) / a
686 
687  local_mbb_lines.append({"X1": X1, "X2": X2, "Y1": Y1, "Y2": Y2})
688  self.all_lines.append(((X1, Y1), (X2, Y2)))
689  self.segments_v_mbb_lines.append(local_mbb_lines)
690 
691  for s in self.slices_h_dir:
692  local_segments = []
693  temp_map = np.zeros(self.binary_map.shape)
694  for p in s:
695  for q in zip(p[0], p[1]):
696  temp_map[q[0], q[1]] = 1
697  temp_map_fill = temp_map.copy()
698  filled = False
699  while not filled:
700  seed = np.argwhere(temp_map_fill == 1)
701  if seed.size != 0:
702  temp_map_fill = flood_fill(temp_map_fill, (seed[0][0], seed[0][1]), id)
703  id = id + 1
704  else:
705  filled = True
706  local_segment = sh.Segment()
707  cluster = np.where(temp_map_fill == id - 1)
708  cluster = np.column_stack((cluster[0], cluster[1]))
709  local_segment.add_cells(cluster)
710  local_segment.compute_hull()
711  local_segment.compute_mbb()
712  local_segment.id = id
713  local_segments.append(local_segment)
714  self.segments_h.append(local_segments)
715  self.labeled_map = self.labeled_map + temp_map_fill
716  local_mbb_lines = []
717  for l_segment in local_segments:
718  x1, y1 = l_segment.center
719  x2, y2 = l_segment.center[0] + l_segment.rectangle_direction[0], l_segment.center[1] + \
720  l_segment.rectangle_direction[1]
721  a = y2 - y1
722  b = x1 - x2
723  c = a * (x1) + b * (y1)
724  if not b == 0:
725  X1 = 0
726  Y1 = (c - a * X1) / b
727  X2 = self.binary_map.shape[0]
728  Y2 = (c - a * X2) / b
729  if np.abs(Y1) > 3 * np.max(self.binary_map.shape) or b == 0:
730 
731  Y1 = 0
732  X1 = (c - b * Y1) / a
733  Y2 = self.binary_map.shape[1]
734  X2 = (c - b * Y2) / a
735 
736  local_mbb_lines.append({"X1": X1, "X2": X2, "Y1": Y1, "Y2": Y2})
737  self.all_lines.append(((X1, Y1), (X2, Y2)))
738  self.segments_h_mbb_lines.append(local_mbb_lines)
739  self.all_lines = list(dict.fromkeys(self.all_lines))
740  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
741 
743  rospy.loginfo("[ROSE] Find Walls with line segment clustering.....")
744  t = time.time()
745  eps = 10
746  min_samples = 2
747  if len(self.slices_h_dir) is not 0:
748  for direction in self.slices_h_dir:
749  slice_lines = generate_line_segments_per_direction(direction)
750  clustering_h = DBSCAN(eps=eps, min_samples=min_samples,
751  metric=he.shortest_distance_between_segements).fit(
752  slice_lines)
753  self.slice_h_lines.append(slice_lines)
754  self.clustering_h_labels.append(clustering_h.labels_)
755 
756  if len(self.slices_v_dir) is not 0:
757  for direction in self.slices_v_dir:
758  slice_lines = generate_line_segments_per_direction(direction)
759  clustering_v = DBSCAN(eps=eps, min_samples=min_samples,
760  metric=he.shortest_distance_between_segements).fit(
761  slice_lines)
762  self.slice_v_lines.append(slice_lines)
763  self.clustering_v_labels.append(clustering_v.labels_)
764 
765  id = 2
766  temp_map = np.zeros(self.binary_map.shape)
767 
768  last_label = 0
769  for slice, label in zip(self.slices_h_dir, self.clustering_h_labels):
770  if last_label != label:
771  id = id + 1
772  for s in zip(slice[0][0], slice[1][0]):
773  temp_map[s[0]][s[1]] = id
774  last_label = label
775  last_label = 0
776  for slice, label in zip(self.slices_v_dir, self.clustering_v_labels):
777  if last_label != label:
778  id = id + 1
779  for s in zip(slice[0][0], slice[1][0]):
780  temp_map[s[0]][s[1]] = id
781  last_label = label
782  self.labeled_map_line_segment = temp_map
783  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
784 
785  # output
786 
787  def report(self):
788  for p in self.comp:
789  rospy.loginfo("[ROSE] dir:", self.angles[p[0]] * 180.0 / np.pi, self.angles[p[1]] * 180.0 / np.pi)
790 
791  def show(self, visualisation, path, shape, format='.png'):
792  rospy.loginfo("[ROSE] Generating visualisation.....")
793  t = time.time()
794 
795  if visualisation["Binary map"]:
796  fig, ax = plt.subplots(nrows=1, ncols=1)
797  ax.imshow(self.binary_map * 1, cmap="gray")
798  ax.axis("off")
799  name = "Binary Map"
800  ax.set_title(name)
801  fig.canvas.set_window_title(name)
802  title = os.path.join(path, name + format)
803  plt.savefig(title)
804 
805  if visualisation["FFT Spectrum"]:
806  fig, ax = plt.subplots(nrows=1, ncols=1)
807  ax.imshow((np.abs(self.ft_image)), cmap="nipy_spectral")
808  ax.axis("off")
809  name = "FFT Spectrum"
810  ax.set_title(name)
811  fig.canvas.set_window_title(name)
812  title = os.path.join(path, name + format)
813  plt.savefig(title)
814 
815  if visualisation["FFT spectrum with directions"]:
816  fig, ax = plt.subplots(nrows=1, ncols=1)
817  ax.imshow((np.abs(self.ft_image)), cmap="nipy_spectral")
818  for l in self.lines:
819  ax.plot([l[1], l[3]], [l[0], l[2]])
820  ax.axis("off")
821  name = "FFT Spectrum with directions"
822  ax.set_title(name)
823  fig.canvas.set_window_title(name)
824  ax.set_xlim(0, self.ft_image.shape[1])
825  ax.set_ylim(0, self.ft_image.shape[0])
826  title = os.path.join(path, name + format)
827  plt.savefig(title)
828 
829  if visualisation["Map with walls"]:
830  fig, ax = plt.subplots(nrows=1, ncols=1)
831  ax.imshow(self.binary_map, cmap="gray")
832  for indices_slice in self.slices_v_ids:
833  for indices in zip(indices_slice[0], indices_slice[1]):
834  for i in zip(indices[0], indices[1]):
835  ax.plot(i[1], i[0], 'rx')
836  for indices_slice in self.slices_h_ids:
837  for indices in zip(indices_slice[0], indices_slice[1]):
838  for i in zip(indices[0], indices[1]):
839  ax.plot(i[1], i[0], 'rx')
840  ax.axis("off")
841  name = "Map with walls"
842  ax.set_title(name)
843  fig.canvas.set_window_title(name)
844  title = os.path.join(path, name + format)
845  plt.savefig(title)
846 
847  if visualisation["Map with directions"]:
848  fig, ax = plt.subplots(nrows=1, ncols=1)
849  ax.imshow(self.binary_map, cmap="gray")
850  for line in self.lines_hypothesis_v:
851  ax.plot([line[0], line[2]], [line[3], line[1]], alpha=0.5)
852  for line in self.lines_hypothesis_h:
853  ax.plot([line[0], line[2]], [line[3], line[1]], alpha=0.5)
854  for cells, values in zip(self.cell_hypothesis_v, self.scored_hypothesis_v):
855  ax.scatter(cells[1], cells[0], c='r', s=values * 100, alpha=0.5)
856  for cells, values in zip(self.cell_hypothesis_h, self.scored_hypothesis_h):
857  ax.scatter(cells[1], cells[0], c='r', s=values * 100, alpha=0.5)
858  for cells, values in zip(self.cell_hypothesis_v, self.scored_hypothesis_v_cut):
859  ax.scatter(cells[1], cells[0], c='g', s=values * 100, alpha=0.5)
860  for cells, values in zip(self.cell_hypothesis_h, self.scored_hypothesis_h_cut):
861  ax.scatter(cells[1], cells[0], c='g', s=values * 100, alpha=0.5)
862  ax.axis("off")
863  name = "Map with directions"
864  ax.set_title(name)
865  fig.canvas.set_window_title(name)
866  ax.set_xlim(0, self.binary_map.shape[1])
867  ax.set_ylim(self.binary_map.shape[0], 0)
868  title = os.path.join(path, name + format)
869  plt.savefig(title)
870 
871  if visualisation["Unfolded FFT Spectrum"]:
872  fig, ax = plt.subplots(1, 1)
873  ax.imshow(np.flipud(self.pol), cmap="nipy_spectral", aspect='auto',
874  extent=(np.min(self.angles), np.max(self.angles), 0, np.max(self.rads)))
875  ax.set_xlim([np.min(self.angles), np.max(self.angles)])
876  ax.set_xlabel("Orientation [rad]")
877  ax.set_ylabel("Radius in pixel")
878  ax2 = ax.twinx()
879  ax2.plot(self.angles, self.pol_h)
880  ax2.plot(self.angles[self.peak_indices], self.pol_h[self.peak_indices], 'r+')
881  for p in self.comp:
882  ax2.scatter(self.angles[p], self.pol_h[p], marker='^', s=120)
883  ax2.set_ylabel("Orientation score")
884  name = "Unfolded FFT Spectrum"
885  ax.set_title(name)
886  fig.canvas.set_window_title(name)
887  title = os.path.join(path, name + format)
888  plt.savefig(title)
889 
890  if visualisation["FFT Spectrum Signal"]:
891  fig, ax = plt.subplots(nrows=1, ncols=1)
892  ax.imshow((np.abs(self.mask_ft_image)), cmap="nipy_spectral")
893  ax.axis("off")
894  name = "FFT Spectrum Signal"
895  fig.canvas.set_window_title(name)
896  ax.set_title(name)
897  title = os.path.join(path, name + format)
898  plt.savefig(title)
899 
900  if visualisation["FFT Spectrum Noise"]:
901  fig, ax = plt.subplots(nrows=1, ncols=1)
902  ax.imshow((np.abs(self.mask_inv_ft_image)), cmap="nipy_spectral")
903  ax.axis("off")
904  name = "FFT Spectrum Noise"
905  fig.canvas.set_window_title(name)
906  ax.set_title(name)
907  title = os.path.join(path, name + format)
908  plt.savefig(title)
909 
910  if visualisation["Map Scored Good"]:
911  fig, ax = plt.subplots(nrows=1, ncols=1)
912  ax.imshow(np.abs(self.map_scored_good), cmap="plasma")
913  ax.axis("off")
914  name = "Map Scored Good"
915  fig.canvas.set_window_title(name)
916  ax.set_title(name)
917  title = os.path.join(path, name + format)
918  plt.savefig(title)
919 
920  if visualisation["Map Scored Bad"]:
921  fig, ax = plt.subplots(nrows=1, ncols=1)
922  ax.imshow(np.abs(self.map_scored_bad), cmap="plasma")
923  ax.axis("off")
924  name = "Map Scored Bad"
925  fig.canvas.set_window_title(name)
926  ax.set_title(name)
927  title = os.path.join(path, name + format)
928  plt.savefig(title)
929 
930  if visualisation["Map Scored Diff"]:
931  fig, ax = plt.subplots(nrows=1, ncols=1)
932  ax.imshow(np.abs(self.map_scored_diff), cmap="plasma")
933  ax.axis("off")
934  name = "Map Scored Diff"
935  fig.canvas.set_window_title(name)
936  ax.set_title(name)
937  title = os.path.join(path, name + format)
938  plt.savefig(title)
939 
940  if visualisation["Map Split Good"]:
941  fig, ax = plt.subplots(nrows=1, ncols=1)
942  ax.imshow(self.map_split_good, cmap="plasma")
943  ax.axis("off")
944  name = "Map Split Good"
945  fig.canvas.set_window_title(name)
946  ax.set_title(name)
947  title = os.path.join(path, name + format)
948  plt.savefig(title)
949 
950  if visualisation["FFT Map Split Good"]:
951  fig, ax = plt.subplots(nrows=1, ncols=1)
952  ax.imshow((np.abs(self.ft_image_split)), cmap="nipy_spectral")
953  ax.axis("off")
954  name = "FFT Map Split Good"
955  fig.canvas.set_window_title(name)
956  ax.set_title(name)
957  title = os.path.join(path, name + format)
958  plt.savefig(title)
959 
960  if visualisation["Side by Side"]:
961  fig, ax = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True)
962  ax[0].imshow(self.binary_map * 1, cmap="gray")
963  ax[0].axis("off")
964  ax[1].imshow(np.abs(self.map_scored_good), cmap="nipy_spectral")
965  ax[1].axis("off")
966  name1 = "Map"
967  name2 = "Score"
968  fig.canvas.set_window_title("Map Quality assessment")
969  ax[0].set_title(name1)
970  ax[1].set_title(name2)
971  plt.tight_layout()
972  plt.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0, wspace=0, hspace=0)
973  title = os.path.join(path, name + format)
974  plt.savefig(title)
975 
976  if visualisation["Simple Filtered Map"]:
977  fig, ax = plt.subplots(nrows=1, ncols=1)
978  ax.imshow(self.binary_map, cmap="gray")
979  non_zero_ind = np.nonzero(self.analysed_map)
980  for ind in zip(non_zero_ind[0], non_zero_ind[1]):
981  square = patches.Rectangle((ind[1], ind[0]), 1, 1, color='green')
982  ax.add_patch(square)
983  name = "Simple Filtered Map (" + str(self.quality_threshold) + ")"
984  ax.axis("off")
985  fig.canvas.set_window_title(name)
986  ax.set_title(name)
987  title = os.path.join(path, name + format)
988  plt.savefig(title)
989 
990  if visualisation["Threshold Setup with Clusters"]:
991  x = np.arange(np.min(self.pixel_quality_histogram["edges"]), np.max(self.pixel_quality_histogram["edges"]),
992  (np.max(self.pixel_quality_histogram["edges"]) - np.min(
993  self.pixel_quality_histogram["edges"])) / 1000)
994 
995  if self.pixel_quality_gmm["means"][0] < self.pixel_quality_gmm["means"][1]:
996  y_b = stats.norm.pdf(x, self.pixel_quality_gmm["means"][0],
997  math.sqrt(self.pixel_quality_gmm["covariances"][0])) * \
998  self.pixel_quality_gmm["weights"][0]
999  y_g = stats.norm.pdf(x, self.pixel_quality_gmm["means"][1],
1000  math.sqrt(self.pixel_quality_gmm["covariances"][1])) * \
1001  self.pixel_quality_gmm["weights"][1]
1002  else:
1003  y_g = stats.norm.pdf(x, self.pixel_quality_gmm["means"][0],
1004  math.sqrt(self.pixel_quality_gmm["covariances"][0])) * \
1005  self.pixel_quality_gmm["weights"][0]
1006  y_b = stats.norm.pdf(x, self.pixel_quality_gmm["means"][1],
1007  math.sqrt(self.pixel_quality_gmm["covariances"][1])) * \
1008  self.pixel_quality_gmm["weights"][1]
1009 
1010  fig, ax = plt.subplots(nrows=1, ncols=1)
1011  ax.bar(self.pixel_quality_histogram["centers"], self.pixel_quality_histogram["bins"],
1012  width=self.pixel_quality_histogram["width"])
1013  ax.plot(x, y_b, 'r')
1014  ax.plot(x, y_g, 'g')
1015  ax.axvline(x=self.cluster_quality_threshold, color='y')
1016  name = "Treshold Setup with Clusters"
1017  fig.canvas.set_window_title(name)
1018  ax.set_title(name)
1019  title = os.path.join(path, name + format)
1020  plt.savefig(title)
1021 
1022  if visualisation["Cluster Filtered Map"]:
1023  fig, ax = plt.subplots(nrows=1, ncols=1)
1024  ax.imshow(self.binary_map, cmap="gray")
1025  non_zero_ind = np.nonzero(self.analysed_map)
1026  for ind in zip(non_zero_ind[0], non_zero_ind[1]):
1027  square = patches.Rectangle((ind[1], ind[0]), 1, 1, color='green')
1028  ax.add_patch(square)
1029  name = "Cluster Filtered Map (" + str(self.cluster_quality_threshold) + ")"
1030  ax.axis("off")
1031  fig.canvas.set_window_title(name)
1032  ax.set_title(name)
1033  title = os.path.join(path, name + format)
1034  plt.savefig(title)
1035 
1036  if visualisation["Map with slices"]:
1037  fig, ax = plt.subplots(nrows=1, ncols=1)
1038  ax.imshow(self.binary_map, cmap="gray")
1039  for l in self.slices_v:
1040  for s in zip(l[0], l[1]):
1041  ax.plot(s[1], s[0], '.')
1042  for l in self.slices_h:
1043  for s in zip(l[0], l[1]):
1044  ax.plot(s[1], s[0], '.')
1045  ax.axis("off")
1046  name = "Map with slices"
1047  ax.set_title(name)
1048  fig.canvas.set_window_title(name)
1049  title = os.path.join(path, name + format)
1050  plt.savefig(title)
1051 
1052  if visualisation["Partial Scores"]:
1053  co = len(self.part_score)
1054  if co > 1:
1055  if co > 2:
1056  div = he.proper_divs2(int(co))
1057  if len(div) is 1:
1058  co = co + 1
1059  div = he.proper_divs2(int(co))
1060  div.add(int(co))
1061  div = list(div)
1062  div.sort()
1063  if len(div) % 2 == 0:
1064  nrows = div[int(len(div) / 2) - 1]
1065  ncols = div[int(len(div) / 2)]
1066  else:
1067  nrows = div[int(len(div) / 2)]
1068  ncols = div[int(len(div) / 2)]
1069  else:
1070  nrows = 1
1071  ncols = int(co)
1072  fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, sharey=True)
1073  i = 0
1074  for p in self.part_score:
1075  ax[int(i / ncols)][int(i % ncols)].imshow(p)
1076  ax[int(i / ncols)][int(i % ncols)].axis('off')
1077  i = i + 1
1078  name = "Partial Scores"
1079  fig.canvas.set_window_title(name)
1080  title = os.path.join(path, name + format)
1081  plt.savefig(title)
1082  elif co == 1:
1083  fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True)
1084  ax.imshow(self.part_score[0])
1085  ax.axis('off')
1086  name = "Partial Scores"
1087  fig.canvas.set_window_title(name)
1088  title = os.path.join(path, name + format)
1089  plt.savefig(title)
1090 
1091  if visualisation["Partial Reconstructs"]:
1092  co = len(self.part_reconstruction)
1093  if co > 1:
1094  if co > 2:
1095  div = he.proper_divs2(int(co))
1096  if len(div) is 1:
1097  co = co + 1
1098  div = he.proper_divs2(int(co))
1099  div.add(int(co))
1100  div = list(div)
1101  div.sort()
1102  if len(div) % 2 == 0:
1103  nrows = div[int(len(div) / 2) - 1]
1104  ncols = div[int(len(div) / 2)]
1105  else:
1106  nrows = div[int(len(div) / 2)]
1107  ncols = div[int(len(div) / 2)]
1108  else:
1109  nrows = 1
1110  ncols = int(co)
1111  fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, sharey=True)
1112  i = 0
1113  for p in self.part_reconstruction:
1114  ax[int(i / ncols)][int(i % ncols)].imshow(p)
1115  ax[int(i / ncols)][int(i % ncols)].axis('off')
1116  i = i + 1
1117  name = "Partial Reconstruct"
1118  fig.canvas.set_window_title(name)
1119  title = os.path.join(path, name + format)
1120  plt.savefig(title)
1121  elif co == 1:
1122  fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True)
1123  ax.imshow(self.part_reconstruction[0])
1124  ax.axis('off')
1125  name = "Partial Reconstruct"
1126  fig.canvas.set_window_title(name)
1127  title = os.path.join(path, name + format)
1128  plt.savefig(title)
1129 
1130  if visualisation["Wall lines from mbb"]:
1131  cmap = plt.cm.get_cmap("tab10")
1132  cmap.set_under("black")
1133  cmap.set_over("yellow")
1134  fig, ax = plt.subplots(nrows=1, ncols=1, sharey=True, sharex=True)
1135  ax.imshow(self.labeled_map, cmap=cmap, vmin=1)
1136  for local_segments, local_mbb_lines in zip(self.segments_h, self.segments_h_mbb_lines):
1137  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1138  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1139  if l_segment.mbb_area > 10:
1140  ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1141  for local_segments, local_mbb_lines in zip(self.segments_v, self.segments_v_mbb_lines):
1142  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1143  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1144  if l_segment.mbb_area > 10:
1145  ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1146  ax.set_xlim(0, self.binary_map.shape[1])
1147  ax.set_ylim(self.binary_map.shape[0], 0)
1148  ax.axis("off")
1149  name = "Wall lines from mbb"
1150  fig.canvas.set_window_title(name)
1151  title = os.path.join(path, name + format)
1152  plt.savefig(title)
1153 
1154  if visualisation["Short wall lines from mbb"]:
1155  cmap = plt.cm.get_cmap("tab10")
1156  cmap.set_under("black")
1157  cmap.set_over("yellow")
1158  fig, ax = plt.subplots(nrows=1, ncols=1, sharey=True, sharex=True)
1159  # ax[0].imshow(temp_map)
1160  ax.imshow(self.labeled_map, cmap=cmap, vmin=1)
1161  for local_segments, local_mbb_lines in zip(self.segments_h, self.segments_h_mbb_lines):
1162  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1163  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1164  wall=he.cetral_line(l_segment.minimal_bounding_box)
1165  ax.plot([wall[0].y, wall[1].y], [wall[0].x, wall[1].x], 'c')
1166  #if l_segment.mbb_area > 10:
1167  #ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1168  for local_segments, local_mbb_lines in zip(self.segments_v, self.segments_v_mbb_lines):
1169  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1170  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1171  wall = he.cetral_line(l_segment.minimal_bounding_box)
1172  ax.plot([wall[0].y, wall[1].y], [wall[0].x, wall[1].x], 'c')
1173  #if l_segment.mbb_area > 10:
1174  #ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1175  ax.set_xlim(0, self.binary_map.shape[1])
1176  ax.set_ylim(self.binary_map.shape[0], 0)
1177  ax.axis("off")
1178  name = "Short wall lines from mbb"
1179  fig.canvas.set_window_title(name)
1180  title = os.path.join(path, name + format)
1181  plt.savefig(title)
1182 
1183  if visualisation["Short wall lines over original map"]:
1184  fig, ax = plt.subplots(nrows=1, ncols=1, sharey=True, sharex=True)
1185  ax.imshow(self.binary_map, cmap="gray")
1186  for local_segments, local_mbb_lines in zip(self.segments_h, self.segments_h_mbb_lines):
1187  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1188  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1189  wall = he.cetral_line(l_segment.minimal_bounding_box)
1190  ax.plot([wall[0].y, wall[1].y], [wall[0].x, wall[1].x], 'c')
1191  # if l_segment.mbb_area > 10:
1192  # ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1193  for local_segments, local_mbb_lines in zip(self.segments_v, self.segments_v_mbb_lines):
1194  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1195  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1196  wall = he.cetral_line(l_segment.minimal_bounding_box)
1197  ax.plot([wall[0].y, wall[1].y], [wall[0].x, wall[1].x], 'c')
1198  # if l_segment.mbb_area > 10:
1199  # ax.plot([l_mbb_lines["Y1"], l_mbb_lines["Y2"]], [l_mbb_lines["X1"], l_mbb_lines["X2"]], 'g')
1200  ax.set_xlim(0, self.binary_map.shape[1])
1201  ax.set_ylim(self.binary_map.shape[0], 0)
1202  ax.axis("off")
1203  name = "Short wall lines over original map"
1204  fig.canvas.set_window_title(name)
1205  title = os.path.join(path, name + format)
1206  plt.savefig(title)
1207 
1208  if visualisation["Labels and Raw map"]:
1209  cmap = plt.cm.get_cmap("tab10")
1210  cmap.set_under("black")
1211  cmap.set_over("yellow")
1212  fig, ax = plt.subplots(nrows=1, ncols=1, sharey=True, sharex=True)
1213  ax.imshow(self.labeled_map, cmap=cmap, vmin=1)
1214  ax.imshow(self.binary_map, cmap="gray", alpha=0.5)
1215  for local_segments, local_mbb_lines in zip(self.segments_h, self.segments_h_mbb_lines):
1216  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1217  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1218  for local_segments, local_mbb_lines in zip(self.segments_v, self.segments_v_mbb_lines):
1219  for l_segment, l_mbb_lines in zip(local_segments, local_mbb_lines):
1220  ax.plot(l_segment.minimal_bounding_box[:, 1], l_segment.minimal_bounding_box[:, 0], 'r')
1221  ax.set_xlim(0, self.binary_map.shape[1])
1222  ax.set_ylim(self.binary_map.shape[0], 0)
1223  ax.axis("off")
1224  name = "Labels and Raw map"
1225  fig.canvas.set_window_title(name)
1226  title = os.path.join(path, name + format)
1227  plt.savefig(title)
1228 
1229  if visualisation["Raw line segments"]:
1230  fig, ax = plt.subplots(nrows=1, ncols=1, sharey=True, sharex=True)
1231  ax.imshow(self.binary_map, cmap="gray")
1232  for segment in self.slice_v_lines:
1233  ax.plot([segment[1], segment[3]], [segment[0], segment[2]])
1234 
1235  for segment in self.slice_h_lines:
1236  ax.plot([segment[1], segment[3]], [segment[0], segment[2]])
1237 
1238  name = "Raw line segments"
1239  fig.canvas.set_window_title(name)
1240 
1241  title = os.path.join(path, name + format)
1242  plt.savefig(title)
1243 
1244  rospy.loginfo("[ROSE] OK ({0:.2f})".format(time.time() - t))
fft_structure_extraction.FFTStructureExtraction.binary_map
binary_map
Definition: fft_structure_extraction.py:79
fft_structure_extraction.FFTStructureExtraction.map_scored_good
map_scored_good
Definition: fft_structure_extraction.py:97
fft_structure_extraction.FFTStructureExtraction.line_parameters
line_parameters
Definition: fft_structure_extraction.py:87
fft_structure_extraction.FFTStructureExtraction.segments_v
segments_v
Definition: fft_structure_extraction.py:48
fft_structure_extraction.FFTStructureExtraction.find_walls_flood_filing
def find_walls_flood_filing(self)
Definition: fft_structure_extraction.py:634
fft_structure_extraction.FFTStructureExtraction.d_row_h
d_row_h
Definition: fft_structure_extraction.py:67
fft_structure_extraction.FFTStructureExtraction.report
def report(self)
Definition: fft_structure_extraction.py:787
fft_structure_extraction.FFTStructureExtraction.generate_initial_hypothesis_direction_simple
def generate_initial_hypothesis_direction_simple(self, lines_long, max_len, padding, cell_tr, V)
Definition: fft_structure_extraction.py:505
fft_structure_extraction.FFTStructureExtraction.histogram_filtering
def histogram_filtering(self)
Definition: fft_structure_extraction.py:368
fft_structure_extraction.FFTStructureExtraction.simple_filter_map
def simple_filter_map(self, tr)
Definition: fft_structure_extraction.py:359
fft_structure_extraction.FFTStructureExtraction.ft_image
ft_image
Definition: fft_structure_extraction.py:102
fft_structure_extraction.FFTStructureExtraction.peak_indices
peak_indices
Definition: fft_structure_extraction.py:92
fft_structure_extraction.FFTStructureExtraction.norm_ft_image
norm_ft_image
Definition: fft_structure_extraction.py:88
fft_structure_extraction.FFTStructureExtraction.process_map
def process_map(self)
Definition: fft_structure_extraction.py:169
fft_structure_extraction.generate_line_segments_per_direction
def generate_line_segments_per_direction(slices)
Definition: fft_structure_extraction.py:23
fft_structure_extraction.FFTStructureExtraction.map_split_good
map_split_good
Definition: fft_structure_extraction.py:100
fft_structure_extraction.FFTStructureExtraction.pixel_quality_gmm
pixel_quality_gmm
Definition: fft_structure_extraction.py:84
fft_structure_extraction.FFTStructureExtraction.segments_h
segments_h
Definition: fft_structure_extraction.py:47
fft_structure_extraction.FFTStructureExtraction.slice_h_lines
slice_h_lines
Definition: fft_structure_extraction.py:42
fft_structure_extraction.FFTStructureExtraction.part_mask
part_mask
Definition: fft_structure_extraction.py:69
fft_structure_extraction.FFTStructureExtraction.slices_v_dir
slices_v_dir
Definition: fft_structure_extraction.py:50
fft_structure_extraction.FFTStructureExtraction.labeled_map_line_segment
labeled_map_line_segment
Definition: fft_structure_extraction.py:782
fft_structure_extraction.FFTStructureExtraction.compute_fft
def compute_fft(self)
Definition: fft_structure_extraction.py:132
fft_structure_extraction.FFTStructureExtraction.generate_initial_hypothesis_direction_with_kde
def generate_initial_hypothesis_direction_with_kde(self, lines_long, max_len, bandwidth, cutoff_percent, cell_tr, V)
Definition: fft_structure_extraction.py:407
fft_structure_extraction.FFTStructureExtraction.scored_hypothesis_h
scored_hypothesis_h
Definition: fft_structure_extraction.py:65
fft_structure_extraction.FFTStructureExtraction.amp_tr
amp_tr
Definition: fft_structure_extraction.py:73
fft_structure_extraction.FFTStructureExtraction.rads
rads
Definition: fft_structure_extraction.py:93
fft_structure_extraction.FFTStructureExtraction.slices_v_ids
slices_v_ids
Definition: fft_structure_extraction.py:51
fft_structure_extraction.FFTStructureExtraction.grid_map
grid_map
Definition: fft_structure_extraction.py:78
fft_structure_extraction.FFTStructureExtraction.slices_h_ids
slices_h_ids
Definition: fft_structure_extraction.py:52
fft_structure_extraction.FFTStructureExtraction.lines
lines
Definition: fft_structure_extraction.py:58
fft_structure_extraction.FFTStructureExtraction.map_split_good_t
map_split_good_t
Definition: fft_structure_extraction.py:103
fft_structure_extraction.save_simple_map
def save_simple_map(name, map_to_save, shape)
Definition: fft_structure_extraction.py:30
fft_structure_extraction.FFTStructureExtraction.pol
pol
Definition: fft_structure_extraction.py:89
fft_structure_extraction.FFTStructureExtraction.all_lines
all_lines
Definition: fft_structure_extraction.py:44
fft_structure_extraction.FFTStructureExtraction
Definition: fft_structure_extraction.py:37
fft_structure_extraction.FFTStructureExtraction.clustering_h_labels
clustering_h_labels
Definition: fft_structure_extraction.py:43
fft_structure_extraction.FFTStructureExtraction.shape
shape
Definition: fft_structure_extraction.py:104
fft_structure_extraction.FFTStructureExtraction.map_scored_diff
map_scored_diff
Definition: fft_structure_extraction.py:99
fft_structure_extraction.FFTStructureExtraction.slices_h
slices_h
Definition: fft_structure_extraction.py:54
fft_structure_extraction.FFTStructureExtraction.find_walls_with_line_segments
def find_walls_with_line_segments(self)
Definition: fft_structure_extraction.py:742
fft_structure_extraction.FFTStructureExtraction.lines_hypothesis_v
lines_hypothesis_v
Definition: fft_structure_extraction.py:64
fft_structure_extraction.FFTStructureExtraction.smooth
smooth
Definition: fft_structure_extraction.py:76
fft_structure_extraction.FFTStructureExtraction.lines_hypothesis_h
lines_hypothesis_h
Definition: fft_structure_extraction.py:63
fft_structure_extraction.FFTStructureExtraction.cell_hypothesis_v
cell_hypothesis_v
Definition: fft_structure_extraction.py:62
fft_structure_extraction.FFTStructureExtraction.pol_h
pol_h
Definition: fft_structure_extraction.py:91
fft_structure_extraction.FFTStructureExtraction.angles
angles
Definition: fft_structure_extraction.py:90
fft_structure_extraction.FFTStructureExtraction.sigma
sigma
Definition: fft_structure_extraction.py:77
fft_structure_extraction.FFTStructureExtraction.peak_height
peak_height
Definition: fft_structure_extraction.py:74
fft_structure_extraction.FFTStructureExtraction.slice_v_lines
slice_v_lines
Definition: fft_structure_extraction.py:41
fft_structure_extraction.FFTStructureExtraction.__init__
def __init__(self, grid_map, ang_tr=0.1, amp_tr=0.8, peak_height=0.5, par=200, smooth=False, sigma=3)
Definition: fft_structure_extraction.py:38
fft_structure_extraction.FFTStructureExtraction.scored_hypothesis_v_cut
scored_hypothesis_v_cut
Definition: fft_structure_extraction.py:55
fft_structure_extraction.FFTStructureExtraction.segments_v_mbb_lines
segments_v_mbb_lines
Definition: fft_structure_extraction.py:46
fft_structure_extraction.FFTStructureExtraction.part_score
part_score
Definition: fft_structure_extraction.py:70
fft_structure_extraction.FFTStructureExtraction.show
def show(self, visualisation, path, shape, format='.png')
Definition: fft_structure_extraction.py:791
fft_structure_extraction.FFTStructureExtraction.ang_tr
ang_tr
Definition: fft_structure_extraction.py:72
fft_structure_extraction.FFTStructureExtraction.scored_hypothesis_h_cut
scored_hypothesis_h_cut
Definition: fft_structure_extraction.py:56
fft_structure_extraction.FFTStructureExtraction.map_scored_bad
map_scored_bad
Definition: fft_structure_extraction.py:98
fft_structure_extraction.FFTStructureExtraction.generate_mask
def generate_mask(self, x1_1, y1_1, x2_1, y2_1, x1_2, y1_2, x2_2, y2_2, y_org)
Definition: fft_structure_extraction.py:142
fft_structure_extraction.FFTStructureExtraction.pixel_quality_histogram
pixel_quality_histogram
Definition: fft_structure_extraction.py:83
fft_structure_extraction.FFTStructureExtraction.lines_long_v
lines_long_v
Definition: fft_structure_extraction.py:60
fft_structure_extraction.FFTStructureExtraction.slices_v
slices_v
Definition: fft_structure_extraction.py:53
fft_structure_extraction.FFTStructureExtraction.labeled_map
labeled_map
Definition: fft_structure_extraction.py:637
fft_structure_extraction.FFTStructureExtraction.scored_hypothesis_v
scored_hypothesis_v
Definition: fft_structure_extraction.py:66
fft_structure_extraction.FFTStructureExtraction.slices_h_dir
slices_h_dir
Definition: fft_structure_extraction.py:49
fft_structure_extraction.FFTStructureExtraction.segments_h_mbb_lines
segments_h_mbb_lines
Definition: fft_structure_extraction.py:45
fft_structure_extraction.FFTStructureExtraction.part_reconstruction
part_reconstruction
Definition: fft_structure_extraction.py:57
fft_structure_extraction.FFTStructureExtraction.quality_threshold
quality_threshold
Definition: fft_structure_extraction.py:363
fft_structure_extraction.FFTStructureExtraction.generate_initial_hypothesis_with_kde
def generate_initial_hypothesis_with_kde(self)
Definition: fft_structure_extraction.py:608
fft_structure_extraction.FFTStructureExtraction.clustering_v_labels
clustering_v_labels
Definition: fft_structure_extraction.py:40
fft_structure_extraction.FFTStructureExtraction.generate_initial_hypothesis_simple
def generate_initial_hypothesis_simple(self)
Definition: fft_structure_extraction.py:621
fft_structure_extraction.FFTStructureExtraction.ft_image_split
ft_image_split
Definition: fft_structure_extraction.py:101
fft_structure_extraction.FFTStructureExtraction.cluster_quality_threshold
cluster_quality_threshold
Definition: fft_structure_extraction.py:85
fft_structure_extraction.FFTStructureExtraction.par
par
Definition: fft_structure_extraction.py:75
fft_structure_extraction.FFTStructureExtraction.d_row_v
d_row_v
Definition: fft_structure_extraction.py:68
fft_structure_extraction.FFTStructureExtraction.analysed_map
analysed_map
Definition: fft_structure_extraction.py:80
fft_structure_extraction.FFTStructureExtraction.load_map
def load_map(self, grid_map)
Definition: fft_structure_extraction.py:108
fft_structure_extraction.FFTStructureExtraction.cell_hypothesis_h
cell_hypothesis_h
Definition: fft_structure_extraction.py:61
fft_structure_extraction.FFTStructureExtraction.main_directions
main_directions
Definition: fft_structure_extraction.py:39
fft_structure_extraction.FFTStructureExtraction.mask_inv_ft_image
mask_inv_ft_image
Definition: fft_structure_extraction.py:96
fft_structure_extraction.FFTStructureExtraction.lines_long_h
lines_long_h
Definition: fft_structure_extraction.py:59
fft_structure_extraction.FFTStructureExtraction.comp
comp
Definition: fft_structure_extraction.py:94
fft_structure_extraction.FFTStructureExtraction.mask_ft_image
mask_ft_image
Definition: fft_structure_extraction.py:95


rose2
Author(s): Gabriele Somaschini, Matteo Luperto
autogenerated on Wed Jun 28 2023 02:21:53