Mercurial Hosting > traffic-intelligence
changeset 998:933670761a57
updated code to python 3 (tests pass and scripts run, but non-executed parts of code are probably still not correct)
line wrap: on
line diff
--- a/python/cvutils.py Fri May 25 18:15:18 2018 -0400 +++ b/python/cvutils.py Sun May 27 23:22:48 2018 -0400 @@ -57,8 +57,8 @@ def int2FOURCC(x): fourcc = '' - for i in xrange(4): - fourcc += unichr((x >> 8*i)&255) + for i in range(4): + fourcc += chr((x >> 8*i)&255) return fourcc def rgb2gray(rgb): @@ -79,8 +79,8 @@ '''Converts an OpenCV CvMat to numpy array.''' print('Deprecated, use new interface') a = zeros((cvmat.rows, cvmat.cols))#array([[0.0]*cvmat.width]*cvmat.height) - for i in xrange(cvmat.rows): - for j in xrange(cvmat.cols): + for i in range(cvmat.rows): + for j in range(cvmat.cols): a[i,j] = cvmat[i,j] return a @@ -127,7 +127,7 @@ print('Empty filename list') return if windowNames is None: - windowNames = ['frame{}'.format(i) for i in xrange(len(filenames))] + windowNames = ['frame{}'.format(i) for i in range(len(filenames))] wait = 5 if rescale == 1.: for windowName in windowNames: @@ -142,8 +142,8 @@ ret = True nFramesShown = 0 if firstFrameNums is not None: - for i in xrange(len(captures)): - captures[i].set(cv2.PROP_POS_FRAMES, firstFrameNums[i]) + for i in range(len(captures)): + captures[i].set(cv2.CAP_PROP_POS_FRAMES, firstFrameNums[i]) while ret and not quitKey(key): rets = [] images = [] @@ -155,7 +155,7 @@ if ret: if printFrames: print('frame shown {0}'.format(nFramesShown)) - for i in xrange(len(filenames)): + for i in range(len(filenames)): if text is not None: cv2.putText(images[i], text, (10,50), cv2.FONT_HERSHEY_PLAIN, 1, cvRed[colorType]) cvImshow(windowNames[i], images[i], rescale) # cv2.imshow('frame', img) @@ -164,7 +164,7 @@ cv2.imwrite('image-{}.png'.format(frameNum), img) nFramesShown += step if step > 1: - for i in xrange(len(captures)): + for i in range(len(captures)): captures[i].set(cv2.CAP_PROP_POS_FRAMES, firstFrameNums[i]+nFramesShown) cv2.destroyAllWindows() else: @@ -331,7 +331,7 @@ if undistort: obj.projectedPositions = obj.projectedPositions.newCameraProject(newCameraMatrix) cvPlot(img, obj.projectedPositions, cvColors[colorType][obj.getNum()], frameNum-obj.getFirstInstant()) - if frameNum not in boundingBoxes.keys() and obj.hasFeatures(): + if frameNum not in boundingBoxes and obj.hasFeatures(): yCropMin, yCropMax, xCropMin, xCropMax = imageBoxSize(obj, frameNum, homography, width, height) cv2.rectangle(img, (xCropMin, yCropMin), (xCropMax, yCropMax), cvBlue[colorType], 1) objDescription = '{} '.format(obj.num) @@ -344,7 +344,7 @@ if obj.getLastInstant() == frameNum: objects.remove(obj) # plot object bounding boxes - if frameNum in boundingBoxes.keys(): + if frameNum in boundingBoxes: for rect in boundingBoxes[frameNum]: cv2.rectangle(img, rect[0].asint().astuple(), rect[1].asint().astuple(), cvColors[colorType][obj.getNum()]) # plot ground truth @@ -506,15 +506,6 @@ [map1, map2] = computeUndistortMaps(width, height, undistortedImageMultiplication, intrinsicCameraMatrix, distortionCoefficients) return cv2.remap(img, map1, map2, interpolation=interpolation) - -def printCvMat(cvmat, out = stdout): - '''Prints the cvmat to out''' - print('Deprecated, use new interface') - for i in xrange(cvmat.rows): - for j in xrange(cvmat.cols): - out.write('{0} '.format(cvmat[i,j])) - out.write('\n') - def homographyProject(points, homography, output3D = False): '''Returns the coordinates of the points (2xN array) projected through homography''' if points.shape[0] != 2:
--- a/python/events.py Fri May 25 18:15:18 2018 -0400 +++ b/python/events.py Sun May 27 23:22:48 2018 -0400 @@ -21,7 +21,7 @@ routeSim={} lcss = utils.LCSS(similarityFunc=lambda x,y: (distanceForLCSS(x,y) <= spatialThreshold),delta=delta) for y in prototypesRoutes: - if y in prototypes.keys(): + if y in prototypes: prototypesIDs=prototypes[y] similarity=[] for x in prototypesIDs: @@ -37,7 +37,7 @@ def getRoute(obj,prototypes,objects,noiseEntryNums,noiseExitNums,useDestination=True): route=(obj.startRouteID,obj.endRouteID) if useDestination: - if route not in prototypes.keys(): + if route not in prototypes: route= findRoute(prototypes,objects,route,obj.getNum(),noiseEntryNums,noiseExitNums) return route @@ -153,7 +153,7 @@ '''Returns list of indicator values at instant as dict (with keys from indicators dict)''' values = {} - for k, indicator in self.indicators.iteritems(): + for k, indicator in self.indicators.items(): values[k] = indicator[instant] return values @@ -225,7 +225,7 @@ else: commonTimeInterval = self.timeInterval self.collisionPoints, crossingZones = predictionParameters.computeCrossingsCollisions(self.roadUser1, self.roadUser2, collisionDistanceThreshold, timeHorizon, computeCZ, debug, commonTimeInterval) - for i, cps in self.collisionPoints.iteritems(): + for i, cps in self.collisionPoints.items(): TTCs[i] = prediction.SafetyPoint.computeExpectedIndicator(cps) collisionProbabilities[i] = sum([p.probability for p in cps]) if len(TTCs) > 0: @@ -236,7 +236,7 @@ if computeCZ: self.crossingZones = crossingZones pPETs = {} - for i, cz in self.crossingZones.iteritems(): + for i, cz in self.crossingZones.items(): pPETs[i] = prediction.SafetyPoint.computeExpectedIndicator(cz) self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[9], pPETs, mostSevereIsMax=False)) # TODO add probability of collision, and probability of successful evasive action @@ -269,10 +269,10 @@ interactions = [] num = 0 - for i in xrange(len(objects)): + for i in range(len(objects)): if _others is None: others = objects[:i] - for j in xrange(len(others)): + for j in range(len(others)): commonTimeInterval = objects[i].commonTimeInterval(others[j]) if not commonTimeInterval.empty(): interactions.append(Interaction(num, commonTimeInterval, objects[i].num, others[j].num, objects[i], others[j]))
--- a/python/indicators.py Fri May 25 18:15:18 2018 -0400 +++ b/python/indicators.py Sun May 27 23:22:48 2018 -0400 @@ -6,7 +6,7 @@ from matplotlib.pyplot import plot, ylim from matplotlib.pylab import find from numpy import array, arange, mean, floor, mean - +from scipy import percentile def multivariateName(indicatorNames): return '_'.join(indicatorNames) @@ -35,7 +35,7 @@ assert len(values) == timeInterval.length() self.timeInterval = timeInterval self.values = {} - for i in xrange(int(round(self.timeInterval.length()))): + for i in range(int(round(self.timeInterval.length()))): self.values[self.timeInterval[i]] = values[i] self.maxValue = maxValue @@ -60,7 +60,7 @@ self.iterInstantNum = 0 # index in the interval or keys of the dict return self - def next(self): + def __next__(self): if self.iterInstantNum >= len(self.values):#(self.timeInterval and self.iterInstantNum>=self.timeInterval.length())\ # or (self.iterInstantNum >= self.values) raise StopIteration @@ -160,14 +160,25 @@ TemporalIndicator.__init__(self, name, values, timeInterval, maxValue) self.mostSevereIsMax = mostSevereIsMax - def getMostSevereValue(self, minNInstants=1): # TODO use np.percentile - values = array(self.values.values()) - indices = range(len(values)) - if len(indices) >= minNInstants: - values = sorted(values[indices], reverse = self.mostSevereIsMax) # inverted if most severe is max -> take the first values - return mean(values[:minNInstants]) + def getMostSevereValue(self, minNInstants=1, centile=15.): + '''if there are more than minNInstants observations, + returns either the average of these maximum values + or if centile is not None the n% centile from the most severe value + + eg for TTC, 15 returns the 15th centile (value such that 15% of observations are lower)''' + if self.__len__() < minNInstants: + return None else: - return None + values = list(self.values.values()) + if centile is not None: + if self.mostSevereIsMax: + c = 100-centile + else: + c = centile + return percentile(values, c) + else: + values = sorted(values, reverse = self.mostSevereIsMax) # inverted if most severe is max -> take the first values + return mean(values[:minNInstants]) def getInstantOfMostSevereValue(self): '''Returns the instant at which the indicator reaches its most severe value''' @@ -189,15 +200,15 @@ assert len(indicatorValues) == trajectory.length() indicatorMap = {} - for k in xrange(trajectory.length()): + for k in range(trajectory.length()): p = trajectory[k] i = floor(p.x/squareSize) j = floor(p.y/squareSize) - if indicatorMap.has_key((i,j)): + if (i,j) in indicatorMap: indicatorMap[(i,j)].append(indicatorValues[k]) else: indicatorMap[(i,j)] = [indicatorValues[k]] - for k in indicatorMap.keys(): + for k in indicatorMap: indicatorMap[k] = mean(indicatorMap[k]) return indicatorMap @@ -210,7 +221,7 @@ # points.append([x,y]) # inside = nx.points_inside_poly(array(points), polygon) # indicatorMap = {} -# for i in xrange(len(inside)): +# for i in range(len(inside)): # if inside[i]: # indicatorMap[(floor(points[i][0]/squareSize), floor(points[i][1]/squareSize))] = 0 # return indicatorMap @@ -229,12 +240,12 @@ if more than one maps has a value)''' indicatorMap = {} for m in maps: - for k,v in m.iteritems(): - if indicatorMap.has_key(k): + for k,v in m.items(): + if k in indicatorMap: indicatorMap[k].append(v) else: indicatorMap[k] = [v] - for k in indicatorMap.keys(): + for k in indicatorMap: indicatorMap[k] = combinationFunction(indicatorMap[k]) return indicatorMap
--- a/python/ml.py Fri May 25 18:15:18 2018 -0400 +++ b/python/ml.py Sun May 27 23:22:48 2018 -0400 @@ -306,7 +306,7 @@ fig = plt.figure() if len(fig.get_axes()) == 0: fig.add_subplot(111) - for i in xrange(model.n_components): + for i in range(model.n_components): mean = model.means_[i]/nUnitsPerPixel covariance = model.covariances_[i]/nUnitsPerPixel # plot points
--- a/python/moving.py Fri May 25 18:15:18 2018 -0400 +++ b/python/moving.py Sun May 27 23:22:48 2018 -0400 @@ -121,7 +121,7 @@ self.iterInstantNum = -1 return self - def next(self): + def __next__(self): if self.iterInstantNum >= self.length()-1: raise StopIteration else: @@ -378,7 +378,7 @@ prepared_polygon = polygon else: prepared_polygon = prep(polygon) - return filter(prepared_polygon.contains, points) + return list(filter(prepared_polygon.contains, points)) # Functions for coordinate transformation # From Paul St-Aubin's PVA tools @@ -416,7 +416,7 @@ 'Approximates slope singularity by giving some slope roundoff; account for roundoff error' for spline in splines: p1 = spline[0] - for i in xrange(len(spline)-1): + for i in range(len(spline)-1): p2 = spline[i+1] if(round(p1.x, 10) == round(p2.x, 10)): p2.x += 0.0000000001 @@ -665,7 +665,7 @@ t = Trajectory() p0 = Point(p.x, p.y) t.addPosition(p0) - for i in xrange(nPoints-1): + for i in range(nPoints-1): p0 += v t.addPosition(p0) return t, Trajectory([[v.x]*nPoints, [v.y]*nPoints]) @@ -704,7 +704,7 @@ raise TypeError("Invalid argument type.") def __str__(self): - return ' '.join([self.__getitem__(i).__str__() for i in xrange(self.length())]) + return ' '.join([self.__getitem__(i).__str__() for i in range(self.length())]) def __repr__(self): return self.__str__() @@ -713,7 +713,7 @@ self.iterInstantNum = 0 return self - def next(self): + def __next__(self): if self.iterInstantNum >= self.length(): raise StopIteration else: @@ -818,7 +818,7 @@ def differentiate(self, doubleLastPosition = False): diff = Trajectory() - for i in xrange(1, self.length()): + for i in range(1, self.length()): diff.addPosition(self[i]-self[i-1]) if doubleLastPosition: diff.addPosition(diff[-1]) @@ -855,7 +855,7 @@ self.cumulativeDistances = [0.] p1 = self[0] cumulativeDistance = 0. - for i in xrange(self.length()-1): + for i in range(self.length()-1): p2 = self[i+1] self.distances.append(Point.distanceNorm2(p1,p2)) cumulativeDistance += self.distances[-1] @@ -922,7 +922,7 @@ indices = [] intersections = [] - for i in xrange(self.length()-1): + for i in range(self.length()-1): q1=self.__getitem__(i) q2=self.__getitem__(i+1) p = segmentIntersection(q1, q2, p1, p2) @@ -944,7 +944,7 @@ indices = [] intersections = [] - for i in xrange(self.length()-1): + for i in range(self.length()-1): q1=self.__getitem__(i) q2=self.__getitem__(i+1) p = segmentLineIntersection(p1, p2, q1, q2) @@ -1077,7 +1077,7 @@ def differentiate(self, doubleLastPosition = False): diff = CurvilinearTrajectory() p1 = self[0] - for i in xrange(1, self.length()): + for i in range(1, self.length()): p2 = self[i] diff.addPositionSYL(p2[0]-p1[0], p2[1]-p1[1], p1[2]) p1=p2 @@ -1091,7 +1091,7 @@ (in provided lane if lane is not None) Returns an empty list if there is no crossing''' indices = [] - for i in xrange(self.length()-1): + for i in range(self.length()-1): q1=self.__getitem__(i) q2=self.__getitem__(i+1) if q1[0] <= S1 < q2[0] and (lane is None or (self.lanes[i] == lane and self.lanes[i+1] == lane)): @@ -1312,7 +1312,7 @@ if withOrigin and len(instants)>0: plot([instants[0]], [coords[0]], 'ro', **kwargs) else: - print('Object {} has no curvilinear positions'.format(self.getNum())) + print('Object {} has no curvilinear positions'.format(self.getNum())) def setUserType(self, userType): self.userType = userType @@ -1421,7 +1421,7 @@ def speedDiagnostics(self, framerate = 1., display = False, nInstantsIgnoredAtEnds=0): speeds = framerate*self.getSpeeds(nInstantsIgnoredAtEnds) - coef = utils.linearRegression(range(len(speeds)), speeds) + coef = utils.linearRegression(list(range(len(speeds))), speeds) print('min/5th perc speed: {} / {}\nspeed diff: {}\nspeed stdev: {}\nregression: {}'.format(min(speeds), scoreatpercentile(speeds, 5), speeds[-2]-speeds[1], std(speeds), coef[0])) if display: from matplotlib.pyplot import figure, axis @@ -1556,7 +1556,7 @@ self.curvilinearPositions = CurvilinearTrajectory() #For each point - for i in xrange(int(self.length())): + for i in range(int(self.length())): result = getSYfromXY(self.getPositionAt(i), alignments) # Error handling @@ -1572,7 +1572,7 @@ ## Recalculate projected point to new lane lanes = self.curvilinearPositions.getLanes() if(lanes != smoothed_lanes): - for i in xrange(len(lanes)): + for i in range(len(lanes)): if(lanes[i] != smoothed_lanes[i]): result = getSYfromXY(self.getPositionAt(i),[alignments[smoothed_lanes[i]]]) @@ -1596,8 +1596,8 @@ else: # compute the relative position vectors relativePositions = {} # relativePositions[(i,j)] is the position of j relative to i - for i in xrange(nFeatures): - for j in xrange(i): + for i in range(nFeatures): + for j in range(i): fi = self.features[i] fj = self.features[j] inter = fi.commonTimeInterval(fj) @@ -1850,7 +1850,7 @@ else: gtMatches = None toMatches = None - for t in xrange(firstInstant, lastInstant+1): + for t in range(firstInstant, lastInstant+1): previousMatches = matches.copy() # go through currently matched GT-TO and check if they are still matched withing matchingDistance toDelete = [] @@ -1867,8 +1867,8 @@ del matches[a] # match all unmatched GT-TO - matchedGTs = matches.keys() - matchedTOs = matches.values() + matchedGTs = list(matches.keys()) + matchedTOs = list(matches.values()) costs = [] unmatchedGTs = [a for a in annotations if a.existsAtInstant(t) and a not in matchedGTs] unmatchedTOs = [o for o in objects if o.existsAtInstant(t) and o not in matchedTOs] @@ -1884,9 +1884,9 @@ matches[unmatchedGTs[k]]=unmatchedTOs[v] dist += costs[k][v] if debug: - print('{} '.format(t)+', '.join(['{} {}'.format(k.getNum(), v.getNum()) for k,v in matches.iteritems()])) + print('{} '.format(t)+', '.join(['{} {}'.format(k.getNum(), v.getNum()) for k,v in matches.items()])) if returnMatches: - for a,o in matches.iteritems(): + for a,o in matches.items(): gtMatches[a.getNum()][t] = o.getNum() toMatches[o.getNum()][t] = a.getNum() @@ -1902,10 +1902,10 @@ if a in previousMatches: if matches[a] != previousMatches[a]: mismatches.append(a) - elif matches[a] in previousMatches.values(): + elif matches[a] in list(previousMatches.values()): mismatches.append(matches[a]) for a in previousMatches: - if a not in matches and previousMatches[a] in matches.values(): + if a not in matches and previousMatches[a] in list(matches.values()): mismatches.append(previousMatches[a]) if debug: for mm in set(mismatches):
--- a/python/objectsmoothing.py Fri May 25 18:15:18 2018 -0400 +++ b/python/objectsmoothing.py Sun May 27 23:22:48 2018 -0400 @@ -50,7 +50,7 @@ tmp={} delta={} for i in featureList: - for t in xrange(i[1],i[2]+1): + for t in range(i[1],i[2]+1): tmp[t]=[i[0],i[3]] newTraj = moving.Trajectory() @@ -152,7 +152,7 @@ #solve a smoothing problem in case of big drop in computing bearing (0,360) for t,i in enumerate(sorted(bearing.keys())): if i!= max(bearing.keys()) and abs(bearingInput[t] - bearingInput[t+1])>=340: - for x in xrange(max(i-halfWidth,min(bearing.keys())),min(i+halfWidth,max(bearing.keys()))+1): + for x in range(max(i-halfWidth,min(bearing.keys())),min(i+halfWidth,max(bearing.keys()))+1): bearing[x]=bearingInput[t-i+x] translated = moving.Trajectory() @@ -166,7 +166,7 @@ if smoothing: d1= translated[halfWidth]- feature.positions[halfWidth] d2= translated[-halfWidth-1]- feature.positions[-halfWidth-1] - for i in xrange(halfWidth): + for i in range(halfWidth): p1= feature.getPositionAt(i)+d1 p2= feature.getPositionAt(-i-1)+d2 translated.setPosition(i,p1)
--- a/python/pavement.py Fri May 25 18:15:18 2018 -0400 +++ b/python/pavement.py Sun May 27 23:22:48 2018 -0400 @@ -34,10 +34,10 @@ def caracteristiques(rtss, maintenanceLevel, rtssWeatherStation, fmr, paintType): '''Computes characteristic data for the RTSS (class rtss) - maintenanceLevel = pylab.csv2rec('C:\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\exigence_circuits.txt', delimiter = ';') - rtssWeatherStation = pylab.csv2rec('C:\Users\Alexandre\Desktop\Projet_maitrise_recherche\stations_environnement_canada\\rtssWeatherStation\juste_pour_rtss_avec_donnees_entretien_hiv\\rtssWeatherStation_EC3.txt', delimiter = ',') - fmr = pylab.csv2rec('C:\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\fmr.txt', delimiter = ';') - paintType = pylab.csv2rec('C:\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\type_peinture.txt', delimiter = ';') + maintenanceLevel = pylab.csv2rec('C:\\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\exigence_circuits.txt', delimiter = ';') + rtssWeatherStation = pylab.csv2rec('C:\\Users\Alexandre\Desktop\Projet_maitrise_recherche\stations_environnement_canada\\rtssWeatherStation\juste_pour_rtss_avec_donnees_entretien_hiv\\rtssWeatherStation_EC3.txt', delimiter = ',') + fmr = pylab.csv2rec('C:\\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\fmr.txt', delimiter = ';') + paintType = pylab.csv2rec('C:\\Users\Alexandre\Desktop\Projet_maitrise_recherche\BDD_access\\analyse_donnees_deneigement\\type_peinture.txt', delimiter = ';') ''' # determination exigence deneigement if rtss.id in maintenanceLevel['rtss_debut']: @@ -103,7 +103,7 @@ def winterMaintenanceIndicators(data, startDate, endDate, circuitReference, snowThreshold): '''Computes several winter maintenance indicators - data = entretien_hivernal = pylab.csv2rec('C:\Users\Alexandre\Documents\Cours\Poly\Projet\mesures_entretien_hivernal\mesures_deneigement.txt', delimiter = ',')''' + data = entretien_hivernal = pylab.csv2rec('C:\\Users\Alexandre\Documents\Cours\Poly\Projet\mesures_entretien_hivernal\mesures_deneigement.txt', delimiter = ',')''' import datetime somme_eau, somme_neige, somme_abrasif, somme_sel, somme_lc, somme_lrg, somme_lrd, compteur_premiere_neige, compteur_somme_abrasif = 0,0,0,0,0,0,0,0,0
--- a/python/poly-utils.py Fri May 25 18:15:18 2018 -0400 +++ b/python/poly-utils.py Sun May 27 23:22:48 2018 -0400 @@ -23,7 +23,7 @@ inter = Interaction(interactionNum, TimeInterval(indicatorFrameNums[0],indicatorFrameNums[-1]), roaduserNum1, roaduserNum2) inter.addVideoFilename(videoFilename) inter.addInteractionType(interactionType) - for key in indicatorsNames.keys(): + for key in indicatorsNames: values= {} for i,t in enumerate(indicatorFrameNums): values[t] = data[i,key] @@ -115,7 +115,7 @@ values[k]=v return SeverityIndicator(indicatorName, values, mostSevereIsMax = False, maxValue = 1.), roadUserData else: - for i in xrange(time[0],time[-1]+1): + for i in range(time[0],time[-1]+1): try: tmp = getDataAtInstant(roadUserData, i) values[i] = np.sum(tmp[:,5]*tmp[:,6])/np.sum(tmp[:,5])/frameRate
--- a/python/prediction.py Fri May 25 18:15:18 2018 -0400 +++ b/python/prediction.py Sun May 27 23:22:48 2018 -0400 @@ -24,13 +24,13 @@ #self.crossingZones = {} def predictPosition(self, nTimeSteps): - if nTimeSteps > 0 and not nTimeSteps in self.predictedPositions.keys(): + if nTimeSteps > 0 and not nTimeSteps in self.predictedPositions: self.predictPosition(nTimeSteps-1) self.predictedPositions[nTimeSteps], self.predictedSpeedOrientations[nTimeSteps] = moving.predictPosition(self.predictedPositions[nTimeSteps-1], self.predictedSpeedOrientations[nTimeSteps-1], self.getControl(), self.maxSpeed) return self.predictedPositions[nTimeSteps] def getPredictedTrajectory(self): - return moving.Trajectory.fromPointList(self.predictedPositions.values()) + return moving.Trajectory.fromPointList(list(self.predictedPositions.values())) def getPredictedSpeeds(self): return [so.norm for so in self.predictedSpeedOrientations.values()] @@ -83,7 +83,7 @@ self.ratio = self.initialSpeed/prototype.getVelocityAt(self.closestPointIdx).norm2() def predictPosition(self, nTimeSteps): - if nTimeSteps > 0 and not nTimeSteps in self.predictedPositions.keys(): + if nTimeSteps > 0 and not nTimeSteps in self.predictedPositions: deltaPosition = copy(self.deltaPosition) if self.constantSpeed: traj = self.prototype.getPositions() @@ -172,11 +172,11 @@ else: figure() for et in predictedTrajectories1: - for t in xrange(int(np.round(timeHorizon))): + for t in range(int(np.round(timeHorizon))): et.predictPosition(t) et.plot('rx') for et in predictedTrajectories2: - for t in xrange(int(np.round(timeHorizon))): + for t in range(int(np.round(timeHorizon))): et.predictPosition(t) et.plot('bx') obj1.plot('r', withOrigin = True) @@ -187,13 +187,13 @@ savefig('predicted-trajectories-t-{0}.png'.format(currentInstant)) def calculateProbability(nMatching,similarity,objects): - sumFrequencies=sum([nMatching[p] for p in similarity.keys()]) + sumFrequencies=sum([nMatching[p] for p in similarity]) prototypeProbability={} - for i in similarity.keys(): + for i in similarity: prototypeProbability[i]= similarity[i] * float(nMatching[i])/sumFrequencies - sumProbabilities= sum([prototypeProbability[p] for p in prototypeProbability.keys()]) + sumProbabilities= sum([prototypeProbability[p] for p in prototypeProbability]) probabilities={} - for i in prototypeProbability.keys(): + for i in prototypeProbability: probabilities[objects[i]]= float(prototypeProbability[i])/sumProbabilities return probabilities @@ -208,7 +208,7 @@ lcss = LCSS(similarityFunc=lambda x,y: (distanceForLCSS(x,y) <= spatialThreshold),delta=delta) similarity={} for y in prototypesRoutes: - if y in prototypes.keys(): + if y in prototypes: prototypesIDs=prototypes[y] for x in prototypesIDs: s=lcss.computeNormalized(partialObjPositions, objects[x].positions) @@ -220,7 +220,7 @@ return probabilities else: mostMatchedValues=sorted(similarity.values(),reverse=True)[:mostMatched] - keys=[k for k in similarity.keys() if similarity[k] in mostMatchedValues] + keys=[k for k in similarity if similarity[k] in mostMatchedValues] newSimilarity={} for i in keys: newSimilarity[i]=similarity[i] @@ -240,7 +240,7 @@ lcss = LCSS(similarityFunc=lambda x,y: (distanceForLCSS(x,y) <= spatialThreshold),delta=delta) similarity={} for y in prototypesRoutes: - if y in prototypes.keys(): + if y in prototypes: prototypesIDs=prototypes[y] for x in prototypesIDs: s=lcss.computeNormalized(partialObjPositions, objects[x].positions) @@ -248,8 +248,8 @@ similarity[x]=s newSimilarity={} - for i in similarity.keys(): - if i in secondStepPrototypes.keys(): + for i in similarity: + if i in secondStepPrototypes: for j in secondStepPrototypes[i]: newSimilarity[j]=similarity[i] probabilities= calculateProbability(nMatching,newSimilarity,objects) @@ -317,7 +317,7 @@ crossingZones = {} else: crossingZones = None - if timeInterval: + if timeInterval is not None: commonTimeInterval = timeInterval else: commonTimeInterval = obj1.commonTimeInterval(obj2) @@ -334,7 +334,7 @@ '''Computes only collision probabilities Returns for each instant the collision probability and number of samples drawn''' collisionProbabilities = {} - if timeInterval: + if timeInterval is not None: commonTimeInterval = timeInterval else: commonTimeInterval = obj1.commonTimeInterval(obj2) @@ -393,7 +393,7 @@ positions = [obj.getPositionAtInstant(instant)] velocities = [obj.getVelocityAtInstant(instant)] probability = 1./float(len(positions)*self.nPredictedTrajectories) - for i in xrange(self.nPredictedTrajectories): + for i in range(self.nPredictedTrajectories): for initialPosition,initialVelocity in zip(positions, velocities): predictedTrajectories.append(PredictedTrajectoryRandomControl(initialPosition, initialVelocity, @@ -450,7 +450,7 @@ positions = [obj.getPositionAtInstant(instant)] velocities = [obj.getVelocityAtInstant(instant)] probability = 1./float(self.nPredictedTrajectories) - for i in xrange(self.nPredictedTrajectories): + for i in range(self.nPredictedTrajectories): for initialPosition,initialVelocity in zip(positions, velocities): predictedTrajectories.append(PredictedTrajectoryConstant(initialPosition, initialVelocity,
--- a/python/processing.py Fri May 25 18:15:18 2018 -0400 +++ b/python/processing.py Sun May 27 23:22:48 2018 -0400 @@ -13,8 +13,8 @@ for o in objects: inPolygon = nx.points_inside_poly(o.getPositions().asArray().T, zone.T) if inPolygon.any(): - objspeeds = [o.getVelocityAt(i).norm2() for i in xrange(int(o.length()-1)) if inPolygon[i]] + objspeeds = [o.getVelocityAt(i).norm2() for i in range(int(o.length()-1)) if inPolygon[i]] speeds[o.num] = np.mean(objspeeds) # km/h else: objectsNotInZone.append(o) - return speeds.values(), speeds, objectsNotInZone + return speeds, objectsNotInZone
--- a/python/run-tests.sh Fri May 25 18:15:18 2018 -0400 +++ b/python/run-tests.sh Sun May 27 23:22:48 2018 -0400 @@ -2,9 +2,9 @@ # for file in tests/*... basename for f in ./*.py do - python $f + python3 $f done for f in ./tests/*.py do - python $f + python3 $f done
--- a/python/sensors.py Fri May 25 18:15:18 2018 -0400 +++ b/python/sensors.py Sun May 27 23:22:48 2018 -0400 @@ -58,7 +58,7 @@ else: detectionInstants.append(mean(instants)) result = True - for i in xrange(len(sensors)-1): + for i in range(len(sensors)-1): result = result and (detectionInstants[i] <= detectionInstants[i+1]) if not result: return result
--- a/python/storage.py Fri May 25 18:15:18 2018 -0400 +++ b/python/storage.py Sun May 27 23:22:48 2018 -0400 @@ -634,7 +634,7 @@ sys.exit() try: cursor.execute('CREATE TABLE IF NOT EXISTS gaussians2d (poi_id INTEGER, id INTEGER, type VARCHAR, x_center REAL, y_center REAL, covariance VARCHAR, covariance_type VARCHAR, weight, precisions_cholesky VARCHAR, PRIMARY KEY(poi_id, id))') - for i in xrange(gmm.n_components): + for i in range(gmm.n_components): cursor.execute('INSERT INTO gaussians2d VALUES(?,?,?,?,?,?,?,?,?)', (gmmId, i, gmmType, gmm.means_[i][0], gmm.means_[i][1], str(gmm.covariances_[i].tolist()), gmm.covariance_type, gmm.weights_[i], str(gmm.precisions_cholesky_[i].tolist()))) connection.commit() except sqlite3.OperationalError as error: @@ -710,7 +710,7 @@ 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(): + for route in prototypes: 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])) @@ -737,7 +737,7 @@ for row in cursor: route=(row[1],row[2]) - if route not in prototypes.keys(): + if route not in prototypes: prototypes[route]=[] prototypes[route].append(row[0]) nMatching[row[0]]=row[3] @@ -753,7 +753,7 @@ 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(): + for route in labels: if labels[route]!=[]: for i in labels[route]: for j in labels[route][i]: @@ -777,9 +777,9 @@ for row in cursor: route=(row[1],row[2]) p=row[3] - if route not in labels.keys(): + if route not in labels: labels[route]={} - if p not in labels[route].keys(): + if p not in labels[route]: labels[route][p]=[] labels[route][p].append(row[0]) @@ -793,7 +793,7 @@ cursor.execute("CREATE TABLE IF NOT EXISTS speedprototypes (spdprototype_id INTEGER,prototype_id INTEGER,routeID_start INTEGER, routeID_end INTEGER, nMatching INTEGER, PRIMARY KEY(spdprototype_id))") - for route in prototypes.keys(): + for route in prototypes: if prototypes[route]!={}: for i in prototypes[route]: if prototypes[route][i]!= []: @@ -820,9 +820,9 @@ for row in cursor: route=(row[2],row[3]) - if route not in prototypes.keys(): + if route not in prototypes: prototypes[route]={} - if row[1] not in prototypes[route].keys(): + if row[1] not in prototypes[route]: prototypes[route][row[1]]=[] prototypes[route][row[1]].append(row[0]) nMatching[row[0]]=row[4] @@ -838,7 +838,7 @@ cursor.execute("CREATE TABLE IF NOT EXISTS routes (object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, PRIMARY KEY(object_id))") - for route in Routes.keys(): + for route in Routes: if Routes[route]!=[]: for i in Routes[route]: cursor.execute("insert into routes (object_id, routeIDstart,routeIDend) values (?,?,?)",(i,route[0],route[1])) @@ -860,7 +860,7 @@ for row in cursor: route=(row[1],row[2]) - if route not in Routes.keys(): + if route not in Routes: Routes[route]=[] Routes[route].append(row[0]) @@ -928,21 +928,15 @@ values.append(l.split(delimiterChar)[1].strip()) return values -class FakeSecHead(object): - '''Add fake section header [asection] +def addSectionHeader(propertiesFile, headerName = 'main'): + '''Add fake section header from http://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788 use read_file in Python 3.2+ ''' - def __init__(self, fp): - self.fp = fp - self.sechead = '[main]\n' - - def readline(self): - if self.sechead: - try: return self.sechead - finally: self.sechead = None - else: return self.fp.readline() + yield '[{}]\n'.format(headerName) + for line in propertiesFile: + yield line def loadPemsTraffic(filename): '''Loads traffic data downloaded from the http://pems.dot.ca.gov clearinghouse @@ -952,7 +946,7 @@ items = l.split(',') headers = ['time', 'station', 'district', 'route', 'direction', 'lanetype', 'length', 'nsamples', 'pctobserved', 'flow', 'occupancy', 'speed', 'delay35', 'delay40', 'delay45', 'delay50', 'delay55', 'delay60'] nLanes = (len(items)-len(headers))/3 - for i in xrange(nLanes): + for i in range(nLanes): headers += ['flow{}'.format(i+1), 'occupancy{}'.format(i+1), 'speed{}'.format(i+1)] f.close() return read_csv(filename, delimiter = ',', names = headers) @@ -1029,7 +1023,7 @@ # positions should be rounded to nDecimals decimals only objects[objNum].curvilinearPositions = moving.CurvilinearTrajectory(S = npround(tmp['POS'].tolist(), nDecimals), Y = npround(tmp['POSLAT'].tolist(), nDecimals), lanes = tmp['LANE'].tolist()) if objectNumbers is not None and objectNumbers > 0 and len(objects) >= objectNumbers: - objects.values() + return list(objects.values()) else: if filename.endswith(".fzp"): inputfile = openCheck(filename, quitting = True) @@ -1077,7 +1071,7 @@ printDBError(error) else: print("File type of "+filename+" not supported (only .sqlite and .fzp files)") - return objects.values() + return list(objects.values()) def selectPDLanes(data, lanes = None): '''Selects the subset of data for the right lanes @@ -1257,7 +1251,7 @@ timeInterval = obj.getTimeInterval() positions = obj.getPositions() curvilinearPositions = obj.getCurvilinearPositions() - for i in xrange(int(obj.length())): + for i in range(int(obj.length())): p1 = positions[i] s = '{},{},{},{}'.format(obj.num,timeInterval[i],p1.x,p1.y) if curvilinearPositions is not None: @@ -1279,10 +1273,10 @@ class ClassifierParameters(VideoFilenameAddable): 'Class for the parameters of object classifiers' def loadConfigFile(self, filename): - from ConfigParser import ConfigParser + from configparser import ConfigParser config = ConfigParser() - config.readfp(FakeSecHead(openCheck(filename))) + config.read_file(addSectionHeader(openCheck(filename))) self.sectionHeader = config.sections()[0] self.pedBikeCarSVMFilename = config.get(self.sectionHeader, 'pbv-svm-filename') @@ -1346,10 +1340,10 @@ Note: framerate is already taken into account''' def loadConfigFile(self, filename): - from ConfigParser import ConfigParser + from configparser import ConfigParser - config = ConfigParser() - config.readfp(FakeSecHead(openCheck(filename))) + config = ConfigParser(strict=False) + config.read_file(addSectionHeader(openCheck(filename))) self.sectionHeader = config.sections()[0] # Tracking/display parameters @@ -1441,7 +1435,7 @@ # deprecated class SceneParameters(object): def __init__(self, config, sectionName): - from ConfigParser import NoOptionError + from configparser import NoOptionError from ast import literal_eval try: self.sitename = config.get(sectionName, 'sitename') @@ -1460,7 +1454,7 @@ @staticmethod def loadConfigFile(filename): - from ConfigParser import ConfigParser + from configparser import ConfigParser config = ConfigParser() config.readfp(openCheck(filename)) configDict = dict()
--- a/python/sumo.py Fri May 25 18:15:18 2018 -0400 +++ b/python/sumo.py Sun May 27 23:22:48 2018 -0400 @@ -16,7 +16,7 @@ f.readline() # skip the headers for r in f: tmp = r.strip().split(',') - tazID = tmp[1] + tazID = tmp[1] for edge in tmp[2:]: if len(edge) > 0: if tazID in tazs: @@ -29,7 +29,7 @@ def edge2Taz(tazs): '''Returns the associative array of the TAZ of each SUMO edge''' edge2Tazs = {} - for taz, edges in tazs.iteritems(): + for taz, edges in tazs.items(): for edge in edges: if edge in edge2Tazs: print('error for edge: {} (taz {}/{})'.format(edge, edge2Tazs[edge], taz)) @@ -38,11 +38,11 @@ def saveTazEdges(outFilename, tazs): with open(outFilename,'w') as out: - out.write('<tazs>\n') - for tazID in tazs: - out.write('<taz id="{}" edges="'.format(tazID)+' '.join(tazs[tazID])+'"/>\n') - out.write('</tazs>\n') - + out.write('<tazs>\n') + for tazID in tazs: + out.write('<taz id="{}" edges="'.format(tazID)+' '.join(tazs[tazID])+'"/>\n') + out.write('</tazs>\n') + # TODO add utils from process-cyber.py? # if __name__ == "__main__":
--- a/python/tests/indicators.txt Fri May 25 18:15:18 2018 -0400 +++ b/python/tests/indicators.txt Sun May 27 23:22:48 2018 -0400 @@ -20,7 +20,15 @@ 0 >>> t1 = Trajectory([[0.5,1.5,2.5],[0.5,3.5,6.5]]) ->>> indicatorMap([1,2,3], t1, 1) -{(1.0, 3.0): 2.0, (2.0, 6.0): 3.0, (0.0, 0.0): 1.0} ->>> indicatorMap([1,2,3], t1, 4) -{(0.0, 1.0): 3.0, (0.0, 0.0): 1.5} +>>> m = indicatorMap([1,2,3], t1, 1) +>>> m[(1.0, 3.0)] +2.0 +>>> m[(2.0, 6.0)] +3.0 +>>> m[(0.0, 0.0)] +1.0 +>>> m = indicatorMap([1,2,3], t1, 4) +>>> m[(0.0, 1.0)] +3.0 +>>> m[(0.0, 0.0)] +1.5
--- a/python/tests/moving.txt Fri May 25 18:15:18 2018 -0400 +++ b/python/tests/moving.txt Sun May 27 23:22:48 2018 -0400 @@ -219,11 +219,11 @@ >>> computeClearMOT([gt1], [o1], 0.05, 0, 10) (None, -1.0, 11, 0, 11, 11, None, None) ->>> o1 = MovingObject(1, TimeInterval(0,3), positions = Trajectory([range(4), [0.1, 0.1, 1.1, 1.1]])) ->>> o2 = MovingObject(2, TimeInterval(0,3), positions = Trajectory([range(4), [0.9, 0.9, -0.1, -0.1]])) ->>> gt1 = BBMovingObject(1, TimeInterval(0,3), MovingObject(positions = Trajectory([range(4), [0.]*4])), MovingObject(positions = Trajectory([range(4), [0.]*4]))) +>>> o1 = MovingObject(1, TimeInterval(0,3), positions = Trajectory([list(range(4)), [0.1, 0.1, 1.1, 1.1]])) +>>> o2 = MovingObject(2, TimeInterval(0,3), positions = Trajectory([list(range(4)), [0.9, 0.9, -0.1, -0.1]])) +>>> gt1 = BBMovingObject(1, TimeInterval(0,3), MovingObject(positions = Trajectory([list(range(4)), [0.]*4])), MovingObject(positions = Trajectory([list(range(4)), [0.]*4]))) >>> gt1.computeCentroidTrajectory() ->>> gt2 = BBMovingObject(2, TimeInterval(0,3), MovingObject(positions = Trajectory([range(4), [1.]*4])), MovingObject(positions = Trajectory([range(4), [1.]*4]))) +>>> gt2 = BBMovingObject(2, TimeInterval(0,3), MovingObject(positions = Trajectory([list(range(4)), [1.]*4])), MovingObject(positions = Trajectory([list(range(4)), [1.]*4]))) >>> gt2.computeCentroidTrajectory() >>> computeClearMOT([gt1, gt2], [o1, o2], 0.2, 0, 3) # doctest:+ELLIPSIS (0.1..., 0.75, 0, 2, 0, 8, None, None)
--- a/python/tests/prediction.txt Fri May 25 18:15:18 2018 -0400 +++ b/python/tests/prediction.txt Sun May 27 23:22:48 2018 -0400 @@ -51,7 +51,7 @@ >>> et = PredictedTrajectoryPrototype(proto.getPositionAt(10)+moving.Point(0.5, 0.5), proto.getVelocityAt(10)*0.9, proto, True) >>> absolute(et.initialSpeed - proto.getVelocityAt(10).norm2()*0.9) < 1e-5 True ->>> for t in xrange(int(proto.length())): x=et.predictPosition(t) +>>> for t in range(int(proto.length())): x=et.predictPosition(t) >>> traj = et.getPredictedTrajectory() >>> traj.computeCumulativeDistances() >>> absolute(array(traj.distances).mean() - et.initialSpeed < 1e-3) @@ -62,7 +62,7 @@ True >>> proto = moving.MovingObject.generate(1, moving.Point(-5.,0.), moving.Point(1.,0.), moving.TimeInterval(0,10)) >>> et = PredictedTrajectoryPrototype(proto.getPositionAt(0)+moving.Point(0., 1.), proto.getVelocityAt(0)*0.5, proto, False) ->>> for t in xrange(int(proto.length()/0.5)): x=et.predictPosition(t) +>>> for t in range(int(proto.length()/0.5)): x=et.predictPosition(t) >>> et.predictPosition(10) # doctest:+ELLIPSIS (0.0...,1.0...) >>> et.predictPosition(12) # doctest:+ELLIPSIS
--- a/python/tests/storage.txt Fri May 25 18:15:18 2018 -0400 +++ b/python/tests/storage.txt Sun May 27 23:22:48 2018 -0400 @@ -1,5 +1,5 @@ >>> from storage import * ->>> from StringIO import StringIO +>>> from io import StringIO >>> from moving import MovingObject, Point, TimeInterval, Trajectory, prepareSplines >>> f = openCheck('non_existant_file.txt')
--- a/python/ubc_utils.py Fri May 25 18:15:18 2018 -0400 +++ b/python/ubc_utils.py Sun May 27 23:22:48 2018 -0400 @@ -160,7 +160,7 @@ objects.append(obj) objNum+=1 else: - print("Error two lines of data for feature %d"%(f.num)) + print("Error two lines of data for feature {}".format(f.num)) lines = storage.getLines(file)
--- a/scripts/classify-objects.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/classify-objects.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import cvutils, moving, ml, storage
--- a/scripts/clean-ground-truth.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/clean-ground-truth.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import argparse import pandas as pd import sqlite3
--- a/scripts/compute-clearmot.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/compute-clearmot.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse from numpy import loadtxt @@ -71,7 +71,7 @@ def shiftMatches(matches, offset): shifted = {} for k in matches: - shifted[k] = {t+offset:v for t, v in matches[k].iteritems()} + shifted[k] = {t+offset:v for t, v in matches[k].items()} return shifted if args.display:
--- a/scripts/compute-homography.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/compute-homography.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse
--- a/scripts/create-bounding-boxes.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/create-bounding-boxes.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import argparse
--- a/scripts/create-metadata.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/create-metadata.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import argparse from datetime import datetime @@ -7,7 +7,6 @@ timeConverter = utils.TimeConverter() parser = argparse.ArgumentParser(description='The program add camera views (metadata.CameraView) for a site or video sequences (metadata.VideoSequence) for a site and a view.') -#parser.add_argument('-d', dest = 'siteDirectory', help = 'name of the directory for the site')#, required = True parser.add_argument('-i', dest = 'databaseFilename', help = 'name of the metadata filename', required = True) parser.add_argument('-d', dest = 'dirname', help = 'directory name containing sites or video sequences for a given view') #parser.add_argument('-s', dest = 'siteId', help = 'site id (if provided, the program adds video sequences for the camera view)')
--- a/scripts/delete-tables.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/delete-tables.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse
--- a/scripts/display-synced-trajectories.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/display-synced-trajectories.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse, os.path from datetime import datetime, timedelta @@ -57,7 +57,7 @@ sys.exit() if windowNames is None: - windowNames = ['frame{}'.format(i) for i in xrange(len(filenames))] + windowNames = ['frame{}'.format(i) for i in range(len(filenames))] #wait = 5 #if rescale == 1.: for windowName in windowNames: @@ -72,13 +72,13 @@ key = -1 ret = True nFramesShown = 0 - for i in xrange(len(captures)): + for i in range(len(captures)): if firstFrameNums[i] > 0: captures[i].set(cv2.cv.CV_CAP_PROP_POS_FRAMES, firstFrameNums[i]) while ret and not cvutils.quitKey(key): rets = [] images = [] - for i in xrange(len(captures)): + for i in range(len(captures)): if firstFrameNums[i]+nFramesShown>=0: ret, img = captures[i].read() if ret and args.undistort: @@ -91,7 +91,7 @@ if np.array(rets).any(): #if printFrames: print('frame shown {0}'.format(nFramesShown)) - for i in xrange(len(filenames)): + for i in range(len(filenames)): if rets[i]:#firstFrameNums[i]+nFramesShown>=0: for obj in objects: if obj.existsAtInstant(mergedFirstFrameNum+nFramesShown): @@ -111,7 +111,7 @@ # cv2.imwrite('image-{}.png'.format(frameNum), img) nFramesShown += args.step if args.step > 1: - for i in xrange(len(captures)): + for i in range(len(captures)): if firstFrameNums[i]+nFramesShown >= 0: captures[i].set(cv2.cv.CV_CAP_PROP_POS_FRAMES, firstFrameNums[i]+nFramesShown) cv2.destroyAllWindows()
--- a/scripts/display-trajectories.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/display-trajectories.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse
--- a/scripts/extract-appearance-images.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/extract-appearance-images.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import numpy as np, cv2 import argparse, os
--- a/scripts/extract-camera-parameters.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/extract-camera-parameters.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import argparse
--- a/scripts/info-video.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/info-video.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse import cvutils
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/scripts/init-tracking.py Sun May 27 23:22:48 2018 -0400 @@ -0,0 +1,56 @@ +#! /usr/bin/env python3 + +import sys, argparse, os.path, storage, utils +from shutil import copy +from cvutils import getImagesFromVideo +from matplotlib.pyplot import imsave + +# could try to guess the video +# check if there is already a tracking.cfg file + +parser = argparse.ArgumentParser(description='The program initilizes the files for tracking: copy tracking.cfg, sets up with the video filename, generates a frame image (frame.png) and prints the next commands') + +parser.add_argument('-i', dest = 'videoFilename', help = 'filename of the video sequence', required = True) + +args = parser.parse_args() + +# assumes tracking.cfg is in the parent directory to the directory of the traffic intelligence python modules +matchingPaths = [s for s in sys.path if 'traffic-intelligence' in s] +#if len(matchingPaths) > 1: +# print('Too many matching paths for Traffic Intelligence modules: {}'.format(matchingPaths)) +if len(matchingPaths) == 0: + print('No environment path to Traffic Intelligence modules.\nExiting') + sys.exit() +else: + directoryName = matchingPaths[0] + if directoryName.endswith('/'): + directoryName = directoryName[:-1] + if os.path.exists(directoryName+'/../tracking.cfg') and not os.path.exists('./tracking.cfg'): + f = storage.openCheck(directoryName+'/../tracking.cfg') + out = storage.openCheck('./tracking.cfg', 'w') + for l in f: + if 'video-filename' in l: + tmp = l.split('=') + out.write(tmp[0]+'= '+args.videoFilename+'\n') + elif 'database-filename' in l: + tmp = l.split('=') + out.write(tmp[0]+'= '+utils.removeExtension(args.videoFilename)+'.sqlite\n') + else: + out.write(l) + f.close() + out.close() + print('Configuration file tracking.cfg successfully copied to the current directory with video and database filename adapted') + if os.path.exists(directoryName+'/../classifier.cfg') and not os.path.exists('./classifier.cfg'): + copy(directoryName+'/../classifier.cfg', 'classifier.cfg') + print('Configuration file classifier.cfg successfully copied to the current directory') + +# extract image from video +image = getImagesFromVideo(args.videoFilename, saveImage = True, outputPrefix = 'frame') +print('first video frame successfully copied to the current directory') + +# next commands +print('--------------------------------------\nHere are a sample of the next command to compute the homography,\ntrack features, group them in objects and display object trajectories\n--------------------------------------') +print('compute_homography -i [frame.png] -w [world_image] -n [npoints] -u [unit_per_pixel]') +print('feature-based-tracking tracking.cfg --tf') +print('feature-based-tracking tracking.cfg --gf') +print('display-trajectories --cfg tracking.cfg -t object')
--- a/scripts/init_tracking.py Fri May 25 18:15:18 2018 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -#! /usr/bin/env python - -import sys, argparse, os.path, storage, utils -from shutil import copy -from cvutils import getImagesFromVideo -from matplotlib.pyplot import imsave - -# could try to guess the video -# check if there is already a tracking.cfg file - -parser = argparse.ArgumentParser(description='The program initilizes the files for tracking: copy tracking.cfg, sets up with the video filename, generates a frame image (frame.png) and prints the next commands') - -parser.add_argument('-i', dest = 'videoFilename', help = 'filename of the video sequence', required = True) - -args = parser.parse_args() - -# assumes tracking.cfg is in the parent directory to the directory of the traffic intelligence python modules -matchingPaths = [s for s in sys.path if 'traffic-intelligence' in s] -#if len(matchingPaths) > 1: -# print('Too many matching paths for Traffic Intelligence modules: {}'.format(matchingPaths)) -if len(matchingPaths) == 0: - print('No environment path to Traffic Intelligence modules.\nExiting') - sys.exit() -else: - directoryName = matchingPaths[0] - if directoryName.endswith('/'): - directoryName = directoryName[:-1] - if os.path.exists(directoryName+'/../tracking.cfg') and not os.path.exists('./tracking.cfg'): - f = storage.openCheck(directoryName+'/../tracking.cfg') - out = storage.openCheck('./tracking.cfg', 'w') - for l in f: - if 'video-filename' in l: - tmp = l.split('=') - out.write(tmp[0]+'= '+args.videoFilename+'\n') - elif 'database-filename' in l: - tmp = l.split('=') - out.write(tmp[0]+'= '+utils.removeExtension(args.videoFilename)+'.sqlite\n') - else: - out.write(l) - f.close() - out.close() - print('Configuration file tracking.cfg successfully copied to the current directory with video and database filename adapted') - if os.path.exists(directoryName+'/../classifier.cfg') and not os.path.exists('./classifier.cfg'): - copy(directoryName+'/../classifier.cfg', 'classifier.cfg') - print('Configuration file classifier.cfg successfully copied to the current directory') - -# extract image from video -image = getImagesFromVideo(args.videoFilename, saveImage = True, outputPrefix = 'frame') -print('first video frame successfully copied to the current directory') - -# next commands -print('--------------------------------------\nHere are a sample of the next command to compute the homography,\ntrack features, group them in objects and display object trajectories\n--------------------------------------') -print('compute_homography -i [frame.png] -w [world_image] -n [npoints] -u [unit_per_pixel]') -print('feature-based-tracking tracking.cfg --tf') -print('feature-based-tracking tracking.cfg --gf') -print('display-trajectories --cfg tracking.cfg -t object')
--- a/scripts/learn-motion-patterns.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/learn-motion-patterns.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse @@ -61,7 +61,7 @@ initialPrototypes = storage.loadPrototypesFromSqlite(args.inputPrototypeDatabaseFilename, True) trajectories = [p.getMovingObject().getPositions().asArray().T for p in initialPrototypes]+trajectories if len(initialPrototypes) > 0: - initialPrototypeIndices = range(len(initialPrototypes)) + initialPrototypeIndices = list(range(len(initialPrototypes))) else: initialPrototypeIndices = None else:
--- a/scripts/learn-poi.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/learn-poi.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import argparse @@ -78,8 +78,8 @@ if args.assign: storage.savePOIAssignments(args.databaseFilename, objects) if args.displayPaths: - for i in xrange(args.nOriginClusters): - for j in xrange(args.nDestinationClusters): + for i in range(args.nOriginClusters): + for j in range(args.nDestinationClusters): odObjects = [o for o in objects if o.od[0] == i and o.od[1] == j] if len(odObjects) > 0: fig = plt.figure()
--- a/scripts/manual-video-analysis.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/manual-video-analysis.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse, cv2, numpy as np @@ -22,7 +22,7 @@ Press x to go back 10 frames Press spacebar to go forward one frame Press l to skip to frame number -Press Enter to finish inputting user characteristics (if any in pop up window) +Press s to finish inputting user characteristics (if any in pop up window) Press q to quit and end program''') # configuration of keys and user types (see moving) userTypeNames = ['unknown', @@ -82,8 +82,8 @@ # start of program cap = cv2.VideoCapture(args.videoFilename) -cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, args.firstFrameNum) -fps = cap.get(cv2.cv.CV_CAP_PROP_FPS) +cap.set(cv2.CAP_PROP_POS_FRAMES, args.firstFrameNum) +fps = cap.get(cv2.CAP_PROP_FPS) print('Video at {} frames/s'.format(fps)) cv2.namedWindow('Video', cv2.WINDOW_NORMAL) @@ -102,7 +102,7 @@ while(cap.isOpened()): ret, frame = cap.read() - frameNum = int(cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)) + frameNum = int(cap.get(cv2.CAP_PROP_POS_FRAMES)) cv2.putText(frame, str(frameNum), (1,20), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0,0)) cv2.imshow('Video',frame) @@ -123,7 +123,7 @@ attributeNum = 0 while key2 != ord('s'): attrImg = 255*np.ones((20*args.nAttributes, 20, 3)) - for i in xrange(args.nAttributes): + for i in range(args.nAttributes): if i == (attributeNum%args.nAttributes): cv2.putText(attrImg, str(config.attributes[i]), (1,20*(i+1)), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)) else: @@ -153,8 +153,8 @@ elif key == ord('c'): cap.set(1,frameNum-100) elif key == ord('l'): - frameNum = int(raw_input("Please enter the frame number you would like to skip to\n")) - cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,frameNum) + frameNum = int(input("Please enter the frame number you would like to skip to\n")) + cap.set(cv2.CAP_PROP_POS_FRAMES,frameNum) out.close() cap.release()
--- a/scripts/merge-features.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/merge-features.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse, os.path, sqlite3 import cvutils, utils, moving, storage @@ -40,7 +40,7 @@ timeIntervals[cv] = moving.TimeInterval.unionIntervals([v.getTimeInterval() for v in videoSequences[cv]]) # intersection of the time interval (union) for each camera view -commonTimeInterval = timeIntervals.values()[0] +commonTimeInterval = list(timeIntervals.values())[0] for inter in timeIntervals.values()[1:]: commonTimeInterval = moving.TimeInterval.intersection(commonTimeInterval, inter) commonTimeInterval = moving.TimeInterval.intersection(commonTimeInterval, processInterval) @@ -71,8 +71,8 @@ newTrajectoryId = -1 # first frame num is commonTimeInterval -for cv, vs in videoSequences.iteritems(): - print cv.idx, cv.description +for cv, vs in videoSequences.items(): + print(cv.idx, cv.description) for videoSequence in vs: try: vsConnection = sqlite3.connect(dirname+os.path.sep+videoSequence.getDatabaseFilename()) @@ -93,7 +93,7 @@ for row in vsCursor: outCursor.execute(storage.insertTrajectoryQuery('velocities'), (featureIdCorrespondences[row[0]], row[1]-firstFrameNum, row[2], row[3])) # saving the id correspondences - for oldId, newId in featureIdCorrespondences.iteritems(): + for oldId, newId in featureIdCorrespondences.items(): outCursor.execute("INSERT INTO feature_correspondences (trajectory_id, source_dbname, db_trajectory_id) VALUES ({},\"{}\",{})".format(newId, videoSequence.name, oldId)) outConnection.commit() except sqlite3.OperationalError as error:
--- a/scripts/performance-db.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/performance-db.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, shutil, os, sqlite3, timeit#, argparse @@ -15,14 +15,14 @@ connection = sqlite3.connect(dbFilename) nFeatures=storage.getNumberRowsTable(connection, "positions", "trajectory_id") -print dbFilename, nFeatures +print(dbFilename, nFeatures) #### # test query tmp trajectory instant table #### def selectTrajectoryIdInstant(connection, lastInstant): cursor = connection.cursor() - for i in xrange(lastInstant): + for i in range(lastInstant): cursor.execute("select trajectory_id from trajectory_instants where last_instant = {}".format(lastInstant)) cursor.fetchall() @@ -44,7 +44,7 @@ #### def selectTrajectories(connection, nFeatures): cursor = connection.cursor() - for i in xrange(nFeatures): + for i in range(nFeatures): cursor.execute("select * from positions where trajectory_id = {} order by frame_number".format(i)) cursor.fetchall() @@ -66,7 +66,7 @@ #### print("with index on trajectory_id") storage.createIndex(connection, "positions", "trajectory_id")#sqlite3 $dbFilename "create index trajectory_id_index on positions(trajectory_id)" - print timeit.timeit("selectTrajectories(connection, nFeatures)", setup="from __main__ import selectTrajectories, connection, nFeatures", number = 100) + print(timeit.timeit("selectTrajectories(connection, nFeatures)", setup="from __main__ import selectTrajectories, connection, nFeatures", number = 100)) #### Cleanup os.remove(dbFilename)
--- a/scripts/performance-lcss.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/performance-lcss.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import timeit @@ -6,7 +6,7 @@ number = 10 print('Default Python implementation with lambda') -print timeit.timeit('lcss.compute(random_sample(({},2)), random_sample(({}, 2)))'.format(vectorLength, vectorLength*2), setup = 'from utils import LCSS; from numpy.random import random_sample; lcss = LCSS(similarityFunc = lambda x,y: (abs(x[0]-y[0]) <= 0.1) and (abs(x[1]-y[1]) <= 0.1));', number = number) +print(timeit.timeit('lcss.compute(random_sample(({},2)), random_sample(({}, 2)))'.format(vectorLength, vectorLength*2), setup = 'from utils import LCSS; from numpy.random import random_sample; lcss = LCSS(similarityFunc = lambda x,y: (abs(x[0]-y[0]) <= 0.1) and (abs(x[1]-y[1]) <= 0.1));', number = number)) print('Using scipy distance.cdist') -print timeit.timeit('lcss.compute(random_sample(({},2)), random_sample(({}, 2)))'.format(vectorLength, vectorLength*2), setup = 'from utils import LCSS; from numpy.random import random_sample; lcss = LCSS(metric = "cityblock", epsilon = 0.1);', number = number) +print(timeit.timeit('lcss.compute(random_sample(({},2)), random_sample(({}, 2)))'.format(vectorLength, vectorLength*2), setup = 'from utils import LCSS; from numpy.random import random_sample; lcss = LCSS(metric = "cityblock", epsilon = 0.1);', number = number))
--- a/scripts/play-synced-videos.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/play-synced-videos.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse, os.path import cvutils, utils
--- a/scripts/play-video.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/play-video.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse import cvutils
--- a/scripts/polytracktopdtv.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/polytracktopdtv.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 from pdtv import TsaiCamera, ZipVideo, SyncedVideos, TrackSet, Track, State import sys, os, datetime, argparse @@ -68,7 +68,6 @@ frameList = cvutils.getImagesFromVideo(videoFile, firstFrameNum = currentIdx, nFrames = inc) while len(frameList) == inc and inc > 0: - for f in frameList: cv2.imwrite(os.path.join(framePath,time.strftime("%Y%m%d-%H%M%S.%f")[:-3]+'.jpg'), f) time += datetime.timedelta(microseconds=deltaTimestamp*1000) @@ -80,7 +79,7 @@ inc = delta if inc: frameList = cvutils.getImagesFromVideo(videoFile, firstFrameNum = currentIdx, nFrames = inc) - print('Extracting frame ' + str(currentIdx)) + print('Extracting frame {}'.format(currentIdx)) return len(frameList) > 0 @@ -115,7 +114,7 @@ if videoFile is not None: fps = cvutils.getFPS(videoFile) - print('Video should run at ' + str(fps) + ' fps') + print('Video should run at {} fps'.format(fps)) deltaTimestamp = 1000.0/float(fps); if videoFolderExist == False: if os.path.exists(videoFolderPath):
--- a/scripts/process.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/process.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse from pathlib2 import Path @@ -86,7 +86,7 @@ for speeds, name in zip([medianSpeeds, speeds85], ['Median', '85th Centile']): plt.ioff() plt.figure() - plt.boxplot(speeds.values(), labels = [session.query(Site).get(siteId).name for siteId in speeds]) + plt.boxplot(list(speeds.values()), labels = [session.query(Site).get(siteId).name for siteId in speeds]) plt.ylabel(name+' Speeds (km/h)') plt.savefig(name.lower()+'-speeds.png', dpi=150) plt.close()
--- a/scripts/replay-event-annotation.py Fri May 25 18:15:18 2018 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,26 +0,0 @@ -#! /usr/bin/env python - -import sys, argparse, datetime - -import storage, cvutils, utils - -import matplotlib.pylab as pylab -import matplotlib.pyplot as plt -import numpy as np - - -annotations = pylab.csv2rec(sys.argv[1]) - -frameRate = 30 -dirname = "/home/nicolas/Research/Data/montreal/infractions-pietons/" -videoDirnames = {'amherst': '2011-06-22-sherbrooke-amherst/', - 'iberville': '2011-06-28-sherbrooke-iberville/'} - -# for amherst, subtract 40 seconds: add a delta - -for annotation in annotations: - video = annotation['video_name'].lower() - print('{} {}'.format(annotation['conflict_start_time'], annotation['conflict_end_time'])) - print(annotation['road_user_1']+' '+annotation['road_user_2']+' '+annotation['conflict_quality']) - print(annotation['comments']) - cvutils.playVideo(dirname+videoDirnames[video]+video+'-{}.avi'.format(annotation['video_start_time']), utils.timeToFrames(annotation['conflict_start_time']+datetime.timedelta(seconds=-40), frameRate), frameRate, True, False, annotation['road_user_1']+' '+annotation['road_user_2']+' '+annotation['conflict_quality'])
--- a/scripts/rescale-homography.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/rescale-homography.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys
--- a/scripts/safety-analysis.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/safety-analysis.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import storage, prediction, events, moving
--- a/scripts/test-compute-object-position-from-features.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/test-compute-object-position-from-features.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import sys @@ -70,7 +70,7 @@ # TODO version median: conversion to large matrix will not work, have to do it frame by frame def kalmanFilter(positions, velocities, processNoiseCov, measurementNoiseCov): - kalman=cv.CreateKalman(6, 4) + kalman=cv2.CreateKalman(6, 4) kalman.transition_matrix[0,2]=1 kalman.transition_matrix[0,4]=1./2 kalman.transition_matrix[1,3]=1 @@ -97,15 +97,15 @@ filteredPositions = moving.Trajectory() filteredVelocities = moving.Trajectory() measurement = cv.CreateMat(4,1,cv.CV_32FC1) - for i in xrange(positions.length()): - cv.KalmanPredict(kalman) # no control + for i in range(positions.length()): + kalman.predict() # no control p = positions[i] v = velocities[i] measurement[0,0] = p.x measurement[1,0] = p.y measurement[2,0] = v.x measurement[3,0] = v.y - cv.KalmanCorrect(kalman, measurement) + kalman.correct(measurement) filteredPositions.addPositionXY(kalman.state_post[0,0], kalman.state_post[1,0]) filteredVelocities.addPositionXY(kalman.state_post[2,0], kalman.state_post[3,0])
--- a/scripts/train-object-classification.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/train-object-classification.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import numpy as np import argparse @@ -35,7 +35,7 @@ trainingSamplesPV = {} trainingLabelsPV = {} -for k, v in imageDirectories.iteritems(): +for k, v in imageDirectories.items(): print('Loading {} samples'.format(k)) trainingSamples, trainingLabels = cvutils.createHOGTrainingSet(v, moving.userType2Num[k], classifierParams.hogRescaleSize, classifierParams.hogNOrientations, classifierParams.hogNPixelsPerCell, classifierParams.hogBlockNorm, classifierParams.hogNCellsPerBlock) trainingSamplesPBV[k], trainingLabelsPBV[k] = trainingSamples, trainingLabels @@ -47,30 +47,30 @@ trainingSamplesPV[k], trainingLabelsPV[k] = trainingSamples, trainingLabels # Training the Support Vector Machine -print "Training Pedestrian-Cyclist-Vehicle Model" +print("Training Pedestrian-Cyclist-Vehicle Model") model = ml.SVM(args.svmType, args.kernelType, args.degree, args.gamma, args.coef0, args.cvalue, args.nu, args.svmP) -classifications = model.train(np.concatenate(trainingSamplesPBV.values()), ROW_SAMPLE, np.concatenate(trainingLabelsPBV.values()), True) +classifications = model.train(np.concatenate(list(trainingSamplesPBV.values())), ROW_SAMPLE, np.concatenate(list(trainingLabelsPBV.values())), True) if args.computeConfusionMatrix: print(classifications) model.save(args.directoryName + "/modelPBV.xml") -print "Training Cyclist-Vehicle Model" +print("Training Cyclist-Vehicle Model") model = ml.SVM(args.svmType, args.kernelType, args.degree, args.gamma, args.coef0, args.cvalue, args.nu, args.svmP) -classifications = model.train(np.concatenate(trainingSamplesBV.values()), ROW_SAMPLE, np.concatenate(trainingLabelsBV.values()), True) +classifications = model.train(np.concatenate(list(trainingSamplesBV.values())), ROW_SAMPLE, np.concatenate(list(trainingLabelsBV.values())), True) if args.computeConfusionMatrix: print(classifications) model.save(args.directoryName + "/modelBV.xml") -print "Training Pedestrian-Cyclist Model" +print("Training Pedestrian-Cyclist Model") model = ml.SVM(args.svmType, args.kernelType, args.degree, args.gamma, args.coef0, args.cvalue, args.nu, args.svmP) -classifications = model.train(np.concatenate(trainingSamplesPB.values()), ROW_SAMPLE, np.concatenate(trainingLabelsPB.values()), True) +classifications = model.train(np.concatenate(list(trainingSamplesPB.values())), ROW_SAMPLE, np.concatenate(list(trainingLabelsPB.values())), True) if args.computeConfusionMatrix: print(classifications) model.save(args.directoryName + "/modelPB.xml") -print "Training Pedestrian-Vehicle Model" +print("Training Pedestrian-Vehicle Model") model = ml.SVM(args.svmType, args.kernelType, args.degree, args.gamma, args.coef0, args.cvalue, args.nu, args.svmP) -classifications = model.train(np.concatenate(trainingSamplesPV.values()), ROW_SAMPLE, np.concatenate(trainingLabelsPV.values()), True) +classifications = model.train(np.concatenate(list(trainingSamplesPV.values())), ROW_SAMPLE, np.concatenate(list(trainingLabelsPV.values())), True) if args.computeConfusionMatrix: print(classifications) model.save(args.directoryName + "/modelPV.xml")
--- a/scripts/undistort-video.py Fri May 25 18:15:18 2018 -0400 +++ b/scripts/undistort-video.py Sun May 27 23:22:48 2018 -0400 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys, argparse @@ -50,8 +50,7 @@ frameNum = args.firstFrameNum capture.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, args.firstFrameNum) if args.lastFrameNum is None: - from sys import maxint - lastFrameNum = maxint + lastFrameNum = float('inf') else: lastFrameNum = args.lastFrameNum nZerosFilename = int(ceil(log10(lastFrameNum)))