Mercurial Hosting > traffic-intelligence
changeset 549:b5525249eda1
Merged in mohamedgomaa/trafficintelligence (pull request #7)
add some functions for behaviour analysis and corrected a few bugs
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Tue, 08 Jul 2014 16:32:09 -0400 |
parents | 9816fab353f3 (current diff) e6ab4caf359c (diff) |
children | 5668af2ff515 |
files | python/cvutils.py python/moving.py python/storage.py |
diffstat | 4 files changed, 171 insertions(+), 4 deletions(-) [+] |
line wrap: on
line diff
--- a/python/cvutils.py Tue Jul 08 15:51:43 2014 -0400 +++ b/python/cvutils.py Tue Jul 08 16:32:09 2014 -0400 @@ -210,7 +210,7 @@ croppedImg = img[yCropMin : yCropMax, xCropMin : xCropMax] else: croppedImg = [] - return imgcrop, yCropMin, yCropMax, xCropMin, xCropMax + return croppedImg, yCropMin, yCropMax, xCropMin, xCropMax def displayTrajectories(videoFilename, objects, boundingBoxes = {}, homography = None, firstFrameNum = 0, lastFrameNumArg = None, printFrames = True, rescale = 1., nFramesStep = 1, saveAllImages = False, undistort = False, intrinsicCameraMatrix = None, distortionCoefficients = None, undistortedImageMultiplication = 1.): @@ -425,7 +425,7 @@ prod = dot(homography, augmentedPoints) return prod[0:2]/prod[2] else: - return p + return points def project(homography, p): '''Returns the coordinates of the projection of the point p with coordinates p[0], p[1]
--- a/python/moving.py Tue Jul 08 15:51:43 2014 -0400 +++ b/python/moving.py Tue Jul 08 16:32:09 2014 -0400 @@ -450,6 +450,7 @@ def __repr__(self): return self.__str__() + def __iter__(self): self.iterInstantNum = 0 return self @@ -822,6 +823,17 @@ return MovingObject.distances(obj1, obj2, instant).min() @staticmethod + def distances2(obj1, obj2, instant1,instant2): + from scipy.spatial.distance import cdist + positions1 = [f.getPositionAtInstant(instant1).astuple() for f in obj1.features if f.existsAtInstant(instant1)] + positions2 = [f.getPositionAtInstant(instant2).astuple() for f in obj2.features if f.existsAtInstant(instant2)] + return cdist(positions1, positions2, metric = 'euclidean') + + @staticmethod + def minDistance2(obj1, obj2, instant1,instant2): + return MovingObject.distances2(obj1, obj2, instant1,instant2).min() + + @staticmethod def maxDistance(obj1, obj2, instant): return MovingObject.distances(obj1, obj2, instant).max() @@ -840,7 +852,11 @@ else: print('Load features to compute a maximum size') return None - + + def setRoutes(self,startCode,endCode): + self.startRouteID=startCode + self.endRouteID=endCode + def getInstantsCrossingLane(self, p1, p2): '''Returns the instant(s) at which the object passes from one side of the segment to the other @@ -961,6 +977,7 @@ # what to do: threshold for most common type? self.setUserType() return possibleUserTypes + @staticmethod def collisionCourseDotProduct(movingObject1, movingObject2, instant): 'A positive result indicates that the road users are getting closer'
--- a/python/storage.py Tue Jul 08 15:51:43 2014 -0400 +++ b/python/storage.py Tue Jul 08 16:32:09 2014 -0400 @@ -63,6 +63,155 @@ connection.commit() connection.close() + +def writeFeaturesToSqlite(objects, outFilename, trajectoryType, objectNumbers = -1): + '''write features trajectories maintain trajectory ID,velocities dataset ''' + connection = sqlite3.connect(outFilename) + cursor = connection.cursor() + + cursor.execute("CREATE TABLE IF NOT EXISTS \"positions\"(trajectory_id INTEGER,frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))") + cursor.execute("CREATE TABLE IF NOT EXISTS \"velocities\"(trajectory_id INTEGER,frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))") + + if trajectoryType == 'feature': + if type(objectNumbers) == int and objectNumbers == -1: + for trajectory in objects: + trajectory_id = trajectory.num + frame_number = trajectory.timeInterval.first + for position,velocity in zip(trajectory.getPositions(),trajectory.getVelocities()): + cursor.execute("insert into positions (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)",(trajectory_id,frame_number,position.x,position.y)) + cursor.execute("insert into velocities (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)",(trajectory_id,frame_number,velocity.x,velocity.y)) + frame_number += 1 + + connection.commit() + connection.close() + +def writePrototypesToSqlite(prototypes,nMatching, outFilename): + """ prototype dataset is a dictionary with keys== routes, values== prototypes Ids """ + connection = sqlite3.connect(outFilename) + cursor = connection.cursor() + + cursor.execute("CREATE TABLE IF NOT EXISTS \"prototypes\"(prototype_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, nMatching INTEGER, PRIMARY KEY(prototype_id))") + + for route in prototypes.keys(): + if prototypes[route]!=[]: + for i in prototypes[route]: + cursor.execute("insert into prototypes (prototype_id, routeIDstart,routeIDend, nMatching) values (?,?,?,?)",(i,route[0],route[1],nMatching[route][i])) + + connection.commit() + connection.close() + +def loadPrototypesFromSqlite(filename): + """ + This function loads the prototype file in the database + It returns a dictionary for prototypes for each route and nMatching + """ + prototypes = {} + nMatching={} + + connection = sqlite3.connect(filename) + cursor = connection.cursor() + + try: + cursor.execute('SELECT * from prototypes order by prototype_id, routeIDstart,routeIDend, nMatching') + except sqlite3.OperationalError as error: + utils.printDBError(error) + return [] + + for row in cursor: + route=(row[1],row[2]) + if route not in prototypes.keys(): + prototypes[route]=[] + prototypes[route].append(row[0]) + nMatching[row[0]]=row[3] + + connection.close() + return prototypes,nMatching + +def writeLabelsToSqlite(labels, outFilename): + """ labels is a dictionary with keys: routes, values: prototypes Ids + """ + connection = sqlite3.connect(outFilename) + cursor = connection.cursor() + + cursor.execute("CREATE TABLE IF NOT EXISTS \"labels\"(object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, prototype_id INTEGER, PRIMARY KEY(object_id))") + + for route in labels.keys(): + if labels[route]!=[]: + for i in labels[route]: + for j in labels[route][i]: + cursor.execute("insert into labels (object_id, routeIDstart,routeIDend, prototype_id) values (?,?,?,?)",(j,route[0],route[1],i)) + + connection.commit() + connection.close() + +def loadLabelsFromSqlite(filename): + labels = {} + + connection = sqlite3.connect(filename) + cursor = connection.cursor() + + try: + cursor.execute('SELECT * from labels order by object_id, routeIDstart,routeIDend, prototype_id') + except sqlite3.OperationalError as error: + utils.printDBError(error) + return [] + + for row in cursor: + route=(row[1],row[2]) + p=row[3] + if route not in labels.keys(): + labels[route]={} + if p not in labels[route].keys(): + labels[route][p]=[] + labels[route][p].append(row[0]) + + connection.close() + return labels + +def writeRoutesToSqlite(Routes, outFilename): + """ This function writes the activity path define by start and end IDs""" + connection = sqlite3.connect(outFilename) + cursor = connection.cursor() + + cursor.execute("CREATE TABLE IF NOT EXISTS \"routes\"(object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, PRIMARY KEY(object_id))") + + for route in Routes.keys(): + if Routes[route]!=[]: + for i in Routes[route]: + cursor.execute("insert into routes (object_id, routeIDstart,routeIDend) values (?,?,?)",(i,route[0],route[1])) + + connection.commit() + connection.close() + +def loadRoutesFromSqlite(filename): + Routes = {} + + connection = sqlite3.connect(filename) + cursor = connection.cursor() + + try: + cursor.execute('SELECT * from routes order by object_id, routeIDstart,routeIDend') + except sqlite3.OperationalError as error: + utils.printDBError(error) + return [] + + for row in cursor: + route=(row[1],row[2]) + if route not in Routes.keys(): + Routes[route]=[] + Routes[route].append(row[0]) + + connection.close() + return Routes + +def setRoutes(filename, objects): + connection = sqlite3.connect(filename) + cursor = connection.cursor() + for obj in objects: + cursor.execute('update objects set startRouteID = {} where object_id = {}'.format(obj.startRouteID, obj.getNum())) + cursor.execute('update objects set endRouteID = {} where object_id = {}'.format(obj.endRouteID, obj.getNum())) + connection.commit() + connection.close() def setRoadUserTypes(filename, objects): '''Saves the user types of the objects in the sqlite database stored in filename
--- a/python/utils.py Tue Jul 08 15:51:43 2014 -0400 +++ b/python/utils.py Tue Jul 08 16:32:09 2014 -0400 @@ -246,9 +246,10 @@ def crossProduct(l1, l2): return l1[0]*l2[1]-l1[1]*l2[0] -def filterMovingWindow(input, halfWidth): +def filterMovingWindow(inputSignal, halfWidth): '''Returns an array obtained after the smoothing of the input by a moving average The first and last points are copied from the original.''' + from numpy import ones,convolve,array width = float(halfWidth*2+1) win = ones(width,'d') result = convolve(win/width,array(inputSignal),'same')