tvaLib
Classes | Functions | Variables
lib.draw Namespace Reference

Classes

class  CamDataEntry
 
class  DataEntry
 Data entering tools. More...
 
class  SeqsDataEntry
 

Functions

def tellMe (s, console='', target=False)
 Drawinbg tools. More...
 
def drawMask (objects, sites, siteIx=0, camIx=0, fileIx=0, draw_max_traj=200, local=None, alternateView=False, autoUpdate=True, figsize=[15.0)
 
def drawZone (objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0)
 
def drawAlign (objects, sites, siteIx=0, draw_max_traj=200, local=None, autoUpdate=True, minPointDist=0.5, connectorSearchDistance=2.5, intersectionDistanceFactor=1.5, alpha=0.5, zorder=21, figsize=[15.0)
 
def drawBounds (objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0)
 
def autoBounds (objects, site_analyses, saIx=0, centile=2.0, max_outside_distance=10.0, inside_buffer=5.0, autoUpdate=True, verbose=0)
 
def drawLoops (objects, site_analyses, saIx=0, draw_max_traj=200, radius=3, colour='#D63E33', local=None, autoUpdate=True, figsize=[15.0)
 
def drawTransformation (objects, sequence, draw_max_traj=200, figsize=[15.0)
 
def drawAlignSnap (objects, site, draw_max_traj=200, local=None, figsize=[15.0)
 
def drawObjHighlight (objects, camera, draw_max_traj=200, local=None, arrow_every_dist=8.0, highlight_thickness=3.0, align_highlight_steps=5, figsize=[15.0)
 
def drawMastLocation (sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0)
 
def drawMastCalibration (objects, sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0)
 
def dataEntryCamType (cameraTypes, local)
 
def dataEntrySite (sites, config, local)
 
def dataEntryCameraView (sites, config, cameraTypes, local)
 
def dataEntrySequences (sites, local, allowed_extensions=['.mp4', avi)
 
def dataEntryAnalysis (analyses, local)
 
def dataEntrySA (sites, site_analyses, local)
 

Variables

 original_alignments
 
 alignments
 
 sidewalks
 
 bikepaths
 
 operation
 Draw alignments. More...
 
 minPointDist
 
 origin
 
 zorder
 
 pts
 
 pt_plot
 
 pt_arrows
 
 pt_plots
 
 connectors
 
 instruction
 
 console
 
 obj_traces
 Setup. More...
 

Function Documentation

◆ autoBounds()

def lib.draw.autoBounds (   objects,
  site_analyses,
  saIx = 0,
  centile = 2.0,
  max_outside_distance = 10.0,
  inside_buffer = 5.0,
  autoUpdate = True,
  verbose = 0 
)
Automatically create bounds from trajectory location and orthophoto. 

Definition at line 448 of file draw.py.

448 def autoBounds(objects, site_analyses, saIx=0, centile=2.0, max_outside_distance=10.0, inside_buffer=5.0, autoUpdate=True, verbose=0):
449  ''' Automatically create bounds from trajectory location and orthophoto. '''
450 
451 
452  x_mins = [min(obj.getXCoordinates()) for obj in objects]
453  x_maxs = [max(obj.getXCoordinates()) for obj in objects]
454  y_mins = [min(obj.getYCoordinates()) for obj in objects]
455  y_maxs = [max(obj.getYCoordinates()) for obj in objects]
456 
457  x_min = tvaLib.Math.getPercintileBinFromList(x_mins, percentile=centile)
458  x_max = tvaLib.Math.getPercintileBinFromList(x_maxs, percentile=100.0-centile)
459  y_min = tvaLib.Math.getPercintileBinFromList(y_mins, percentile=centile)
460  y_max = tvaLib.Math.getPercintileBinFromList(y_maxs, percentile=100.0-centile)
461 
462 
463  xy_bounds = [[x_min-inside_buffer,x_max+inside_buffer],[y_min-inside_buffer,y_max+inside_buffer]]
464 
465 
466  try:
467  img = mpimg.imread(site_analyses[saIx].site.getFullSatFilename())
468  x = int(img.shape[1]*site_analyses[saIx].site.satres)
469  y = int(img.shape[0]*site_analyses[saIx].site.satres)
470  if(xy_bounds[0][0] < -max_outside_distance): xy_bounds[0][0] = -max_outside_distance
471  if(xy_bounds[0][1] > x+max_outside_distance): xy_bounds[0][1] = x+max_outside_distance
472  if(xy_bounds[1][0] < -max_outside_distance): xy_bounds[1][0] = -max_outside_distance
473  if(xy_bounds[1][1] > y+max_outside_distance): xy_bounds[1][1] = y+max_outside_distance
474  except: pass
475 
476  if(verbose>=5): print(' Bounds set automatically to: '+str(xy_bounds))
477 
478  if(xy_bounds and autoUpdate):
479  site_analyses[saIx].xy_bounds = tvaLib.Constructors.SuperListParse(xy_bounds, datatype='bound')
480  site_analyses.update()
481  return
482 
483 
def autoBounds(objects, site_analyses, saIx=0, centile=2.0, max_outside_distance=10.0, inside_buffer=5.0, autoUpdate=True, verbose=0)
Definition: draw.py:448

◆ dataEntryAnalysis()

def lib.draw.dataEntryAnalysis (   analyses,
  local 
)

Definition at line 1064 of file draw.py.

1064 def dataEntryAnalysis(analyses, local):
1065  from collections import OrderedDict
1066  entries = DataEntry('Enter analysis details:', submit_label=local['UI_form_add'], rows=OrderedDict([('name',''), ('site_analyses','[]')]))
1067  if(not entries.submit): return False
1068  analyses.new(sqlFields=entries.getEntries())
1069  return True
1070 
def dataEntryAnalysis(analyses, local)
Definition: draw.py:1064

◆ dataEntryCameraView()

def lib.draw.dataEntryCameraView (   sites,
  config,
  cameraTypes,
  local 
)

Definition at line 998 of file draw.py.

998 def dataEntryCameraView(sites, config, cameraTypes, local):
999  from collections import OrderedDict
1000 
1001  missings = []
1002  for site in sites:
1003  if(not site.data): missings.append(site.name)
1004  if(missings):
1005  print 'The following site/camera views are missing sequence data and need to be completed:'
1006  for missing in missings: print ''.ljust(4,' ')+missing
1007 
1008  dropdowns = {'cameraId':OrderedDict()}
1009  for camtype in cameraTypes: dropdowns['cameraId'][camtype.name] = camtype.idx
1010  entries = CamDataEntry('Enter camera view details:', submit_label=local['UI_form_add'], rows=OrderedDict([('name',''), ('homographyFilename','homography-undistort.txt'), ('homographyDistanceUnit','m'), ('cameraCalibrationFilename',''), ('configurationFilename',''), ('maskFilename','mask.png'), ('camOrigin',''), ('camHeight','10.0')]), sites=sites, config=config, dropdowns=dropdowns)
1011  if(not entries.submit): return False
1012  ddVals = entries.getDropDowns()
1013  if(not entries.getEntries()['name']):
1014  site = entries.getSelectedSite()
1015  for path in sorted([x[0] for x in os.walk(os.path.join(sites.getBaseDirectory(), site.name))]):
1016  if(path != os.path.join(sites.getBaseDirectory(), site.name) and len([x[0] for x in os.walk(path)])==1):
1017  entries.setEntry('name', str(os.path.relpath(path, start=os.path.join(sites.getBaseDirectory(), site.name))).replace('\\\\','\\').replace('\\','/'))
1018  entries.getSelectedSite().new(entries.getSiteSelection(), dropdowns['cameraId'][ddVals['cameraId']], sites.session, sqlFields=entries.getEntries())
1019  else:
1020  entries.getSelectedSite().new(entries.getSiteSelection(), dropdowns['cameraId'][ddVals['cameraId']], sites.session, sqlFields=entries.getEntries())
1021  return True
1022 
def dataEntryCameraView(sites, config, cameraTypes, local)
Definition: draw.py:998

◆ dataEntryCamType()

def lib.draw.dataEntryCamType (   cameraTypes,
  local 
)

Definition at line 976 of file draw.py.

976 def dataEntryCamType(cameraTypes, local):
977  from collections import OrderedDict
978  entries = DataEntry('Enter camera type details:', submit_label=local['UI_form_add'], rows=OrderedDict([('name',''), ('resX',''), ('resY',''), ('frameRate',''), ('camera_matrix',''), ('dist_coeffs',''), ('FOV','1'), ('freeScalingParameter',''), ('imageScalingFactor','')]))
979  if(not entries.submit): return False
980  cameraTypes.new(sqlFields=entries.getEntries())
981  return True
982 
def dataEntryCamType(cameraTypes, local)
Definition: draw.py:976

◆ dataEntrySA()

def lib.draw.dataEntrySA (   sites,
  site_analyses,
  local 
)

Definition at line 1071 of file draw.py.

1071 def dataEntrySA(sites, site_analyses, local):
1072  from collections import OrderedDict
1073 
1074  missings = []
1075  for site in sites:
1076  for cam in site:
1077  if(cam.idx not in tvaLib.flatten_list([sa.camIds for sa in site_analyses])): missings.append(site.name+'/'+cam.name)
1078  if(missings):
1079  print 'The following site/camera views are not associated with any site-analysis and should be added:'
1080  for missing in missings: print ''.ljust(4,' ')+missing
1081 
1082  camIds = OrderedDict()
1083  for site in sites:
1084  for cam in site:
1085  camIds.update({((site.name[:15] + '...') if len(site.name) > 15 else site.name)+'/'+cam.name:cam.idx})
1086  entries = DataEntry('Enter site analysis details:', submit_label=local['UI_form_add'], rows=OrderedDict([('name',''), ('startTimes','all'), ('endTimes','all'), ('configurationFilename',''), ('description',''), ('cm_bounds',''), ('max_speed','80'), ('hex_grid_x','60'), ('hex_grid_y','60')]), multiSelectionListBoxes=OrderedDict([('camIds',camIds)]))
1087  if(not entries.submit): return False
1088  if(not entries.getMSLBs()['camIds']): return False
1089  if(not entries.getEntries()['name']):
1090  cam_names = []
1091  for camIdx in tvaLib.Parse.list1D(entries.getMSLBs()['camIds']):
1092  for site in sites:
1093  for cam in site:
1094  if(cam.idx == camIdx): cam_names.append(site.name+'/'+cam.name)
1095  entries.setEntry('name', ','.join(cam_names))
1096  site_analyses.new(sqlFields=tvaLib.mergeDicts(entries.getEntries(),entries.getMSLBs()), sites=sites)
1097  return True
def join(obj1, obj2, postSmoothing=True)
Definition: tools_obj.py:816
def dataEntrySA(sites, site_analyses, local)
Definition: draw.py:1071

◆ dataEntrySequences()

def lib.draw.dataEntrySequences (   sites,
  local,
  allowed_extensions = ['.mp4',
  avi 
)

Definition at line 1023 of file draw.py.

1023 def dataEntrySequences(sites, local, allowed_extensions=['.mp4', '.avi']):
1024  from collections import OrderedDict
1025  from utils import datetimeFormat
1026  from datetime import datetime, timedelta
1027 
1028  missings = []
1029  for site in sites:
1030  for cam in site:
1031  if(not cam.data): missings.append(site.name+'/'+cam.name)
1032  if(missings):
1033  print 'The following site/camera views are missing sequence data and need to be completed:'
1034  for missing in missings: print ''.ljust(4,' ')+missing
1035 
1036  entries = SeqsDataEntry(instructions='Enter sequential sequence search details:', instructions2='"Auto-fill time" will attempt to fill startTime and duration field by analysing the first existing video file, but is NOT guaranteed to work if the video file time encoding is not preoperly set.', submit_label=local['UI_form_search'], rows=OrderedDict([('startTime','2010-01-31 10:00:00'), ('duration','3600'), ('durationUnit','s'), ('configurationFilename',''), ('translationX','0.0'), ('translationY','0.0'), ('rotation','0.0')]), sites=sites, allowed_extensions=allowed_extensions, sites_selection_depth=2)
1037  if(not entries.submit): return False
1038  entriesData = entries.getEntries()
1039  startTime = datetime.strptime(entriesData.pop('startTime'), datetimeFormat)
1040  site = entries.getSelectedSite()
1041  camView = entries.getSelectedCamView()
1042  i=0
1043  cumulativeTimeDelta = timedelta(0)
1044  for filename in sorted(os.listdir(os.path.join(sites.getBaseDirectory(), site.name, camView.name))):
1045  if(os.path.splitext(filename)[-1].lower() in allowed_extensions):
1046  if('auto' in entries.getEntries()['duration']):
1047  try:
1048  import cv2
1049  video_capture = cv2.VideoCapture(os.path.join(sites.getBaseDirectory(), entries.getSelectedSite().name, entries.getSelectedCamView().name, filename))
1050  video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
1051  fps = video_capture.get(cv2.CAP_PROP_FPS)
1052  video_capture.release()
1053  cv2.destroyAllWindows()
1054  if(int(video_length/float(fps))): entriesData['duration'] = str(int(video_length/float(fps)))
1055  except:
1056  entriesData['duration'] = 3600
1057  tvaLib.printWarning('Failed to detect video duration')
1058  camView.new(camView.idx, sites.session, sqlFields=tvaLib.mergeDicts(entriesData, {'videoFilename':filename, 'startTime':startTime+cumulativeTimeDelta, 'dataFilename':os.path.splitext(filename)[0]+'.sqlite'}, overwrite=True))
1059  cumulativeTimeDelta = cumulativeTimeDelta + timedelta(0,int(entriesData['duration']))
1060  print('Sequence for video file "'+filename+'" added.')
1061  i += 1
1062  return True
1063 
def dataEntrySequences(sites, local, allowed_extensions=['.mp4', avi)
Definition: draw.py:1023

◆ dataEntrySite()

def lib.draw.dataEntrySite (   sites,
  config,
  local 
)

Definition at line 983 of file draw.py.

983 def dataEntrySite(sites, config, local):
984 
985  missings = []
986  for site in sorted(os.listdir(sites.getBaseDirectory())):
987  if(os.path.isdir(os.path.join(sites.getBaseDirectory(), site)) and site != config.output_folder and site not in [x.name for x in sites]): missings.append(site)
988  if(missings):
989  print 'The following folders are potential sites but are not entered in the database and may need to be completed:'
990  for missing in missings: print ''.ljust(4,' ')+missing
991 
992  from collections import OrderedDict
993  entries = DataEntry('Enter site details:', submit_label=local['UI_form_add'], rows=OrderedDict([('name',''), ('description',''), ('xcoordinate',''), ('ycoordinate',''), ('satres',''), ('satFilename','ortho-cal.png')]))
994  if(not entries.submit): return False
995  sites.new(sqlFields=entries.getEntries())
996  return True
997 
def dataEntrySite(sites, config, local)
Definition: draw.py:983

◆ drawAlign()

def lib.draw.drawAlign (   objects,
  sites,
  siteIx = 0,
  draw_max_traj = 200,
  local = None,
  autoUpdate = True,
  minPointDist = 0.5,
  connectorSearchDistance = 2.5,
  intersectionDistanceFactor = 1.5,
  alpha = 0.5,
  zorder = 21,
  figsize = [15.0 
)
User interface for alignment drawing. 

    Input:
    ======
    minPointDist: this ensures that a minimum distance in correponding
                  distance units, i.e. meters, exists between points, to
                  avoid rare duplicate points, or exessive point drawing.

Definition at line 142 of file draw.py.

142 def drawAlign(objects, sites, siteIx=0, draw_max_traj=200, local=None, autoUpdate=True, minPointDist=0.5, connectorSearchDistance=2.5, intersectionDistanceFactor=1.5, alpha=0.5, zorder=21, figsize=[15.0,12.0]):
143  ''' User interface for alignment drawing.
144 
145  Input:
146  ======
147  minPointDist: this ensures that a minimum distance in correponding
148  distance units, i.e. meters, exists between points, to
149  avoid rare duplicate points, or exessive point drawing.
150  '''
151  if(type(objects) is not list): objects = [objects]
152  target = tvaVis.traj2D(objects[0], draw_max_traj=draw_max_traj, alignments=sites[siteIx].alignments, mask=sites[siteIx].getCombinedMasks(), sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, fig_name=sites[siteIx].name+': Draw alignments...', figsize=figsize, local=local, **dict(('companion_objects_'+str(olIx), objects[olIx]) for olIx in range(1,len(objects))))
153  plt.setp(target.gca(), autoscale_on=False)
154 
155 
156  '''exit_condition = True
157  while exit_condition:
158  pj = []
159  alignments = []
160  ## Segments
161  while True:
162  pts = []
163  while len(pts) < 2:
164  tellMe('Draw alignments. Left click: select points, right click: undo, middle click: exit.', target=target)
165  pts = [list(x) for x in plb.ginput(0,timeout=-1)]
166  if(len(pts) == 0): break
167  if(len(pts) == 1):
168  tellMe('Too few points, starting over.', target=target)
169  time.sleep(1) # Wait a second
170  if(len(pts) == 0): break
171 
172  ph = plb.plot([x[0] for x in pts], [x[1] for x in pts], 'r', lw=2, zorder=zorder)
173  tellMe('Save alignments? Mouse click for yes, key click for no.', target=target)
174  save_cond = plb.waitforbuttonpress()
175  for p in ph: p.remove()
176  if(not save_cond):
177  alignments.append(pts)
178  pj.append(plb.plot([x[0] for x in pts], [x[1] for x in pts], '#FFA500', lw=2, zorder=zorder))
179 
180  if(not alignments):
181  exit_condition = False
182  break
183 
184 
185  newAlign = tvaScene.Alignments(alignments)
186  for link in newAlign.getLinks():
187  pj.append(plb.plot([link[2], link[6]], [link[3], link[7]], 'c', lw=4 ))
188  for corridorSet in newAlign.getCorridors():
189  if(newAlign[corridorSet[0]].hasAlignBB() and newAlign[corridorSet[1]].hasAlignBB()):
190  X2 = newAlign[corridorSet[1]].getXCoordinatesBB()
191  X2.reverse()
192  Y2 = newAlign[corridorSet[1]].getYCoordinatesBB()
193  Y2.reverse()
194  pj.append(plt.fill(newAlign[corridorSet[0]].getXCoordinatesBB()+X2, newAlign[corridorSet[0]].getYCoordinatesBB()+Y2, 'c', alpha=alpha, zorder=zorder-1))
195  else:
196  X2 = newAlign[corridorSet[1]].getXCoordinates()
197  X2.reverse()
198  Y2 = newAlign[corridorSet[1]].getYCoordinates()
199  Y2.reverse()
200  pj.append(plt.fill(newAlign[corridorSet[0]].getXCoordinates()+X2, newAlign[corridorSet[0]].getYCoordinates()+Y2, 'c', alpha=alpha, zorder=zorder-1))
201 
202  tellMe(. Mouse to continue, key to discard.', target=target) exit_condition = plb.waitforbuttonpress()
203  if(exit_condition): break
204 
205  for ph in pj:
206  for p in ph: p.remove() '''
207 
208  class LocalState(object):
209  def __init__(self, original_alignments, minPointDist=0.5, connectorSearchDistance=2.5, operation=0, zorder=21):
210  self.original_alignments = original_alignments
211  self.alignments = []
212  self.sidewalks = []
213  self.bikepaths = []
214  self.operation = operation
215  self.minPointDist = minPointDist
216  self.origin = None
217  self.zorder = 21
218  self.pts = []
219  self.pt_plot = []
220  self.pt_arrows = []
221  self.pt_plots = []
222  self.connectors = []
223  self.instruction = {1: 'Draw alignments.',
224  2: 'Verify alignment connectors (max search distance = '+str(connectorSearchDistance)+'m)',
225  3: 'Select alignments to identify as sidewalks (step is optional).',
226  4: 'Select alignments to identify as bikepaths (step is optional).',
227  5: 'Close'}
228  self.console = {1: 'Left click: select points; right click: undo; middle click: next alignment; keypress: skip drawing.',
229  2: 'Left click: accept; right click: return to previous step.',
230  3: 'Left click: select alignment; right click: undo; middle click or keypress: finish.',
231  4: 'Left click: select alignment; right click: undo; middle click or keypress: finish.',
232  5: 'Close'}
233 
234  def __call__(self, event):
235  #print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata))
236  #sys.stdout.flush()
237 
238  minPointDistSquared = self.minPointDist**2
239 
240  ## Draw alignments
241  if(self.operation==1):
242  # Left click (add point/alignment)
243  if(hasattr(event, 'button') and event.button == 1):
244  if(len(self.pts) > 0):
245  if((event.xdata-self.pts[-1][0])**2+(event.ydata-self.pts[-1][1])**2 > minPointDistSquared):
246  self.pts.append([event.xdata, event.ydata])
247  plot, = plb.plot([x[0] for x in self.pts[-2:]], [x[1] for x in self.pts[-2:]], color='r', lw=3, zorder=self.zorder)
248  self.pt_plot.append(plot)
249  elif(len(self.pts) == 0):
250  self.pts.append([event.xdata, event.ydata])
251  self.origin, = plb.plot([event.xdata], [event.ydata], color='r', marker='o')
252  plt.draw()
253  # Right click (remove point)
254  elif(hasattr(event, 'button') and event.button == 3 and self.pts):
255  self.pts = self.pts[:-1]
256  if(len(self.pts) > 0):
257  try:
258  self.pt_plot[-1].remove()
259  self.pt_plot = self.pt_plot[:-1]
260  plt.draw()
261  except: pass
262  if(len(self.pts) == 0):
263  self.origin.remove()
264  plt.draw()
265  # Middle click (finish alignment/set)
266  elif(hasattr(event, 'button') and event.button == 2 and self.pts):
267  self.origin.remove()
268  for pp in self.pt_plot: pp.remove()
269  self.pt_plot = []
270  plot,arrows = tvaVis.plotWithArrows([x[0] for x in self.pts], [x[1] for x in self.pts], color='#FFA500', lw=3, zorder=self.zorder)
271  self.pt_plots.append(plot[0])
272  self.pt_arrows.append(arrows)
273  self.alignments.append(self.pts)
274  self.pts = []
275  plt.draw()
276  elif(event.key or event.button == 2 and not self.pts):
277  self.nextOperation()
278 
279 
280  elif(self.operation==2):
281  if(hasattr(event, 'button') and event.button == 1):
282  self.nextOperation()
283  if(hasattr(event, 'button') and event.button == 3):
284  self.alignments = []
285  self.previousOperation()
286 
287 
288  elif(self.operation==3 and self.alignments):
289  if(hasattr(event, 'button') and event.button == 1):
290  [spline,_,_,_] = tvaLib.Geo.matchSplineNearest(event.xdata, event.ydata, self.alignments)
291  if(spline not in self.sidewalks):
292  self.pt_plots[spline].set_color('#377220')
293  self.sidewalks.append(spline)
294  plt.draw()
295  elif(hasattr(event, 'button') and event.button == 3 and self.sidewalks):
296  [spline,_,_,_] = tvaLib.Geo.matchSplineNearest(event.xdata, event.ydata, self.alignments)
297  if(spline in self.sidewalks):
298  self.pt_plots[spline].set_color('#FFA500')
299  self.sidewalks.remove(spline)
300  plt.draw()
301  elif(hasattr(event, 'button') and event.button == 2): self.nextOperation()
302  elif(event.key): self.nextOperation()
303 
304 
305  elif(self.operation==4 and self.alignments):
306  if(hasattr(event, 'button') and event.button == 1):
307  [spline,_,_,_] = tvaLib.Geo.matchSplineNearest(event.xdata, event.ydata, self.alignments)
308  if(spline not in self.sidewalks and spline not in self.bikepaths):
309  self.pt_plots[spline].set_color('#700f92')
310  self.bikepaths.append(spline)
311  plt.draw()
312  elif(hasattr(event, 'button') and event.button == 3 and self.bikepaths):
313  [spline,_,_,_] = tvaLib.Geo.matchSplineNearest(event.xdata, event.ydata, self.alignments)
314  if(spline not in self.sidewalks and spline in self.bikepaths):
315  self.pt_plots[spline].set_color('#FFA500')
316  self.bikepaths.remove(spline)
317  plt.draw()
318  elif(hasattr(event, 'button') and event.button == 2): self.nextOperation()
319  elif(event.key): self.nextOperation()
320 
321  def cleanforward(self):
322  ''' Cleanup drawing (moving forward).
323  Last value of *operation* is origin '''
324 
325  if(self.operation==1):
326  if(not self.alignments): self.alignments = self.original_alignments.data
327  for pp in self.pt_plot: pp.remove()
328  for pp in self.pt_plots:
329  try: pp.remove()
330  except: pass
331  try: self.origin.remove()
332  except: pass
333  self.pt_plots = []
334  for align in self.alignments:
335  plot,arrows = tvaVis.plotWithArrows([x[0] for x in align], [x[1] for x in align], color='#FFA500', lw=3, zorder=self.zorder+1)
336  self.pt_plots.append(plot[0])
337  self.pt_arrows.append(arrows)
338  self.pts = []
339  plt.draw()
340 
341 
342 
343  elif(self.operation==2):
344  for pp in self.connectors:
345  try: pp.remove()
346  except: pass
347 
348 
349  def cleanback(self):
350  ''' Cleanup drawing (moving forward).
351  Last value of *operation* is origin '''
352  if(self.operation==2):
353  for pp in self.pt_plots:
354  try: pp.remove()
355  except: pass
356  for pp in self.pt_arrows:
357  for arrow in pp:
358  try: arrow.remove()
359  except: pass
360 
361  def prepare(self):
362 
363  if(self.operation==1):
364  plt.draw()
365  elif(self.operation==2):
366  newAlign = tvaScene.Alignments(self.alignments)
367  for link in newAlign.getLinks():
368  plot, = plb.plot([link[2], link[6]], [link[3], link[7]], 'c', lw=4)
369  self.connectors.append(plot)
370  for corridorSet in newAlign.getCorridors():
371  if(newAlign[corridorSet[0]].hasAlignBB() and newAlign[corridorSet[1]].hasAlignBB()):
372  X2 = newAlign[corridorSet[1]].getXCoordinatesBB()
373  X2.reverse()
374  Y2 = newAlign[corridorSet[1]].getYCoordinatesBB()
375  Y2.reverse()
376  plot, = plt.fill(newAlign[corridorSet[0]].getXCoordinatesBB()+X2, newAlign[corridorSet[0]].getYCoordinatesBB()+Y2, 'c', alpha=alpha, zorder=zorder-1)
377  self.connectors.append(plot)
378  else:
379  X2 = newAlign[corridorSet[1]].getXCoordinates()
380  X2.reverse()
381  Y2 = newAlign[corridorSet[1]].getYCoordinates()
382  Y2.reverse()
383  plot, = plt.fill(newAlign[corridorSet[0]].getXCoordinates()+X2, newAlign[corridorSet[0]].getYCoordinates()+Y2, 'c', alpha=alpha, zorder=zorder-1)
384  self.connectors.append(plot)
385  plt.draw()
386  elif(self.operation==3):
387  plt.draw()
388 
389  elif(self.operation==5):
390  plt.close()
391 
392 
393  def nextOperation(self):
394  self.cleanforward()
395  self.operation += 1
396  tellMe(self.instruction[self.operation], console=self.console[self.operation], target=target)
397  self.prepare()
398 
399  def previousOperation(self):
400  self.cleanback()
401  self.operation -= 1
402  tellMe(self.instruction[self.operation], console=self.console[self.operation], target=target)
403  self.prepare()
404 
405 
406  localState = LocalState(sites[siteIx].alignments, minPointDist=minPointDist, connectorSearchDistance=connectorSearchDistance, zorder=zorder)
407  localState.nextOperation()
408  target.canvas.mpl_connect('button_release_event', localState)
409  target.canvas.mpl_connect('key_release_event', localState)
410  plt.show(block=True)
411 
412  if(localState.operation==5 and autoUpdate):
413  sites[siteIx].alignments = tvaScene.Alignments(localState.alignments, sidewalks=sorted(localState.sidewalks), bikepaths=sorted(localState.bikepaths))
414  sites.update()
415 
416  return localState.alignments
417 
418 
419 
def drawAlign(objects, sites, siteIx=0, draw_max_traj=200, local=None, autoUpdate=True, minPointDist=0.5, connectorSearchDistance=2.5, intersectionDistanceFactor=1.5, alpha=0.5, zorder=21, figsize=[15.0)
Definition: draw.py:142
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawAlignSnap()

def lib.draw.drawAlignSnap (   objects,
  site,
  draw_max_traj = 200,
  local = None,
  figsize = [15.0 
)
Snap point to alignment.
    This mode is verbose only. 

Definition at line 590 of file draw.py.

590 def drawAlignSnap(objects, site, draw_max_traj=200, local=None, figsize=[15.0,12.0]):
591  ''' Snap point to alignment.
592  This mode is verbose only. '''
593  target = tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=site.alignments, mask=site.getCombinedMasks(), labels=False, figsize=figsize, local=local)
594  plt.setp(target.gca(), autoscale_on=False)
595 
596  exit_cond = False
597  while not exit_cond:
598 
599  try: tellMe('(X,Y)=({0},{1}) snaps to (S,Y,L)=({2},{3},{4}); Left click: next point; Middle click: exit'.format(round(qx,2),round(qy,2),round(seg_d,2),round(OFFS_mag,2),round(spline,0)))
600  except: tellMe('Align Snap. Left click: select point near alignment.')
601  pts = np.asarray(plb.ginput(1,timeout=-1))
602  try:
603  qx = pts[0,0]
604  qy = pts[0,1]
605  except: break
606 
607  [spline,_,snapped_x,snapped_y] = tvaLib.Geo.matchSplineNearest(qx, qy, site.alignments)
608 
609  if(spline is False):
610  tellMe('There was a problem snapping this point. Please try again.')
611  continue
612 
613  plb.plot([snapped_x], [snapped_y], 'o', zorder=90000)
614 
615 
616  plt.close()
617  return True
618 
619 
def drawAlignSnap(objects, site, draw_max_traj=200, local=None, figsize=[15.0)
Definition: draw.py:590
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawBounds()

def lib.draw.drawBounds (   objects,
  sites,
  site_analyses,
  siteIx = 0,
  camIx = 0,
  saIx = 0,
  draw_max_traj = 200,
  local = None,
  autoUpdate = True,
  figsize = [15.0 
)
User interface for bound drawing. 

Definition at line 421 of file draw.py.

421 def drawBounds(objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0,12.0]):
422  ''' User interface for bound drawing. '''
423  target = tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=sites[siteIx].alignments, mask=sites[siteIx][camIx].mask, sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, labels=False, figsize=figsize, local=local)
424  plt.setp(target.gca(),autoscale_on=False)
425 
426  fig = plt.gcf()
427  exit_cond = False
428  while not exit_cond:
429  tellMe('Draw plot bounds. Left click: draw points, right click: undo, middle click: finish.', target=target)
430  pts = [list(x) for x in plb.ginput(2,timeout=-1)]
431  if(len(pts) < 2):
432  plt.close()
433  return None
434  rect_artist = fig.gca().add_artist(plt.Rectangle(pts[0], pts[1][0]-pts[0][0], pts[1][1]-pts[0][1], alpha=1, facecolor='none', edgecolor='#000000', linestyle='-', linewidth=2))
435 
436  tellMe('Save plot bounds? Mouse click for yes, key click for no.', target=target)
437  exit_cond = not plb.waitforbuttonpress()
438 
439  rect_artist.remove()
440  xy_bounds = [[min(pts[0][0],pts[1][0]),max(pts[0][0],pts[1][0])],[min(pts[0][1],pts[1][1]),max(pts[0][1],pts[1][1])]]
441  plt.close()
442 
443  if(xy_bounds and autoUpdate):
444  site_analyses[saIx].xy_bounds = tvaLib.Constructors.SuperListParse(xy_bounds, datatype='bound')
445  site_analyses.update()
446  return
447 
def drawBounds(objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0)
Definition: draw.py:421
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawLoops()

def lib.draw.drawLoops (   objects,
  site_analyses,
  saIx = 0,
  draw_max_traj = 200,
  radius = 3,
  colour = '#D63E33',
  local = None,
  autoUpdate = True,
  figsize = [15.0 
)
User interface for virtual loop drawing. 

Definition at line 484 of file draw.py.

484 def drawLoops(objects, site_analyses, saIx=0, draw_max_traj=200, radius=3, colour='#D63E33', local=None, autoUpdate=True, figsize=[15.0,12.0]):
485  ''' User interface for virtual loop drawing. '''
486  target = tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=tvaScene.Alignments(site_analyses[saIx].cameras[0].site.alignments), mask=site_analyses[saIx].getCombinedMasks(), virtual_loops=False, labels=False, figsize=figsize, local=local)
487  plt.setp(target.gca(),autoscale_on=False)
488 
489  virtual_loops_return = []
490  fig = plt.gcf()
491  exit_cond = False
492  while not exit_cond:
493  tellMe('Draw virtual loops. Left click: draw points, right click: undo, middle click: finish.', target=target)
494  pts = [list(x) for x in plb.ginput(0,timeout=-1)]
495  if(len(pts) == 0):
496  plt.close()
497  return None
498 
499  circles=[]
500  for pt in pts:
501  circle = plt.Circle((pt[0], pt[1]), radius=radius, color=colour, alpha=0.7, zorder=1000)
502  circles.append(fig.gca().add_artist(circle))
503 
504  tellMe('Save virtual loops? Mouse click for yes, key click for no.', target=target)
505  save_cond = plb.waitforbuttonpress()
506  if(not save_cond):
507  virtual_loops_return += pts
508  else:
509  for circle in circles:
510  circle.remove()
511  tellMe('Add more virtual loops? Mouse for yes, key for no.', target=target)
512  exit_cond = plb.waitforbuttonpress()
513  plt.close()
514 
515  if(virtual_loops_return and autoUpdate):
516  site_analyses[saIx].virtual_loops = tvaScene.VirtualLoops(virtual_loops_return)
517  site_analyses.update()
518  return site_analyses
519 
520 
def drawLoops(objects, site_analyses, saIx=0, draw_max_traj=200, radius=3, colour='#D63E33', local=None, autoUpdate=True, figsize=[15.0)
Definition: draw.py:484
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawMask()

def lib.draw.drawMask (   objects,
  sites,
  siteIx = 0,
  camIx = 0,
  fileIx = 0,
  draw_max_traj = 200,
  local = None,
  alternateView = False,
  autoUpdate = True,
  figsize = [15.0 
)
User interface for mask drawing. 

    Input:
    ======
    alternateView: display drawing in image space

Definition at line 43 of file draw.py.

43 def drawMask(objects, sites, siteIx=0, camIx=0, fileIx=0, draw_max_traj=200, local=None, alternateView=False, autoUpdate=True, figsize=[15.0,12.0]):
44  ''' User interface for mask drawing.
45 
46  Input:
47  ======
48  alternateView: display drawing in image space
49  '''
50 
51  if(alternateView and sites[siteIx][camIx].getHomography()):
52  if(sites[siteIx][camIx].camera.camera_matrix.data): forceDistorted = True
53  else: forceDistorted = False
54  target = tvaVis.visTrajImageSpace(objects, sites[siteIx][camIx][fileIx].getImageSpaceFrameFilename(forceDistorted=forceDistorted), tvaLib.Obj.invHomography(sites[siteIx][camIx].getHomography().asNpArray()), draw_max_traj=draw_max_traj, mask=sites[siteIx][camIx].mask, figsize=figsize, local=local)
55  else:
56  target = tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, mask=sites[siteIx][camIx].mask, sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, figsize=figsize, local=local)
57  if(target is None): raise Exception, [311, 'There was an unknown problem preparing the mask.']
58  plt.setp(target.gca(), autoscale_on=False)
59 
60  target.tight_layout()
61 
62  exit_cond = False
63  mask = []
64  pj = []
65  j = 0
66  while not exit_cond:
67  pts = []
68  while len(pts) < 3:
69  tellMe('Draw mask. Left click: select points, right click: undo, middle click: exit.', target=target)
70  pts = [list(x) for x in plb.ginput(0,timeout=-1)]
71  if(len(pts) == 0):
72  plt.close()
73  return None
74  if(len(pts) < 3):
75  tellMe('Too few points, starting over.', target=target)
76  time.sleep(1) # Wait a second
77 
78  ph = plb.fill([x[0] for x in pts], [x[1] for x in pts], 'r', lw=2)
79  tellMe('Save mask? Mouse click for yes, key click for no.', target=target)
80  save_cond = plb.waitforbuttonpress()
81  for p in ph: p.remove()
82  if(not save_cond):
83  mask.append(pts)
84  pj.append(plb.fill([x[0] for x in pts], [x[1] for x in pts], '0.66', lw=2))
85  j += 1
86  tellMe('Add mask? Mouse for yes, key for no.', target=target)
87  exit_cond = plb.waitforbuttonpress()
88  plt.close()
89 
90 
91  if(alternateView and sites[siteIx][camIx].getHomography()):
92  for mIx in range(len(mask)):
93  mask[mIx] = tvaLib.Obj.homographyProject(mask[mIx], sites[siteIx][camIx].getHomography())
94 
95  if(mask and autoUpdate):
96  sites[siteIx][camIx].mask = tvaLib.Constructors.SuperListParse(mask, dimension=3, datatype='point')
97  sites.update()
98  return sites
99 
100 
def drawMask(objects, sites, siteIx=0, camIx=0, fileIx=0, draw_max_traj=200, local=None, alternateView=False, autoUpdate=True, figsize=[15.0)
Definition: draw.py:43
def getHomography(homoSrcFrame='', orthoSrcPath='', savePath='homography.txt', tsaiCameraSrcPath='', nPoints=4, unitsPerPixel=0.1, videoPts=None, worldPts=None, pointDrawSize=3, pointTargetDrawSize=7, pointTargetDrawThickness=2, maxDisplayResolutionX=900, fig_name='', verbose=0)
Definition: tools_obj.py:403
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawMastCalibration()

def lib.draw.drawMastCalibration (   objects,
  sites,
  siteIx,
  camIx,
  autoUpdate = True,
  local = None,
  figsize = [15.0 
)
Draw plot with slider allowing for mast height to be interactively changed
    trajectories available. 

Definition at line 700 of file draw.py.

700 def drawMastCalibration(objects, sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0,12.0]):
701  ''' Draw plot with slider allowing for mast height to be interactively changed
702  trajectories available. '''
703 
704  from matplotlib.widgets import Slider
705  if(not sites[siteIx][camIx].camHeight): sites[siteIx][camIx].camHeight=10.0
706 
707 
708  target = tvaVis.traj2D([], alignments=sites[siteIx].alignments, sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, labels=False, fig_name=sites[siteIx].name+'/'+sites[siteIx][camIx].name+': Calibrate camera height (0-30m)...', figsize=figsize, local=local)
709  ca = target.gca()
710  plt.setp(target.gca(), autoscale_on=False)
711 
712 
713  sliderHeight_ax = plt.axes([0.25, 0.1, 0.65, 0.03])
714  sliderHeight = Slider(sliderHeight_ax, 'camHeight', 0.1, 30.0, valinit=sites[siteIx][camIx].camHeight)
715 
716 
717  class LocalState(object):
718  def __init__(self):
719  self.obj_traces = []
720 
721  def update(self, val):
722 
723  for obj in self.obj_traces:
724  obj.remove()
725  self.obj_traces=[]
726 
727  transformed_obj = deepcopy(objects)
728  transformed_obj = tvaFilter.compensateParralax(transformed_obj, origin=sites[siteIx][camIx].camOrigin, mast_height=sliderHeight.val, verbose=0)
729  for obj in transformed_obj:
730  plot, = ca.plot(obj.getXCoordinates(), obj.getYCoordinates(), color='b')
731  self.obj_traces.append(plot)
732  plt.draw()
733 
734  localState = LocalState()
735  sliderHeight.on_changed(localState.update)
736  localState.update(None)
737 
738 
739 
740 
741  plt.show(block=True)
742  plt.close()
743 
744 
745  if(autoUpdate):
746  sites[siteIx][camIx].camHeight = sliderHeight.val
747  sites.update()
748  return sliderHeight.val
749 
def drawMastCalibration(objects, sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0)
Definition: draw.py:700

◆ drawMastLocation()

def lib.draw.drawMastLocation (   sites,
  siteIx,
  camIx,
  autoUpdate = True,
  local = None,
  figsize = [15.0 
)
Draw interactive plot to select mast location. 

Definition at line 680 of file draw.py.

680 def drawMastLocation(sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0,12.0]):
681  ''' Draw interactive plot to select mast location. '''
682 
683 
684  target = tvaVis.traj2D([], sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, labels=False, fig_name=sites[siteIx].name+'/'+sites[siteIx][camIx].name+': Select camera origin...', figsize=figsize, local=local)
685  plt.setp(target.gca(), autoscale_on=False)
686  pt = plb.ginput(1,timeout=-1)
687 
688 
689  plt.close()
690 
691 
692  if(autoUpdate):
693  sites[siteIx][camIx].camOrigin = tvaLib.Constructors.SuperListParse(list(pt[0]), dimension=1, datatype='float')
694  sites.update()
695  return sites
696 
697 
698 
699 
def drawMastLocation(sites, siteIx, camIx, autoUpdate=True, local=None, figsize=[15.0)
Definition: draw.py:680

◆ drawObjHighlight()

def lib.draw.drawObjHighlight (   objects,
  camera,
  draw_max_traj = 200,
  local = None,
  arrow_every_dist = 8.0,
  highlight_thickness = 3.0,
  align_highlight_steps = 5,
  figsize = [15.0 
)
Highlight selected object. This mode currently must plot all 
    trajectories available. 

Definition at line 620 of file draw.py.

620 def drawObjHighlight(objects, camera, draw_max_traj=200, local=None, arrow_every_dist=8.0, highlight_thickness=3.0, align_highlight_steps=5, figsize=[15.0,12.0]):
621  ''' Highlight selected object. This mode currently must plot all
622  trajectories available. '''
623 
624  alignments = tvaScene.Alignments(camera.site.alignments)
625  target = tvaVis.traj2D(objects, draw_max_traj=None, alignments=alignments, mask=camera.mask, labels=False, figsize=figsize, local=local)
626  plt.setp(target.gca(), autoscale_on=False)
627 
628  exit_cond = False
629  while not exit_cond:
630 
631  try: tellMe('Object ID: '+str(objects[nearest_object_ix].num)+'; Left click: continue; Middle click: exit')
632  except: tellMe('Object highlighting. Left click: select point near object.')
633  pts = np.asarray(plb.ginput(1,timeout=-1))
634  try:
635  qx = pts[0,0]
636  qy = pts[0,1]
637  except: break
638 
639 
640  nearest_squared_distance = float('inf')
641  nearest_object_ix = None
642  for oIx in range(len(objects)):
643  for pIx in range(len(objects[oIx].positions.getXCoordinates())):
644  squared_distance = (qx-objects[oIx].positions.getXCoordinates()[pIx])**2+(qy-objects[oIx].positions.getYCoordinates()[pIx])**2
645  if(squared_distance < nearest_squared_distance):
646  nearest_squared_distance = squared_distance
647  nearest_object_ix = oIx
648 
649 
650  if(oIx is None):
651  tellMe('Could not locate a nearest object. Please try again.')
652  continue
653 
654 
655  try:
656  line.remove()
657  for arrow in arrows: arrow.remove()
658  except: pass
659  try:
660  for align_correspondance in align_correspondances: align_correspondance[0].remove()
661  except: pass
662 
663  line, = plt.plot(objects[nearest_object_ix].getXCoordinates(), objects[nearest_object_ix].getYCoordinates(), color='red', linewidth=highlight_thickness)
664  arrows=[]
665  cum_dist_since = 0
666  for pIx in range(len(objects[nearest_object_ix].getXCoordinates())):
667  cum_dist_since += math.sqrt(objects[nearest_object_ix].velocities.getXCoordinates()[pIx]**2+objects[nearest_object_ix].velocities.getYCoordinates()[pIx]**2)
668  if(cum_dist_since>arrow_every_dist):
669  cum_dist_since = 0
670  arrows.append(plt.arrow(objects[nearest_object_ix].getXCoordinates()[pIx], objects[nearest_object_ix].getYCoordinates()[pIx], objects[nearest_object_ix].velocities.getXCoordinates()[pIx], objects[nearest_object_ix].velocities.getYCoordinates()[pIx], head_width=1, head_length=2, fc='red', ec='red', zorder=20))
671  if(hasattr(objects[nearest_object_ix], 'curvilinearPositions')):
672  align_correspondances = []
673  for pIx in range(0,len(objects[nearest_object_ix].getXCoordinates()),align_highlight_steps):
674  [x,y] = tvaLib.Geo.getXYfromSY(objects[nearest_object_ix].curvilinearPositions.getXCoordinates()[pIx], alignments[objects[nearest_object_ix].curvilinearPositions.getLanes()[pIx]])
675  align_correspondances.append(plt.plot([objects[nearest_object_ix].getXCoordinates()[pIx],x], [objects[nearest_object_ix].getYCoordinates()[pIx],y], color='orange', linewidth=2))
676  plt.close()
677  return True
678 
679 
def drawObjHighlight(objects, camera, draw_max_traj=200, local=None, arrow_every_dist=8.0, highlight_thickness=3.0, align_highlight_steps=5, figsize=[15.0)
Definition: draw.py:620
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ drawTransformation()

def lib.draw.drawTransformation (   objects,
  sequence,
  draw_max_traj = 200,
  figsize = [15.0 
)
Setup drawing of transformation vectors. 

Definition at line 521 of file draw.py.

521 def drawTransformation(objects, sequence, draw_max_traj=200, figsize=[15.0,12.0]):
522  ''' Setup drawing of transformation vectors. '''
523 
524  translationX = sequence.translationX
525  translationY = sequence.translationY
526  rotation = sequence.rotation
527 
528  alignments = tvaScene.Alignments(sequence.cameraView.site.alignments)
529  mask = tvaLib.Constructors.SuperListParse(sequence.cameraView.mask, dimension=3, datatype='point')
530 
531  objects = tvaFilter.transformTrajectories(objects, 0.0, 0.0, rotation, objectsOnly=True)
532  tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=alignments, mask=mask, virtual_loops=False, labels=False, figsize=figsize)
533 
534  exit_cond = False
535  while not exit_cond:
536  tellMe('Change rotation? Mouse click for yes, key click for no.')
537  exit_cond = plt.waitforbuttonpress()
538  if(exit_cond == True):
539  break
540 
541  tellMe('Draw origin (1) and desination (2) reference points to rotate about (0,0).')
542 
543  pts = []
544  for point in range(2):
545  pts.append(list(plb.ginput(1,timeout=-1)[0]))
546  plt.plot([0,pts[point][0]], [0,pts[point][1]], 'm', lw=2 )
547 
548  incrRotation = tvaLib.Geo.vectorsToAngleDegCC(pts[0][0],pts[0][1],pts[1][0],pts[1][1])
549  rotation += incrRotation
550  print('Rotation angle: '+str(rotation))
551  print('Incremental rotation angle: '+str(incrRotation))
552  objects = tvaFilter.transformTrajectories(objects, 0.0, 0.0, incrRotation, objectsOnly=True)
553  plt.clf()
554  tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=alignments, mask=mask, virtual_loops=False, labels=False)
555 
556  tellMe('Change rotation? Mouse click for yes, key click for no.')
557  exit_cond = plt.waitforbuttonpress()
558 
559  plt.clf()
560  objects = tvaFilter.transformTrajectories(objects, translationX, translationY, 0.0, objectsOnly=True)
561  tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=alignments, mask=mask, virtual_loops=False, labels=False)
562 
563  exit_cond = False
564  while not exit_cond:
565  tellMe('Apply new translation? Mouse click for yes, key click for no.')
566  exit_cond = plt.waitforbuttonpress()
567  if(exit_cond == True):
568  break
569 
570  tellMe('Draw origin (1) and desination (2) reference points for translation.')
571 
572  pts = []
573  for point in range(2):
574  pts.append(list(plb.ginput(1,timeout=-1)[0]))
575 
576  incrTranslation = [pts[1][0]-pts[0][0],pts[1][1]-pts[0][1]]
577  translationX += incrTranslation[0]
578  translationY += incrTranslation[1]
579  print('Translation : '+str(translationX)+','+str(translationY))
580  print('Incremental translation: '+str(incrTranslation[0])+','+str(incrTranslation[1]))
581  objects = tvaFilter.transformTrajectories(objects, incrTranslation[0], incrTranslation[1], 0.0, objectsOnly=True)
582  plt.clf()
583  tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=alignments, mask=mask, virtual_loops=False, labels=False)
584 
585  plt.draw()
586  plt.close()
587  return rotation, translationX, translationY
588 
589 
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33
def drawTransformation(objects, sequence, draw_max_traj=200, figsize=[15.0)
Definition: draw.py:521

◆ drawZone()

def lib.draw.drawZone (   objects,
  sites,
  site_analyses,
  siteIx = 0,
  camIx = 0,
  saIx = 0,
  draw_max_traj = 200,
  local = None,
  autoUpdate = True,
  figsize = [15.0 
)
User interface for analysis zone drawing. 

Definition at line 101 of file draw.py.

101 def drawZone(objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0,12.0]):
102  ''' User interface for analysis zone drawing. '''
103  target = tvaVis.traj2D(objects, draw_max_traj=draw_max_traj, alignments=sites[siteIx].alignments, mask=sites[siteIx][camIx].mask, zone=site_analyses[saIx].zone, xy_bounds=site_analyses[saIx].xy_bounds, sateliteImage=sites[siteIx].getFullSatFilename(), sateliteResolution=sites[siteIx].satres, figsize=figsize, local=local)
104  plt.setp(target.gca(), autoscale_on=False)
105 
106  target.tight_layout()
107 
108  exit_cond = False
109  zone = []
110  pj = []
111  j = 0
112  while not exit_cond:
113  pts = []
114  while len(pts) < 3:
115  tellMe('Draw zone. Left click: select points, right click: undo, middle click: exit.', target=target)
116  pts = [list(x) for x in plb.ginput(0,timeout=-1)]
117  if(len(pts) == 0):
118  plt.close()
119  return None
120  if(len(pts) < 3):
121  tellMe('Too few points, starting over.', target=target)
122  time.sleep(1) # Wait a second
123 
124  ph = plb.fill([x[0] for x in pts], [x[1] for x in pts], 'r', lw=2)
125  tellMe('Save zone? Mouse click for yes, key click for no.', target=target)
126  save_cond = plb.waitforbuttonpress()
127  for p in ph: p.remove()
128  if(not save_cond):
129  zone.append(pts)
130  pj.append(plb.fill([x[0] for x in pts], [x[1] for x in pts], '0.66', lw=2))
131  j += 1
132  tellMe('Add zone? Mouse for yes, key for no.', target=target)
133  exit_cond = plb.waitforbuttonpress()
134  plt.close()
135 
136  if(zone and autoUpdate):
137  site_analyses[saIx].zone = tvaLib.Constructors.SuperListParse(zone, dimension=3, datatype='point')
138  site_analyses.update()
139  return site_analyses
140 
141 
def drawZone(objects, sites, site_analyses, siteIx=0, camIx=0, saIx=0, draw_max_traj=200, local=None, autoUpdate=True, figsize=[15.0)
Definition: draw.py:101
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

◆ tellMe()

def lib.draw.tellMe (   s,
  console = '',
  target = False 
)

Drawinbg tools.

Definition at line 33 of file draw.py.

33 def tellMe(s, console='', target=False):
34  if(not target):
35  target = plt
36 
37  if(console): print(console)
38  #print('Drawing console: '+s)
39  plt.title(s,fontsize=14)
40  plt.draw()
41 
42 
def tellMe(s, console='', target=False)
Drawinbg tools.
Definition: draw.py:33

Variable Documentation

◆ alignments

lib.draw.alignments

Definition at line 213 of file draw.py.

◆ bikepaths

lib.draw.bikepaths

Definition at line 215 of file draw.py.

◆ connectors

lib.draw.connectors

Definition at line 224 of file draw.py.

◆ console

lib.draw.console

Definition at line 230 of file draw.py.

◆ instruction

lib.draw.instruction

Definition at line 225 of file draw.py.

◆ minPointDist

lib.draw.minPointDist

Definition at line 217 of file draw.py.

◆ obj_traces

lib.draw.obj_traces

Setup.

Flush previous plot.

Draw objects Interface elements Runtime state

Definition at line 719 of file draw.py.

◆ operation

lib.draw.operation

Draw alignments.

Close diagram.

Prepare connectors.

Cleanup connectors.

Cleanup alignments segments.

Identify sidewalks.

Verify connectors.

Definition at line 216 of file draw.py.

◆ origin

lib.draw.origin

Definition at line 218 of file draw.py.

◆ original_alignments

lib.draw.original_alignments

Definition at line 212 of file draw.py.

◆ pt_arrows

lib.draw.pt_arrows

Definition at line 222 of file draw.py.

◆ pt_plot

lib.draw.pt_plot

Definition at line 221 of file draw.py.

◆ pt_plots

lib.draw.pt_plots

Definition at line 223 of file draw.py.

◆ pts

lib.draw.pts

Definition at line 220 of file draw.py.

◆ sidewalks

lib.draw.sidewalks

Definition at line 214 of file draw.py.

◆ zorder

lib.draw.zorder

Definition at line 219 of file draw.py.