# HG changeset patch
# User Wendlasida
# Date 1527864469 14400
# Node ID 01db14e947e4326f8aed3c3c201017ae963ddbdf
# Parent 4f0312bee39319ec4692081465a4bc3f41579551# Parent cc7c6b821ae6f88bb30ab1388c42ca40bb8c6461
resolved
diff -r 4f0312bee393 -r 01db14e947e4 .hgtags
--- a/.hgtags Fri Jun 01 10:43:23 2018 -0400
+++ b/.hgtags Fri Jun 01 10:47:49 2018 -0400
@@ -1,2 +1,5 @@
ea2a8e8e4e77dbf0374e3ddc935d3a28672e8456 v0.1
6022350f81736f3881726076987300fb3381cd25 OpenCV 3.1
+6022350f81736f3881726076987300fb3381cd25 OpenCV 3.1
+0000000000000000000000000000000000000000 OpenCV 3.1
+8bcac18c2b554e96c3bd7a5164e0def31d9b9920 OpenCV3 and Python3
diff -r 4f0312bee393 -r 01db14e947e4 python/cvutils.py
--- a/python/cvutils.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/cvutils.py Fri Jun 01 10:47:49 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:
diff -r 4f0312bee393 -r 01db14e947e4 python/events.py
--- a/python/events.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/events.py Fri Jun 01 10:47:49 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]))
diff -r 4f0312bee393 -r 01db14e947e4 python/indicators.py
--- a/python/indicators.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/indicators.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/ml.py
--- a/python/ml.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/ml.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/moving.py
--- a/python/moving.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/moving.py Fri Jun 01 10:47:49 2018 -0400
@@ -122,7 +122,7 @@
self.iterInstantNum = -1
return self
- def next(self):
+ def __next__(self):
if self.iterInstantNum >= self.length()-1:
raise StopIteration
else:
@@ -172,6 +172,18 @@
def getLastInstant(self):
return self.timeInterval.last
+ def setFirstInstant(self, t):
+ if t <= self.timeInterval.last:
+ self.timeInterval.first = t
+ else:
+ print('new first instant is after last, not changing')
+
+ def setLastInstant(self, t):
+ if t >= self.timeInterval.first:
+ self.timeInterval.last = t
+ else:
+ print('new last instant is before first, not changing')
+
def getTimeInterval(self):
return self.timeInterval
@@ -379,7 +391,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
@@ -417,7 +429,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
@@ -666,7 +678,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])
@@ -705,7 +717,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__()
@@ -714,7 +726,7 @@
self.iterInstantNum = 0
return self
- def next(self):
+ def __next__(self):
if self.iterInstantNum >= self.length():
raise StopIteration
else:
@@ -819,7 +831,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])
@@ -856,7 +868,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]
@@ -923,7 +935,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)
@@ -945,7 +957,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)
@@ -1078,7 +1090,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
@@ -1092,7 +1104,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)):
@@ -1261,10 +1273,10 @@
@staticmethod
def concatenate(obj1, obj2, num = None):
'''Concatenates two objects supposed to overlap temporally '''
- if num is None:
- newNum = obj1.getNum()
- else:
- newNum = num
+ if num is None:
+ newNum = obj1.getNum()
+ else:
+ newNum = num
commonTimeInterval = obj1.commonTimeInterval(obj2)
if commonTimeInterval.empty():
print('The two objects\' time intervals do not overlap: obj1 {} and obj2 {}'.format(obj1.getTimeInterval(), obj2.getTimeInterval()))
@@ -1289,8 +1301,7 @@
newObject = MovingObject(newNum, emptyInterval, positions, velocities, userType = obj1.getUserType())
newObject.features = [MovingObject(newNum, emptyInterval, positions, velocities, userType = obj1.getUserType())] #In case there is features to add when we recursively call concatenate
return MovingObject.concatenate(MovingObject.concatenate(obj1, newObject),obj2)
-
-
+
else:
newTimeInterval = TimeInterval.union(obj1.getTimeInterval(), obj2.getTimeInterval())
# positions
@@ -1424,7 +1435,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
@@ -1533,7 +1544,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
@@ -1668,7 +1679,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
@@ -1684,7 +1695,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]]])
@@ -1708,8 +1719,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)
@@ -1962,7 +1973,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 = []
@@ -1979,8 +1990,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]
@@ -1996,9 +2007,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()
@@ -2014,10 +2025,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):
diff -r 4f0312bee393 -r 01db14e947e4 python/objectsmoothing.py
--- a/python/objectsmoothing.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/objectsmoothing.py Fri Jun 01 10:47:49 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)
diff -r 4f0312bee393 -r 01db14e947e4 python/pavement.py
--- a/python/pavement.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/pavement.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/poly-utils.py
--- a/python/poly-utils.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/poly-utils.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/prediction.py
--- a/python/prediction.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/prediction.py Fri Jun 01 10:47:49 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,
diff -r 4f0312bee393 -r 01db14e947e4 python/processing.py
--- a/python/processing.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/processing.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/run-tests.sh
--- a/python/run-tests.sh Fri Jun 01 10:43:23 2018 -0400
+++ b/python/run-tests.sh Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/sensors.py
--- a/python/sensors.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/sensors.py Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/storage.py
--- a/python/storage.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/storage.py Fri Jun 01 10:47:49 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()
diff -r 4f0312bee393 -r 01db14e947e4 python/sumo.py
--- a/python/sumo.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/sumo.py Fri Jun 01 10:47:49 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('\n')
- for tazID in tazs:
- out.write('\n')
- out.write('\n')
-
+ out.write('\n')
+ for tazID in tazs:
+ out.write('\n')
+ out.write('\n')
+
# TODO add utils from process-cyber.py?
# if __name__ == "__main__":
diff -r 4f0312bee393 -r 01db14e947e4 python/tests/indicators.txt
--- a/python/tests/indicators.txt Fri Jun 01 10:43:23 2018 -0400
+++ b/python/tests/indicators.txt Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/tests/moving.txt
--- a/python/tests/moving.txt Fri Jun 01 10:43:23 2018 -0400
+++ b/python/tests/moving.txt Fri Jun 01 10:47:49 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)
diff -r 4f0312bee393 -r 01db14e947e4 python/tests/prediction.txt
--- a/python/tests/prediction.txt Fri Jun 01 10:43:23 2018 -0400
+++ b/python/tests/prediction.txt Fri Jun 01 10:47:49 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
diff -r 4f0312bee393 -r 01db14e947e4 python/tests/storage.txt
--- a/python/tests/storage.txt Fri Jun 01 10:43:23 2018 -0400
+++ b/python/tests/storage.txt Fri Jun 01 10:47:49 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')
diff -r 4f0312bee393 -r 01db14e947e4 python/tests/utils.txt
--- a/python/tests/utils.txt Fri Jun 01 10:43:23 2018 -0400
+++ b/python/tests/utils.txt Fri Jun 01 10:47:49 2018 -0400
@@ -11,9 +11,9 @@
>>> computeChi2([],[])
0
->>> computeChi2(range(1,10),range(1,10))
+>>> computeChi2(list(range(1,10)),list(range(1,10)))
0.0
->>> computeChi2(range(1,9),range(1,10))
+>>> computeChi2(list(range(1,9)),list(range(1,10)))
0.0
>>> ceilDecimals(1.23, 0)
@@ -53,26 +53,26 @@
'b'
>>> mostCommon(['a','b','c','b', 'c'])
'b'
->>> mostCommon(range(10)+[1])
+>>> mostCommon(list(range(10))+[1])
1
->>> mostCommon([range(2), range(4), range(2)])
+>>> mostCommon([list(range(2)), list(range(4)), list(range(2))])
[0, 1]
->>> res = sortByLength([range(3), range(4), range(1)])
+>>> res = sortByLength([list(range(3)), list(range(4)), list(range(1))])
>>> [len(r) for r in res]
[1, 3, 4]
->>> res = sortByLength([range(3), range(4), range(1), range(5)], reverse = True)
+>>> res = sortByLength([list(range(3)), list(range(4)), list(range(1)), list(range(5))], reverse = True)
>>> [len(r) for r in res]
[5, 4, 3, 1]
>>> lcss = LCSS(similarityFunc = lambda x,y: abs(x-y) <= 0.1)
->>> lcss.compute(range(5), range(5))
+>>> lcss.compute(list(range(5)), list(range(5)))
5
->>> lcss.compute(range(1,5), range(5))
+>>> lcss.compute(list(range(1,5)), list(range(5)))
4
->>> lcss.compute(range(5,10), range(5))
+>>> lcss.compute(list(range(5,10)), list(range(5)))
0
->>> lcss.compute(range(5), range(10))
+>>> lcss.compute(list(range(5)), list(range(10)))
5
>>> lcss.similarityFunc = lambda x,y: x == y
>>> lcss.compute(['a','b','c'], ['a','b','c', 'd'])
@@ -106,27 +106,27 @@
[(0, 0), (2, 1), (3, 2)]
>>> alignedLcss = LCSS(lambda x,y:(abs(x-y) <= 0.1), delta = 2, aligned = True)
->>> alignedLcss.compute(range(5), range(5))
+>>> alignedLcss.compute(list(range(5)), list(range(5)))
5
->>> alignedLcss.compute(range(1,5), range(5))
+>>> alignedLcss.compute(list(range(1,5)), list(range(5)))
4
->>> alignedLcss.compute(range(5,10), range(10))
+>>> alignedLcss.compute(list(range(5,10)), list(range(10)))
5
>>> lcss.delta = 2
->>> lcss.compute(range(5,10), range(10))
+>>> lcss.compute(list(range(5,10)), list(range(10)))
0
>>> alignedLcss.delta = 6
->>> alignedLcss.compute(range(5), range(5))
+>>> alignedLcss.compute(list(range(5)), list(range(5)))
5
->>> alignedLcss.compute(range(5), range(6))
+>>> alignedLcss.compute(list(range(5)), list(range(6)))
5
>>> lcss.delta = 10
->>> alignedLcss.compute(range(1,7), range(6))
+>>> alignedLcss.compute(list(range(1,7)), list(range(6)))
5
>>> lcss = LCSS(lambda x,y: x == y, delta = 2, aligned = True)
->>> lcss.compute(range(20), [2,4,6,7,8,9,11,13], True)
+>>> lcss.compute(list(range(20)), [2,4,6,7,8,9,11,13], True)
8
>>> lcss.subSequenceIndices
[(2, 0), (4, 1), (6, 2), (7, 3), (8, 4), (9, 5), (11, 6), (13, 7)]
@@ -141,3 +141,4 @@
>>> lcss.compute([[i] for i in range(5)], [[i] for i in range(10)])
5
+
diff -r 4f0312bee393 -r 01db14e947e4 python/ubc_utils.py
--- a/python/ubc_utils.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/ubc_utils.py Fri Jun 01 10:47:49 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)
diff -r 4f0312bee393 -r 01db14e947e4 python/utils.py
--- a/python/utils.py Fri Jun 01 10:43:23 2018 -0400
+++ b/python/utils.py Fri Jun 01 10:47:49 2018 -0400
@@ -301,7 +301,7 @@
def sortByLength(instances, reverse = False):
'''Returns a new list with the instances sorted by length (method __len__)
reverse is passed to sorted'''
- return sorted(instances, cmp = compareLengthForSort, reverse = reverse)
+ return sorted(instances, key = len, reverse = reverse)
def ceilDecimals(v, nDecimals):
'''Rounds the number at the nth decimal
@@ -406,7 +406,7 @@
newVariables.append(newVariable)
return newVariables
-def kruskalWallis(data, dependentVariable, independentVariable, plotFigure = False, filenamePrefix = None, figureFileType = 'pdf', saveLatex = False, renameVariables = lambda s: s, kwCaption = u''):
+def kruskalWallis(data, dependentVariable, independentVariable, plotFigure = False, filenamePrefix = None, figureFileType = 'pdf', saveLatex = False, renameVariables = lambda s: s, kwCaption = ''):
'''Studies the influence of (nominal) independent variable over the dependent variable
Makes tests if the conditional distributions are normal
@@ -512,10 +512,10 @@
def saveDokMatrix(filename, m, lowerTriangle = False):
'Saves a dok_matrix using savez'
if lowerTriangle:
- keys = [k for k in m.keys() if k[0] > k[1]]
+ keys = [k for k in m if k[0] > k[1]]
savez(filename, shape = m.shape, keys = keys, values = [m[k[0],k[1]] for k in keys])
else:
- savez(filename, shape = m.shape, keys = m.keys(), values = m.values())
+ savez(filename, shape = m.shape, keys = list(m.keys()), values = list(m.values()))
def loadDokMatrix(filename):
'Loads a dok_matrix saved using the above saveDokMatrix'
@@ -612,17 +612,17 @@
if experiments is None:
experiments = generateExperiments(independentVariables)
nIndependentVariables = len(independentVariables)
- permutation = nppermutation(range(nIndependentVariables)).tolist()
+ permutation = nppermutation(list(range(nIndependentVariables)))
variableMapping = {j: independentVariables[i] for i,j in enumerate(permutation)}
- print('Tested variables '+', '.join([variableMapping[i] for i in xrange(nIndependentVariables)]))
+ print('Tested variables '+', '.join([variableMapping[i] for i in range(nIndependentVariables)]))
bestModel = [False]*nIndependentVariables
currentVarNum = 0
currentR2Adj = 0.
- for currentVarNum in xrange(nIndependentVariables):
+ for currentVarNum in range(nIndependentVariables):
currentModel = [i for i in bestModel]
currentModel[currentVarNum] = True
- rowIdx = sum([0]+[2**i for i in xrange(nIndependentVariables) if currentModel[permutation[i]]])
- #print currentVarNum, sum(currentModel), ', '.join([independentVariables[i] for i in xrange(nIndependentVariables) if currentModel[permutation[i]]])
+ rowIdx = sum([0]+[2**i for i in range(nIndependentVariables) if currentModel[permutation[i]]])
+ #print currentVarNum, sum(currentModel), ', '.join([independentVariables[i] for i in range(nIndependentVariables) if currentModel[permutation[i]]])
if experiments.loc[rowIdx, 'shapiroP'] < 0:
modelStr = modelString(experiments.loc[rowIdx], dependentVariable, independentVariables)
model = modelFunc(modelStr, data = data)
@@ -752,16 +752,16 @@
n2 = len(l2)
self.similarityTable = zeros((n1+1,n2+1), dtype = npint)
if self.similarityFunc is not None:
- for i in xrange(1,n1+1):
- for j in xrange(max(1,i-jshift-self.delta),min(n2,i-jshift+self.delta)+1):
+ for i in range(1,n1+1):
+ for j in range(max(1,i-jshift-self.delta),min(n2,i-jshift+self.delta)+1):
if self.similarityFunc(l1[i-1], l2[j-1]):
self.similarityTable[i,j] = self.similarityTable[i-1,j-1]+1
else:
self.similarityTable[i,j] = max(self.similarityTable[i-1,j], self.similarityTable[i,j-1])
elif self.metric is not None:
similarElements = distance.cdist(l1, l2, self.metric) <= self.epsilon
- for i in xrange(1,n1+1):
- for j in xrange(max(1,i-jshift-self.delta),min(n2,i-jshift+self.delta)+1):
+ for i in range(1,n1+1):
+ for j in range(max(1,i-jshift-self.delta),min(n2,i-jshift+self.delta)+1):
if similarElements[i-1, j-1]:
self.similarityTable[i,j] = self.similarityTable[i-1,j-1]+1
else:
@@ -802,7 +802,7 @@
if self.aligned:
lcssValues = {}
similarityTables = {}
- for i in xrange(-n2-self.delta+1, n1+self.delta): # interval such that [i-shift-delta, i-shift+delta] is never empty, which happens when i-shift+delta < 1 or when i-shift-delta > n2
+ for i in range(-n2-self.delta+1, n1+self.delta): # interval such that [i-shift-delta, i-shift+delta] is never empty, which happens when i-shift+delta < 1 or when i-shift-delta > n2
self.similarities(l1, l2, i)
lcssValues[i] = self.similarityTable.max()
similarityTables[i] = self.similarityTable
@@ -894,13 +894,13 @@
def plotIndicatorMap(indicatorMap, squareSize, masked = True, defaultValue=-1):
from matplotlib.pyplot import pcolor
- coords = array(indicatorMap.keys())
+ coords = array(list(indicatorMap.keys()))
minX = min(coords[:,0])
minY = min(coords[:,1])
X = arange(minX, max(coords[:,0])+1.1)*squareSize
Y = arange(minY, max(coords[:,1])+1.1)*squareSize
C = defaultValue*ones((len(Y), len(X)))
- for k,v in indicatorMap.iteritems():
+ for k,v in indicatorMap.items():
C[k[1]-minY,k[0]-minX] = v
if masked:
pcolor(X, Y, ma.masked_where(C==defaultValue,C))
@@ -926,7 +926,7 @@
for annee in `seq 2016 2017`;do wget --content-disposition "http://climat.meteo.gc.ca/climate_data/bulk_data_f.html?format=csv&stationID=10761&Year=${annee}&timeframe=2&submit=++T%C3%A9l%C3%A9charger+%0D%0Ades+donn%C3%A9es" ;done
for annee in `seq 2016 2017`;do for mois in `seq 1 12`;do wget --content-disposition "http://climat.meteo.gc.ca/climate_data/bulk_data_f.html?format=csv&stationID=10761&Year=${annee}&Month=${mois}&timeframe=1&submit=++T%C3%A9l%C3%A9charger+%0D%0Ades+donn%C3%A9es" ;done;done
'''
- import urllib2
+ import urllib.request
if english:
language = 'e'
else:
@@ -939,18 +939,13 @@
for year in years:
for month in months:
- url = urllib2.urlopen('http://climate.weather.gc.ca/climate_data/bulk_data_{}.html?format=csv&stationID={}&Year={}&Month={}&Day=1&timeframe={}&submit= Download+Data'.format(language, stationID, year, month, timeFrame))
- #http://climat.meteo.gc.ca/climateData/bulkdata_{}.html?format=csv&stationID={}&Year={}&Month={}&Day=1&timeframe={}&submit=++T%C3%A9l%C3%A9charger+%0D%0Ades+donn%C3%A9es
- data = url.read()
outFilename = '{}/{}-{}'.format(outputDirectoryname, stationID, year)
if timeFrame == 1:
outFilename += '-{}-hourly'.format(month)
else:
outFilename += '-daily'
outFilename += '.csv'
- out = open(outFilename, 'w')
- out.write(data)
- out.close()
+ url = urllib.request.urlretrieve('http://climate.weather.gc.ca/climate_data/bulk_data_{}.html?format=csv&stationID={}&Year={}&Month={}&Day=1&timeframe={}&submit=Download+Data'.format(language, stationID, year, month, timeFrame), outFilename)
#########################
# File I/O
@@ -1013,40 +1008,6 @@
return [int(x) for x in l.split(separator)]
#########################
-# CLI utils
-#########################
-
-def parseCLIOptions(helpMessage, options, cliArgs, optionalOptions=[]):
- ''' Simple function to handle similar argument parsing
- Returns the dictionary of options and their values
-
- * cliArgs are most likely directly sys.argv
- (only the elements after the first one are considered)
-
- * options should be a list of strings for getopt options,
- eg ['frame=','correspondences=','video=']
- A value must be provided for each option, or the program quits'''
- import sys, getopt
- from numpy.core.fromnumeric import all
- optionValues, args = getopt.getopt(cliArgs[1:], 'h', ['help']+options+optionalOptions)
- optionValues = dict(optionValues)
-
- if '--help' in optionValues.keys() or '-h' in optionValues.keys():
- print(helpMessage+
- '\n - Compulsory options: '+' '.join([opt.replace('=','') for opt in options])+
- '\n - Non-compulsory options: '+' '.join([opt.replace('=','') for opt in optionalOptions]))
- sys.exit()
-
- missingArgument = [('--'+opt.replace('=','') in optionValues.keys()) for opt in options]
- if not all(missingArgument):
- print('Missing argument')
- print(optionValues)
- sys.exit()
-
- return optionValues
-
-
-#########################
# Profiling
#########################
diff -r 4f0312bee393 -r 01db14e947e4 scripts/classify-objects.py
--- a/scripts/classify-objects.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/classify-objects.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import cvutils, moving, ml, storage
diff -r 4f0312bee393 -r 01db14e947e4 scripts/clean-ground-truth.py
--- a/scripts/clean-ground-truth.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/clean-ground-truth.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import argparse
import pandas as pd
import sqlite3
diff -r 4f0312bee393 -r 01db14e947e4 scripts/compute-clearmot.py
--- a/scripts/compute-clearmot.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/compute-clearmot.py Fri Jun 01 10:47:49 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:
diff -r 4f0312bee393 -r 01db14e947e4 scripts/compute-homography.py
--- a/scripts/compute-homography.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/compute-homography.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse
diff -r 4f0312bee393 -r 01db14e947e4 scripts/create-bounding-boxes.py
--- a/scripts/create-bounding-boxes.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/create-bounding-boxes.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import argparse
diff -r 4f0312bee393 -r 01db14e947e4 scripts/create-metadata.py
--- a/scripts/create-metadata.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/create-metadata.py Fri Jun 01 10:47:49 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)')
diff -r 4f0312bee393 -r 01db14e947e4 scripts/delete-tables.py
--- a/scripts/delete-tables.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/delete-tables.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse
diff -r 4f0312bee393 -r 01db14e947e4 scripts/display-synced-trajectories.py
--- a/scripts/display-synced-trajectories.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/display-synced-trajectories.py Fri Jun 01 10:47:49 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()
diff -r 4f0312bee393 -r 01db14e947e4 scripts/display-trajectories.py
--- a/scripts/display-trajectories.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/display-trajectories.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse
diff -r 4f0312bee393 -r 01db14e947e4 scripts/extract-appearance-images.py
--- a/scripts/extract-appearance-images.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/extract-appearance-images.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import numpy as np, cv2
import argparse, os
diff -r 4f0312bee393 -r 01db14e947e4 scripts/extract-camera-parameters.py
--- a/scripts/extract-camera-parameters.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/extract-camera-parameters.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import argparse
diff -r 4f0312bee393 -r 01db14e947e4 scripts/info-video.py
--- a/scripts/info-video.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/info-video.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse
import cvutils
diff -r 4f0312bee393 -r 01db14e947e4 scripts/init-tracking.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/init-tracking.py Fri Jun 01 10:47:49 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')
diff -r 4f0312bee393 -r 01db14e947e4 scripts/init_tracking.py
--- a/scripts/init_tracking.py Fri Jun 01 10:43:23 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')
diff -r 4f0312bee393 -r 01db14e947e4 scripts/learn-motion-patterns.py
--- a/scripts/learn-motion-patterns.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/learn-motion-patterns.py Fri Jun 01 10:47:49 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:
diff -r 4f0312bee393 -r 01db14e947e4 scripts/learn-poi.py
--- a/scripts/learn-poi.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/learn-poi.py Fri Jun 01 10:47:49 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()
diff -r 4f0312bee393 -r 01db14e947e4 scripts/manual-video-analysis.py
--- a/scripts/manual-video-analysis.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/manual-video-analysis.py Fri Jun 01 10:47:49 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()
diff -r 4f0312bee393 -r 01db14e947e4 scripts/merge-features.py
--- a/scripts/merge-features.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/merge-features.py Fri Jun 01 10:47:49 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:
diff -r 4f0312bee393 -r 01db14e947e4 scripts/performance-db.py
--- a/scripts/performance-db.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/performance-db.py Fri Jun 01 10:47:49 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)
diff -r 4f0312bee393 -r 01db14e947e4 scripts/performance-lcss.py
--- a/scripts/performance-lcss.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/performance-lcss.py Fri Jun 01 10:47:49 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))
diff -r 4f0312bee393 -r 01db14e947e4 scripts/play-synced-videos.py
--- a/scripts/play-synced-videos.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/play-synced-videos.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse, os.path
import cvutils, utils
diff -r 4f0312bee393 -r 01db14e947e4 scripts/play-video.py
--- a/scripts/play-video.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/play-video.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys, argparse
import cvutils
diff -r 4f0312bee393 -r 01db14e947e4 scripts/polytracktopdtv.py
--- a/scripts/polytracktopdtv.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/polytracktopdtv.py Fri Jun 01 10:47:49 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):
diff -r 4f0312bee393 -r 01db14e947e4 scripts/process.py
--- a/scripts/process.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/process.py Fri Jun 01 10:47:49 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()
diff -r 4f0312bee393 -r 01db14e947e4 scripts/replay-event-annotation.py
--- a/scripts/replay-event-annotation.py Fri Jun 01 10:43:23 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'])
diff -r 4f0312bee393 -r 01db14e947e4 scripts/rescale-homography.py
--- a/scripts/rescale-homography.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/rescale-homography.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import sys
diff -r 4f0312bee393 -r 01db14e947e4 scripts/safety-analysis.py
--- a/scripts/safety-analysis.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/safety-analysis.py Fri Jun 01 10:47:49 2018 -0400
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import storage, prediction, events, moving
diff -r 4f0312bee393 -r 01db14e947e4 scripts/test-compute-object-position-from-features.py
--- a/scripts/test-compute-object-position-from-features.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/test-compute-object-position-from-features.py Fri Jun 01 10:47:49 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])
diff -r 4f0312bee393 -r 01db14e947e4 scripts/train-object-classification.py
--- a/scripts/train-object-classification.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/train-object-classification.py Fri Jun 01 10:47:49 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")
diff -r 4f0312bee393 -r 01db14e947e4 scripts/undistort-video.py
--- a/scripts/undistort-video.py Fri Jun 01 10:43:23 2018 -0400
+++ b/scripts/undistort-video.py Fri Jun 01 10:47:49 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)))