Mercurial Hosting > traffic-intelligence
comparison trafficintelligence/storage.py @ 1077:3939ae415be0
Merging
author | Wendlasida |
---|---|
date | Fri, 20 Jul 2018 14:03:34 -0400 |
parents | 67144f26609e d4d052a05337 |
children | e53c6e87bb3f |
comparison
equal
deleted
inserted
replaced
1076:108c5dc4e34a | 1077:3939ae415be0 |
---|---|
68 cursor.execute('SELECT COUNT(*) FROM SQLITE_MASTER WHERE type = \'table\' AND name = \''+tableName+'\'') | 68 cursor.execute('SELECT COUNT(*) FROM SQLITE_MASTER WHERE type = \'table\' AND name = \''+tableName+'\'') |
69 return cursor.fetchone()[0] == 1 | 69 return cursor.fetchone()[0] == 1 |
70 except sqlite3.OperationalError as error: | 70 except sqlite3.OperationalError as error: |
71 printDBError(error) | 71 printDBError(error) |
72 | 72 |
73 def tableNames(filename): | |
74 'Lists the names of the tables in the SQLite file' | |
75 if Path(filename).is_file(): | |
76 with sqlite3.connect(filename) as connection: | |
77 try: | |
78 cursor = connection.cursor() | |
79 cursor.execute('SELECT name FROM sqlite_master WHERE type = \'table\'') | |
80 return [row[0] for row in cursor] | |
81 except sqlite3.OperationalError as error: | |
82 printDBError(error) | |
83 return [] | |
84 | |
73 def createTrajectoryTable(cursor, tableName): | 85 def createTrajectoryTable(cursor, tableName): |
74 if tableName.endswith('positions') or tableName.endswith('velocities'): | 86 if tableName.endswith('positions') or tableName.endswith('velocities'): |
75 cursor.execute("CREATE TABLE IF NOT EXISTS "+tableName+" (trajectory_id INTEGER, frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))") | 87 cursor.execute("CREATE TABLE IF NOT EXISTS "+tableName+" (trajectory_id INTEGER, frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))") |
76 else: | 88 else: |
77 print('Unallowed name {} for trajectory table'.format(tableName)) | 89 print('Unallowed name {} for trajectory table'.format(tableName)) |
257 if object, features can be loaded with withFeatures or nLongestObjectFeatures used to select the n longest features | 269 if object, features can be loaded with withFeatures or nLongestObjectFeatures used to select the n longest features |
258 | 270 |
259 The number loaded is either the first objectNumbers objects, | 271 The number loaded is either the first objectNumbers objects, |
260 or the indices in objectNumbers from the database''' | 272 or the indices in objectNumbers from the database''' |
261 objects = [] | 273 objects = [] |
262 with sqlite3.connect(filename) as connection: | 274 if Path(filename).is_file(): |
263 objects = loadTrajectoriesFromTable(connection, 'positions', trajectoryType, objectNumbers, timeStep) | 275 with sqlite3.connect(filename) as connection: |
264 objectVelocities = loadTrajectoriesFromTable(connection, 'velocities', trajectoryType, objectNumbers, timeStep) | 276 objects = loadTrajectoriesFromTable(connection, 'positions', trajectoryType, objectNumbers, timeStep) |
265 | 277 objectVelocities = loadTrajectoriesFromTable(connection, 'velocities', trajectoryType, objectNumbers, timeStep) |
266 if len(objectVelocities) > 0: | 278 |
267 for o,v in zip(objects, objectVelocities): | 279 if len(objectVelocities) > 0: |
268 if o.getNum() == v.getNum(): | 280 for o,v in zip(objects, objectVelocities): |
269 o.velocities = v.positions | 281 if o.getNum() == v.getNum(): |
270 o.velocities.duplicateLastPosition() # avoid having velocity shorter by one position than positions | 282 o.velocities = v.positions |
271 else: | 283 o.velocities.duplicateLastPosition() # avoid having velocity shorter by one position than positions |
272 print('Could not match positions {0} with velocities {1}'.format(o.getNum(), v.getNum())) | |
273 | |
274 if trajectoryType == 'object': | |
275 cursor = connection.cursor() | |
276 try: | |
277 # attribute feature numbers to objects | |
278 queryStatement = 'SELECT trajectory_id, object_id FROM objects_features' | |
279 if objectNumbers is not None: | |
280 queryStatement += ' WHERE object_id '+getObjectCriteria(objectNumbers) | |
281 queryStatement += ' ORDER BY object_id' # order is important to group all features per object | |
282 logging.debug(queryStatement) | |
283 cursor.execute(queryStatement) | |
284 | |
285 featureNumbers = {} | |
286 for row in cursor: | |
287 objId = row[1] | |
288 if objId not in featureNumbers: | |
289 featureNumbers[objId] = [row[0]] | |
290 else: | 284 else: |
291 featureNumbers[objId].append(row[0]) | 285 print('Could not match positions {0} with velocities {1}'.format(o.getNum(), v.getNum())) |
292 | 286 |
293 for obj in objects: | 287 if trajectoryType == 'object': |
294 obj.featureNumbers = featureNumbers[obj.getNum()] | 288 cursor = connection.cursor() |
295 | 289 try: |
296 # load userType | 290 # attribute feature numbers to objects |
297 attributes = loadObjectAttributesFromTable(cursor, objectNumbers, True) | 291 queryStatement = 'SELECT trajectory_id, object_id FROM objects_features' |
298 for obj in objects: | 292 if objectNumbers is not None: |
299 userType, nObjects = attributes[obj.getNum()] | 293 queryStatement += ' WHERE object_id '+getObjectCriteria(objectNumbers) |
300 obj.setUserType(userType) | 294 queryStatement += ' ORDER BY object_id' # order is important to group all features per object |
301 obj.setNObjects(nObjects) | 295 logging.debug(queryStatement) |
302 | 296 cursor.execute(queryStatement) |
303 # add features | 297 |
304 if withFeatures: | 298 featureNumbers = {} |
299 for row in cursor: | |
300 objId = row[1] | |
301 if objId not in featureNumbers: | |
302 featureNumbers[objId] = [row[0]] | |
303 else: | |
304 featureNumbers[objId].append(row[0]) | |
305 | |
305 for obj in objects: | 306 for obj in objects: |
306 obj.features = loadTrajectoriesFromSqlite(filename, 'feature', obj.featureNumbers, timeStep = timeStep) | 307 obj.featureNumbers = featureNumbers[obj.getNum()] |
307 elif nLongestFeaturesPerObject is not None: | 308 |
309 # load userType | |
310 attributes = loadObjectAttributesFromTable(cursor, objectNumbers, True) | |
308 for obj in objects: | 311 for obj in objects: |
309 queryStatement = 'SELECT trajectory_id, max(frame_number)-min(frame_number) AS length FROM positions WHERE trajectory_id '+getObjectCriteria(obj.featureNumbers)+' GROUP BY trajectory_id ORDER BY length DESC' | 312 userType, nObjects = attributes[obj.getNum()] |
310 logging.debug(queryStatement) | 313 obj.setUserType(userType) |
311 cursor.execute(queryStatement) | 314 obj.setNObjects(nObjects) |
312 obj.features = loadTrajectoriesFromSqlite(filename, 'feature', [row[0] for i,row in enumerate(cursor) if i<nLongestFeaturesPerObject], timeStep = timeStep) | 315 |
313 | 316 # add features |
314 except sqlite3.OperationalError as error: | 317 if withFeatures: |
315 printDBError(error) | 318 for obj in objects: |
319 obj.features = loadTrajectoriesFromSqlite(filename, 'feature', obj.featureNumbers, timeStep = timeStep) | |
320 elif nLongestFeaturesPerObject is not None: | |
321 for obj in objects: | |
322 queryStatement = 'SELECT trajectory_id, max(frame_number)-min(frame_number) AS length FROM positions WHERE trajectory_id '+getObjectCriteria(obj.featureNumbers)+' GROUP BY trajectory_id ORDER BY length DESC' | |
323 logging.debug(queryStatement) | |
324 cursor.execute(queryStatement) | |
325 obj.features = loadTrajectoriesFromSqlite(filename, 'feature', [row[0] for i,row in enumerate(cursor) if i<nLongestFeaturesPerObject], timeStep = timeStep) | |
326 | |
327 except sqlite3.OperationalError as error: | |
328 printDBError(error) | |
316 return objects | 329 return objects |
317 | 330 |
318 def loadObjectFeatureFrameNumbers(filename, objectNumbers = None): | 331 def loadObjectFeatureFrameNumbers(filename, objectNumbers = None): |
319 'Loads the feature frame numbers for each object' | 332 'Loads the feature frame numbers for each object' |
320 with sqlite3.connect(filename) as connection: | 333 with sqlite3.connect(filename) as connection: |
449 (format of SQLite output by the ground truth annotation tool | 462 (format of SQLite output by the ground truth annotation tool |
450 or Urban Tracker | 463 or Urban Tracker |
451 | 464 |
452 Load descriptions?''' | 465 Load descriptions?''' |
453 objects = [] | 466 objects = [] |
454 with sqlite3.connect(filename) as connection: | 467 if Path(filename).is_file(): |
455 if objectType == 'bb': | 468 with sqlite3.connect(filename) as connection: |
456 topCorners = loadTrajectoriesFromTable(connection, 'bounding_boxes', 'bbtop', objectNumbers, timeStep) | 469 if objectType == 'bb': |
457 bottomCorners = loadTrajectoriesFromTable(connection, 'bounding_boxes', 'bbbottom', objectNumbers, timeStep) | 470 topCorners = loadTrajectoriesFromTable(connection, 'bounding_boxes', 'bbtop', objectNumbers, timeStep) |
458 userTypes = loadObjectAttributesFromTable(connection.cursor(), objectNumbers) # string format is same as object | 471 bottomCorners = loadTrajectoriesFromTable(connection, 'bounding_boxes', 'bbbottom', objectNumbers, timeStep) |
459 | 472 userTypes = loadObjectAttributesFromTable(connection.cursor(), objectNumbers) # string format is same as object |
460 for t, b in zip(topCorners, bottomCorners): | 473 |
461 num = t.getNum() | 474 for t, b in zip(topCorners, bottomCorners): |
462 if t.getNum() == b.getNum(): | 475 num = t.getNum() |
463 annotation = moving.BBMovingObject(num, t.getTimeInterval(), t, b, userTypes[num]) | 476 if t.getNum() == b.getNum(): |
464 objects.append(annotation) | 477 annotation = moving.BBMovingObject(num, t.getTimeInterval(), t, b, userTypes[num]) |
465 else: | 478 objects.append(annotation) |
466 print ('Unknown type of bounding box {}'.format(objectType)) | 479 else: |
480 print ('Unknown type of bounding box {}'.format(objectType)) | |
467 return objects | 481 return objects |
468 | 482 |
469 def saveInteraction(cursor, interaction): | 483 def saveInteraction(cursor, interaction): |
470 roadUserNumbers = list(interaction.getRoadUserNumbers()) | 484 roadUserNumbers = list(interaction.getRoadUserNumbers()) |
471 cursor.execute('INSERT INTO interactions VALUES({}, {}, {}, {}, {})'.format(interaction.getNum(), roadUserNumbers[0], roadUserNumbers[1], interaction.getFirstInstant(), interaction.getLastInstant())) | 485 cursor.execute('INSERT INTO interactions VALUES({}, {}, {}, {}, {})'.format(interaction.getNum(), roadUserNumbers[0], roadUserNumbers[1], interaction.getFirstInstant(), interaction.getLastInstant())) |
507 def loadInteractionsFromSqlite(filename): | 521 def loadInteractionsFromSqlite(filename): |
508 '''Loads interaction and their indicators | 522 '''Loads interaction and their indicators |
509 | 523 |
510 TODO choose the interactions to load''' | 524 TODO choose the interactions to load''' |
511 interactions = [] | 525 interactions = [] |
512 with sqlite3.connect(filename) as connection: | 526 if Path(filename).is_file(): |
513 cursor = connection.cursor() | 527 with sqlite3.connect(filename) as connection: |
514 try: | 528 cursor = connection.cursor() |
515 cursor.execute('SELECT INT.id, INT.object_id1, INT.object_id2, INT.first_frame_number, INT.last_frame_number, IND.indicator_type, IND.frame_number, IND.value from interactions INT, indicators IND WHERE INT.id = IND.interaction_id ORDER BY INT.id, IND.indicator_type, IND.frame_number') | 529 try: |
516 interactionNum = -1 | 530 cursor.execute('SELECT INT.id, INT.object_id1, INT.object_id2, INT.first_frame_number, INT.last_frame_number, IND.indicator_type, IND.frame_number, IND.value from interactions INT, indicators IND WHERE INT.id = IND.interaction_id ORDER BY INT.id, IND.indicator_type, IND.frame_number') |
517 indicatorTypeNum = -1 | 531 interactionNum = -1 |
518 tmpIndicators = {} | 532 indicatorTypeNum = -1 |
519 for row in cursor: | 533 tmpIndicators = {} |
520 if row[0] != interactionNum: | 534 for row in cursor: |
521 interactionNum = row[0] | 535 if row[0] != interactionNum: |
522 interactions.append(events.Interaction(interactionNum, moving.TimeInterval(row[3],row[4]), row[1], row[2])) | 536 interactionNum = row[0] |
523 interactions[-1].indicators = {} | 537 interactions.append(events.Interaction(interactionNum, moving.TimeInterval(row[3],row[4]), row[1], row[2])) |
524 if indicatorTypeNum != row[5] or row[0] != interactionNum: | 538 interactions[-1].indicators = {} |
525 indicatorTypeNum = row[5] | 539 if indicatorTypeNum != row[5] or row[0] != interactionNum: |
526 indicatorName = events.Interaction.indicatorNames[indicatorTypeNum] | 540 indicatorTypeNum = row[5] |
527 indicatorValues = {row[6]:row[7]} | 541 indicatorName = events.Interaction.indicatorNames[indicatorTypeNum] |
528 interactions[-1].indicators[indicatorName] = indicators.SeverityIndicator(indicatorName, indicatorValues, mostSevereIsMax = not indicatorName in events.Interaction.timeIndicators) | 542 indicatorValues = {row[6]:row[7]} |
529 else: | 543 interactions[-1].indicators[indicatorName] = indicators.SeverityIndicator(indicatorName, indicatorValues, mostSevereIsMax = not indicatorName in events.Interaction.timeIndicators) |
530 indicatorValues[row[6]] = row[7] | 544 else: |
531 interactions[-1].indicators[indicatorName].timeInterval.last = row[6] | 545 indicatorValues[row[6]] = row[7] |
532 except sqlite3.OperationalError as error: | 546 interactions[-1].indicators[indicatorName].timeInterval.last = row[6] |
533 printDBError(error) | 547 except sqlite3.OperationalError as error: |
534 return [] | 548 printDBError(error) |
549 return [] | |
535 return interactions | 550 return interactions |
536 # load first and last object instants | 551 # load first and last object instants |
537 # CREATE TEMP TABLE IF NOT EXISTS object_instants AS SELECT OF.object_id, min(frame_number) as first_instant, max(frame_number) as last_instant from positions P, objects_features OF WHERE P.trajectory_id = OF.trajectory_id group by OF.object_id order by OF.object_id | 552 # CREATE TEMP TABLE IF NOT EXISTS object_instants AS SELECT OF.object_id, min(frame_number) as first_instant, max(frame_number) as last_instant from positions P, objects_features OF WHERE P.trajectory_id = OF.trajectory_id group by OF.object_id order by OF.object_id |
538 | 553 |
539 def createBoundingBoxTable(filename, invHomography = None): | 554 def createBoundingBoxTable(filename, invHomography = None): |
552 connection.commit() | 567 connection.commit() |
553 | 568 |
554 def loadBoundingBoxTableForDisplay(filename): | 569 def loadBoundingBoxTableForDisplay(filename): |
555 '''Loads bounding boxes from bounding_boxes table for display over trajectories''' | 570 '''Loads bounding boxes from bounding_boxes table for display over trajectories''' |
556 boundingBoxes = {} # list of bounding boxes for each instant | 571 boundingBoxes = {} # list of bounding boxes for each instant |
557 with sqlite3.connect(filename) as connection: | 572 if Path(filename).is_file(): |
558 cursor = connection.cursor() | 573 with sqlite3.connect(filename) as connection: |
559 try: | 574 cursor = connection.cursor() |
560 cursor.execute('SELECT name FROM sqlite_master WHERE type=\'table\' AND name=\'bounding_boxes\'') | 575 try: |
561 result = cursor.fetchall() | 576 cursor.execute('SELECT name FROM sqlite_master WHERE type=\'table\' AND name=\'bounding_boxes\'') |
562 if len(result) > 0: | 577 result = cursor.fetchall() |
563 cursor.execute('SELECT * FROM bounding_boxes') | 578 if len(result) > 0: |
564 for row in cursor: | 579 cursor.execute('SELECT * FROM bounding_boxes') |
565 boundingBoxes.setdefault(row[1], []).append([moving.Point(row[2], row[3]), moving.Point(row[4], row[5])]) | 580 for row in cursor: |
566 except sqlite3.OperationalError as error: | 581 boundingBoxes.setdefault(row[1], []).append([moving.Point(row[2], row[3]), moving.Point(row[4], row[5])]) |
567 printDBError(error) | 582 except sqlite3.OperationalError as error: |
568 return boundingBoxes | 583 printDBError(error) |
569 return boundingBoxes | 584 return boundingBoxes |
570 | 585 |
571 ######################### | 586 ######################### |
572 # saving and loading for scene interpretation: POIs and Prototypes | 587 # saving and loading for scene interpretation: POIs and Prototypes |
573 ######################### | 588 ######################### |
622 except sqlite3.OperationalError as error: | 637 except sqlite3.OperationalError as error: |
623 printDBError(error) | 638 printDBError(error) |
624 connection.commit() | 639 connection.commit() |
625 | 640 |
626 def loadPrototypeAssignmentsFromSqlite(filename, objectType): | 641 def loadPrototypeAssignmentsFromSqlite(filename, objectType): |
627 with sqlite3.connect(filename) as connection: | 642 prototypeAssignments = {} |
628 cursor = connection.cursor() | 643 if Path(filename).is_file(): |
629 try: | 644 with sqlite3.connect(filename) as connection: |
630 tableName, objectIdColumnName = prototypeAssignmentNames(objectType) | 645 cursor = connection.cursor() |
631 cursor.execute('SELECT * FROM '+tableName) | 646 try: |
632 prototypeAssignments = {} | 647 tableName, objectIdColumnName = prototypeAssignmentNames(objectType) |
633 for row in cursor: | 648 cursor.execute('SELECT * FROM '+tableName) |
634 p = moving.Prototype(row[1], row[2], row[3]) | 649 for row in cursor: |
635 if p in prototypeAssignments: | 650 p = moving.Prototype(row[1], row[2], row[3]) |
636 prototypeAssignments[p].append(row[0]) | 651 if p in prototypeAssignments: |
637 else: | 652 prototypeAssignments[p].append(row[0]) |
638 prototypeAssignments[p] = [row[0]] | 653 else: |
639 return prototypeAssignments | 654 prototypeAssignments[p] = [row[0]] |
640 except sqlite3.OperationalError as error: | 655 return prototypeAssignments |
641 printDBError(error) | 656 except sqlite3.OperationalError as error: |
642 | 657 printDBError(error) |
658 return prototypeAssignments | |
659 | |
643 def loadPrototypesFromSqlite(filename, withTrajectories = True): | 660 def loadPrototypesFromSqlite(filename, withTrajectories = True): |
644 'Loads prototype ids and matchings (if stored)' | 661 'Loads prototype ids and matchings (if stored)' |
645 prototypes = [] | 662 prototypes = [] |
646 with sqlite3.connect(filename) as connection: | 663 if Path(filename).is_file(): |
647 cursor = connection.cursor() | 664 with sqlite3.connect(filename) as connection: |
648 objects = [] | 665 cursor = connection.cursor() |
649 try: | 666 objects = [] |
650 cursor.execute('SELECT * FROM prototypes') | 667 try: |
651 for row in cursor: | 668 cursor.execute('SELECT * FROM prototypes') |
652 prototypes.append(moving.Prototype(row[0], row[1], row[2], row[3])) | 669 for row in cursor: |
653 if withTrajectories: | 670 prototypes.append(moving.Prototype(row[0], row[1], row[2], row[3])) |
654 for p in prototypes: | 671 if withTrajectories: |
655 p.setMovingObject(loadTrajectoriesFromSqlite(p.getFilename(), p.getTrajectoryType(), [p.getNum()])[0]) | 672 for p in prototypes: |
656 # loadingInformation = {} # complicated slightly optimized | 673 p.setMovingObject(loadTrajectoriesFromSqlite(p.getFilename(), p.getTrajectoryType(), [p.getNum()])[0]) |
657 # for p in prototypes: | 674 # loadingInformation = {} # complicated slightly optimized |
658 # dbfn = p.getFilename() | 675 # for p in prototypes: |
659 # trajType = p.getTrajectoryType() | 676 # dbfn = p.getFilename() |
660 # if (dbfn, trajType) in loadingInformation: | 677 # trajType = p.getTrajectoryType() |
661 # loadingInformation[(dbfn, trajType)].append(p) | 678 # if (dbfn, trajType) in loadingInformation: |
662 # else: | 679 # loadingInformation[(dbfn, trajType)].append(p) |
663 # loadingInformation[(dbfn, trajType)] = [p] | 680 # else: |
664 # for k, v in loadingInformation.iteritems(): | 681 # loadingInformation[(dbfn, trajType)] = [p] |
665 # objects += loadTrajectoriesFromSqlite(k[0], k[1], [p.getNum() for p in v]) | 682 # for k, v in loadingInformation.iteritems(): |
666 except sqlite3.OperationalError as error: | 683 # objects += loadTrajectoriesFromSqlite(k[0], k[1], [p.getNum() for p in v]) |
667 printDBError(error) | 684 except sqlite3.OperationalError as error: |
668 if len(set([p.getTrajectoryType() for p in prototypes])) > 1: | 685 printDBError(error) |
669 print('Different types of prototypes in database ({}).'.format(set([p.getTrajectoryType() for p in prototypes]))) | 686 if len(set([p.getTrajectoryType() for p in prototypes])) > 1: |
687 print('Different types of prototypes in database ({}).'.format(set([p.getTrajectoryType() for p in prototypes]))) | |
670 return prototypes | 688 return prototypes |
671 | 689 |
672 def savePOIsToSqlite(filename, gmm, gmmType, gmmId): | 690 def savePOIsToSqlite(filename, gmm, gmmType, gmmId): |
673 '''Saves a Gaussian mixture model (of class sklearn.mixture.GaussianMixture) | 691 '''Saves a Gaussian mixture model (of class sklearn.mixture.GaussianMixture) |
674 gmmType is a type of GaussianMixture, learnt either from beginnings or ends of trajectories''' | 692 gmmType is a type of GaussianMixture, learnt either from beginnings or ends of trajectories''' |
701 def loadPOIsFromSqlite(filename): | 719 def loadPOIsFromSqlite(filename): |
702 'Loads all 2D Gaussians in the database' | 720 'Loads all 2D Gaussians in the database' |
703 from sklearn import mixture # todo if not avalaible, load data in duck-typed class with same fields | 721 from sklearn import mixture # todo if not avalaible, load data in duck-typed class with same fields |
704 from ast import literal_eval | 722 from ast import literal_eval |
705 pois = [] | 723 pois = [] |
706 with sqlite3.connect(filename) as connection: | 724 if Path(filename).is_file(): |
707 cursor = connection.cursor() | 725 with sqlite3.connect(filename) as connection: |
708 try: | 726 cursor = connection.cursor() |
709 cursor.execute('SELECT * from gaussians2d') | 727 try: |
710 gmmId = None | 728 cursor.execute('SELECT * from gaussians2d') |
711 gmm = [] | 729 gmmId = None |
712 for row in cursor: | 730 gmm = [] |
713 if gmmId is None or row[0] != gmmId: | 731 for row in cursor: |
714 if len(gmm) > 0: | 732 if gmmId is None or row[0] != gmmId: |
715 tmp = mixture.GaussianMixture(len(gmm), covarianceType) | 733 if len(gmm) > 0: |
716 tmp.means_ = array([gaussian['mean'] for gaussian in gmm]) | 734 tmp = mixture.GaussianMixture(len(gmm), covarianceType) |
717 tmp.covariances_ = array([gaussian['covar'] for gaussian in gmm]) | 735 tmp.means_ = array([gaussian['mean'] for gaussian in gmm]) |
718 tmp.weights_ = array([gaussian['weight'] for gaussian in gmm]) | 736 tmp.covariances_ = array([gaussian['covar'] for gaussian in gmm]) |
719 tmp.gmmTypes = [gaussian['type'] for gaussian in gmm] | 737 tmp.weights_ = array([gaussian['weight'] for gaussian in gmm]) |
720 tmp.precisions_cholesky_ = array([gaussian['precisions'] for gaussian in gmm]) | 738 tmp.gmmTypes = [gaussian['type'] for gaussian in gmm] |
721 pois.append(tmp) | 739 tmp.precisions_cholesky_ = array([gaussian['precisions'] for gaussian in gmm]) |
722 gaussian = {'type': row[2], | 740 pois.append(tmp) |
723 'mean': row[3:5], | 741 gaussian = {'type': row[2], |
724 'covar': array(literal_eval(row[5])), | 742 'mean': row[3:5], |
725 'weight': row[7], | 743 'covar': array(literal_eval(row[5])), |
726 'precisions': array(literal_eval(row[8]))} | 744 'weight': row[7], |
727 gmm = [gaussian] | 745 'precisions': array(literal_eval(row[8]))} |
728 covarianceType = row[6] | 746 gmm = [gaussian] |
729 gmmId = row[0] | 747 covarianceType = row[6] |
730 else: | 748 gmmId = row[0] |
731 gmm.append({'type': row[2], | 749 else: |
732 'mean': row[3:5], | 750 gmm.append({'type': row[2], |
733 'covar': array(literal_eval(row[5])), | 751 'mean': row[3:5], |
734 'weight': row[7], | 752 'covar': array(literal_eval(row[5])), |
735 'precisions': array(literal_eval(row[8]))}) | 753 'weight': row[7], |
736 if len(gmm) > 0: | 754 'precisions': array(literal_eval(row[8]))}) |
737 tmp = mixture.GaussianMixture(len(gmm), covarianceType) | 755 if len(gmm) > 0: |
738 tmp.means_ = array([gaussian['mean'] for gaussian in gmm]) | 756 tmp = mixture.GaussianMixture(len(gmm), covarianceType) |
739 tmp.covariances_ = array([gaussian['covar'] for gaussian in gmm]) | 757 tmp.means_ = array([gaussian['mean'] for gaussian in gmm]) |
740 tmp.weights_ = array([gaussian['weight'] for gaussian in gmm]) | 758 tmp.covariances_ = array([gaussian['covar'] for gaussian in gmm]) |
741 tmp.gmmTypes = [gaussian['type'] for gaussian in gmm] | 759 tmp.weights_ = array([gaussian['weight'] for gaussian in gmm]) |
742 tmp.precisions_cholesky_ = array([gaussian['precisions'] for gaussian in gmm]) | 760 tmp.gmmTypes = [gaussian['type'] for gaussian in gmm] |
743 pois.append(tmp) | 761 tmp.precisions_cholesky_ = array([gaussian['precisions'] for gaussian in gmm]) |
744 except sqlite3.OperationalError as error: | 762 pois.append(tmp) |
745 printDBError(error) | 763 except sqlite3.OperationalError as error: |
764 printDBError(error) | |
746 return pois | 765 return pois |
747 | 766 |
748 ######################### | 767 ######################### |
749 # saving and loading for scene interpretation (Mohamed Gomaa Mohamed's PhD) | 768 # saving and loading for scene interpretation (Mohamed Gomaa Mohamed's PhD) |
750 ######################### | 769 ######################### |
1324 self.scaleCyclistSpeed = config.getfloat(self.sectionHeader, 'cyc-speed-scale') | 1343 self.scaleCyclistSpeed = config.getfloat(self.sectionHeader, 'cyc-speed-scale') |
1325 self.meanVehicleSpeed = config.getfloat(self.sectionHeader, 'mean-veh-speed') | 1344 self.meanVehicleSpeed = config.getfloat(self.sectionHeader, 'mean-veh-speed') |
1326 self.stdVehicleSpeed = config.getfloat(self.sectionHeader, 'std-veh-speed') | 1345 self.stdVehicleSpeed = config.getfloat(self.sectionHeader, 'std-veh-speed') |
1327 | 1346 |
1328 def __init__(self, filename = None): | 1347 def __init__(self, filename = None): |
1329 if filename is not None and Path(filename).exists(): | 1348 self.configFilename = filename |
1349 if filename is not None and Path(filename).is_file(): | |
1330 self.loadConfigFile(filename) | 1350 self.loadConfigFile(filename) |
1331 else: | 1351 else: |
1332 print('Configuration filename {} could not be loaded.'.format(filename)) | 1352 print('Configuration filename {} could not be loaded.'.format(filename)) |
1333 | 1353 |
1334 def convertToFrames(self, frameRate, speedRatio = 3.6): | 1354 def convertToFrames(self, frameRate, speedRatio = 3.6): |
1384 self.sectionHeader = config.sections()[0] | 1404 self.sectionHeader = config.sections()[0] |
1385 # Tracking/display parameters | 1405 # Tracking/display parameters |
1386 self.videoFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'video-filename')) | 1406 self.videoFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'video-filename')) |
1387 self.databaseFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'database-filename')) | 1407 self.databaseFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'database-filename')) |
1388 self.homographyFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'homography-filename')) | 1408 self.homographyFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'homography-filename')) |
1389 if Path(self.homographyFilename).exists(): | 1409 if Path(self.homographyFilename).is_file(): |
1390 self.homography = loadtxt(self.homographyFilename) | 1410 self.homography = loadtxt(self.homographyFilename) |
1391 else: | 1411 else: |
1392 self.homography = None | 1412 self.homography = None |
1393 self.intrinsicCameraFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'intrinsic-camera-filename')) | 1413 self.intrinsicCameraFilename = utils.getRelativeFilename(parentPath, config.get(self.sectionHeader, 'intrinsic-camera-filename')) |
1394 if Path(self.intrinsicCameraFilename).exists(): | 1414 if Path(self.intrinsicCameraFilename).is_file(): |
1395 self.intrinsicCameraMatrix = loadtxt(self.intrinsicCameraFilename) | 1415 self.intrinsicCameraMatrix = loadtxt(self.intrinsicCameraFilename) |
1396 else: | 1416 else: |
1397 self.intrinsicCameraMatrix = None | 1417 self.intrinsicCameraMatrix = None |
1398 distortionCoefficients = getValuesFromINIFile(filename, 'distortion-coefficients', '=') | 1418 distortionCoefficients = getValuesFromINIFile(filename, 'distortion-coefficients', '=') |
1399 self.distortionCoefficients = [float(x) for x in distortionCoefficients] | 1419 self.distortionCoefficients = [float(x) for x in distortionCoefficients] |
1442 self.minFeatureDisplacement = config.getfloat(self.sectionHeader, 'min-feature-displacement') | 1462 self.minFeatureDisplacement = config.getfloat(self.sectionHeader, 'min-feature-displacement') |
1443 self.updateTimer = config.getint(self.sectionHeader, 'tracker-reload-time') | 1463 self.updateTimer = config.getint(self.sectionHeader, 'tracker-reload-time') |
1444 | 1464 |
1445 | 1465 |
1446 def __init__(self, filename = None): | 1466 def __init__(self, filename = None): |
1447 if filename is not None and Path(filename).exists(): | 1467 self.configFilename = filename |
1468 if filename is not None and Path(filename).is_file(): | |
1448 self.loadConfigFile(filename) | 1469 self.loadConfigFile(filename) |
1449 else: | 1470 else: |
1450 print('Configuration filename {} could not be loaded.'.format(filename)) | 1471 print('Configuration filename {} could not be loaded.'.format(filename)) |
1451 self.configFilename = filename | |
1452 | 1472 |
1453 def processVideoArguments(args): | 1473 def processVideoArguments(args): |
1454 '''Loads information from configuration file | 1474 '''Loads information from configuration file |
1455 then checks what was passed on the command line | 1475 then checks what was passed on the command line |
1456 for override (eg video filename and database filename''' | 1476 for override (eg video filename and database filename''' |