Mercurial Hosting > traffic-intelligence
comparison python/cvutils.py @ 672:5473b7460375
moved and rationalized imports in modules
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Tue, 26 May 2015 13:53:40 +0200 |
parents | 15e244d2a1b5 |
children | 5505f9dbb28e |
comparison
equal
deleted
inserted
replaced
671:849f5f8bf4b9 | 672:5473b7460375 |
---|---|
15 except ImportError: | 15 except ImportError: |
16 print('Scikit-image library could not be loaded (HoG-based classification methods will not be available)') | 16 print('Scikit-image library could not be loaded (HoG-based classification methods will not be available)') |
17 skimageAvailable = False | 17 skimageAvailable = False |
18 | 18 |
19 from sys import stdout | 19 from sys import stdout |
20 from numpy import dot, array, append | |
20 | 21 |
21 #import aggdraw # agg on top of PIL (antialiased drawing) | 22 #import aggdraw # agg on top of PIL (antialiased drawing) |
22 | 23 |
23 | 24 |
24 cvRed = (0,0,255) | 25 cvRed = (0,0,255) |
65 points = loadtxt(filename, delimiter=',') | 66 points = loadtxt(filename, delimiter=',') |
66 savetxt(utils.removeExtension(filename)+'-point-correspondences.txt',append(points[:,:2].T, points[:,3:].T, axis=0)) | 67 savetxt(utils.removeExtension(filename)+'-point-correspondences.txt',append(points[:,:2].T, points[:,3:].T, axis=0)) |
67 | 68 |
68 def loadPointCorrespondences(filename): | 69 def loadPointCorrespondences(filename): |
69 '''Loads and returns the corresponding points in world (first 2 lines) and image spaces (last 2 lines)''' | 70 '''Loads and returns the corresponding points in world (first 2 lines) and image spaces (last 2 lines)''' |
70 from numpy.lib.npyio import loadtxt | 71 from numpy import loadtxt, float32 |
71 from numpy import float32 | |
72 points = loadtxt(filename, dtype=float32) | 72 points = loadtxt(filename, dtype=float32) |
73 return (points[:2,:].T, points[2:,:].T) # (world points, image points) | 73 return (points[:2,:].T, points[2:,:].T) # (world points, image points) |
74 | 74 |
75 def cvMatToArray(cvmat): | 75 def cvMatToArray(cvmat): |
76 '''Converts an OpenCV CvMat to numpy array.''' | 76 '''Converts an OpenCV CvMat to numpy array.''' |
77 print('Deprecated, use new interface') | 77 print('Deprecated, use new interface') |
78 from numpy.core.multiarray import zeros | 78 from numpy import zeros |
79 a = zeros((cvmat.rows, cvmat.cols))#array([[0.0]*cvmat.width]*cvmat.height) | 79 a = zeros((cvmat.rows, cvmat.cols))#array([[0.0]*cvmat.width]*cvmat.height) |
80 for i in xrange(cvmat.rows): | 80 for i in xrange(cvmat.rows): |
81 for j in xrange(cvmat.cols): | 81 for j in xrange(cvmat.cols): |
82 a[i,j] = cvmat[i,j] | 82 a[i,j] = cvmat[i,j] |
83 return a | 83 return a |
114 else: | 114 else: |
115 cv2.imshow(windowName, img) | 115 cv2.imshow(windowName, img) |
116 | 116 |
117 def computeUndistortMaps(width, height, undistortedImageMultiplication, intrinsicCameraMatrix, distortionCoefficients): | 117 def computeUndistortMaps(width, height, undistortedImageMultiplication, intrinsicCameraMatrix, distortionCoefficients): |
118 from copy import deepcopy | 118 from copy import deepcopy |
119 from numpy import identity, array | 119 from numpy import identity |
120 newImgSize = (int(round(width*undistortedImageMultiplication)), int(round(height*undistortedImageMultiplication))) | 120 newImgSize = (int(round(width*undistortedImageMultiplication)), int(round(height*undistortedImageMultiplication))) |
121 newCameraMatrix = deepcopy(intrinsicCameraMatrix) | 121 newCameraMatrix = deepcopy(intrinsicCameraMatrix) |
122 newCameraMatrix[0,2] = newImgSize[0]/2. | 122 newCameraMatrix[0,2] = newImgSize[0]/2. |
123 newCameraMatrix[1,2] = newImgSize[1]/2. | 123 newCameraMatrix[1,2] = newImgSize[1]/2. |
124 return cv2.initUndistortRectifyMap(intrinsicCameraMatrix, array(distortionCoefficients), identity(3), newCameraMatrix, newImgSize, cv2.CV_32FC1) | 124 return cv2.initUndistortRectifyMap(intrinsicCameraMatrix, array(distortionCoefficients), identity(3), newCameraMatrix, newImgSize, cv2.CV_32FC1) |
323 print 'Cannot load file ' + videoFilename | 323 print 'Cannot load file ' + videoFilename |
324 | 324 |
325 def computeHomographyFromPDTV(camera): | 325 def computeHomographyFromPDTV(camera): |
326 '''Returns the homography matrix at ground level from PDTV camera | 326 '''Returns the homography matrix at ground level from PDTV camera |
327 https://bitbucket.org/hakanardo/pdtv''' | 327 https://bitbucket.org/hakanardo/pdtv''' |
328 from numpy import array | |
329 # camera = pdtv.load(cameraFilename) | 328 # camera = pdtv.load(cameraFilename) |
330 srcPoints = [[x,y] for x, y in zip([1.,2.,2.,1.],[1.,1.,2.,2.])] # need floats!! | 329 srcPoints = [[x,y] for x, y in zip([1.,2.,2.,1.],[1.,1.,2.,2.])] # need floats!! |
331 dstPoints = [] | 330 dstPoints = [] |
332 for srcPoint in srcPoints: | 331 for srcPoint in srcPoints: |
333 projected = camera.image_to_world(tuple(srcPoint)) | 332 projected = camera.image_to_world(tuple(srcPoint)) |
338 def undistortedCoordinates(map1, map2, x, y, maxDistance = 1.): | 337 def undistortedCoordinates(map1, map2, x, y, maxDistance = 1.): |
339 '''Returns the coordinates of a point in undistorted image | 338 '''Returns the coordinates of a point in undistorted image |
340 map1 and map2 are the mapping functions from undistorted image | 339 map1 and map2 are the mapping functions from undistorted image |
341 to distorted (original image) | 340 to distorted (original image) |
342 map1(x,y) = originalx, originaly''' | 341 map1(x,y) = originalx, originaly''' |
343 from numpy import abs, logical_and, unravel_index, dot, sum | 342 from numpy import abs, logical_and, unravel_index, sum |
344 from matplotlib.mlab import find | 343 from matplotlib.mlab import find |
345 distx = abs(map1-x) | 344 distx = abs(map1-x) |
346 disty = abs(map2-y) | 345 disty = abs(map2-y) |
347 indices = logical_and(distx<maxDistance, disty<maxDistance) | 346 indices = logical_and(distx<maxDistance, disty<maxDistance) |
348 closeCoordinates = unravel_index(find(indices), distx.shape) # returns i,j, ie y,x | 347 closeCoordinates = unravel_index(find(indices), distx.shape) # returns i,j, ie y,x |
457 out.write('\n') | 456 out.write('\n') |
458 | 457 |
459 def projectArray(homography, points): | 458 def projectArray(homography, points): |
460 '''Returns the coordinates of the projected points through homography | 459 '''Returns the coordinates of the projected points through homography |
461 (format: array 2xN points)''' | 460 (format: array 2xN points)''' |
462 from numpy.core import dot | |
463 from numpy.core.multiarray import array | |
464 from numpy.lib.function_base import append | |
465 | |
466 if points.shape[0] != 2: | 461 if points.shape[0] != 2: |
467 raise Exception('points of dimension {0} {1}'.format(points.shape[0], points.shape[1])) | 462 raise Exception('points of dimension {0} {1}'.format(points.shape[0], points.shape[1])) |
468 | 463 |
469 if (homography is not None) and homography.size>0: | 464 if (homography is not None) and homography.size>0: |
470 #alternatively, on could use cv2.convertpointstohomogeneous and other conversion to/from homogeneous coordinates | 465 #alternatively, on could use cv2.convertpointstohomogeneous and other conversion to/from homogeneous coordinates |
475 return points | 470 return points |
476 | 471 |
477 def project(homography, p): | 472 def project(homography, p): |
478 '''Returns the coordinates of the projection of the point p with coordinates p[0], p[1] | 473 '''Returns the coordinates of the projection of the point p with coordinates p[0], p[1] |
479 through homography''' | 474 through homography''' |
480 from numpy import array | |
481 return projectArray(homography, array([[p[0]],[p[1]]])) | 475 return projectArray(homography, array([[p[0]],[p[1]]])) |
482 | 476 |
483 def projectTrajectory(homography, trajectory): | 477 def projectTrajectory(homography, trajectory): |
484 '''Projects a series of points in the format | 478 '''Projects a series of points in the format |
485 [[x1, x2, ...], | 479 [[x1, x2, ...], |
486 [y1, y2, ...]]''' | 480 [y1, y2, ...]]''' |
487 from numpy.core.multiarray import array | |
488 return projectArray(homography, array(trajectory)) | 481 return projectArray(homography, array(trajectory)) |
489 | 482 |
490 def invertHomography(homography): | 483 def invertHomography(homography): |
491 '''Returns an inverted homography | 484 '''Returns an inverted homography |
492 Unnecessary for reprojection over camera image''' | 485 Unnecessary for reprojection over camera image''' |
493 from numpy.linalg.linalg import inv | 486 from numpy import inv |
494 invH = inv(homography) | 487 invH = inv(homography) |
495 invH /= invH[2,2] | 488 invH /= invH[2,2] |
496 return invH | 489 return invH |
497 | 490 |
498 def undistortTrajectory(invMap1, invMap2, positions): | 491 def undistortTrajectory(invMap1, invMap2, positions): |
515 undistortedTrajectory[0].append(x) | 508 undistortedTrajectory[0].append(x) |
516 undistortedTrajectory[1].append(y) | 509 undistortedTrajectory[1].append(y) |
517 return undistortedTrajectory | 510 return undistortedTrajectory |
518 | 511 |
519 def projectGInputPoints(homography, points): | 512 def projectGInputPoints(homography, points): |
520 from numpy import array | |
521 return projectTrajectory(homography, array(points+[points[0]]).T) | 513 return projectTrajectory(homography, array(points+[points[0]]).T) |
522 | 514 |
523 if opencvAvailable: | 515 if opencvAvailable: |
524 def computeTranslation(img1, img2, img1Points, maxTranslation2, minNMatches, windowSize = (5,5), level = 5, criteria = (cv2.TERM_CRITERIA_EPS, 0, 0.01)): | 516 def computeTranslation(img1, img2, img1Points, maxTranslation2, minNMatches, windowSize = (5,5), level = 5, criteria = (cv2.TERM_CRITERIA_EPS, 0, 0.01)): |
525 '''Computes the translation of img2 with respect to img1 | 517 '''Computes the translation of img2 with respect to img1 |
526 (loaded using OpenCV as numpy arrays) | 518 (loaded using OpenCV as numpy arrays) |
527 img1Points are used to compute the translation | 519 img1Points are used to compute the translation |
528 | 520 |
529 TODO add diagnostic if data is all over the place, and it most likely is not a translation (eg zoom, other non linear distortion)''' | 521 TODO add diagnostic if data is all over the place, and it most likely is not a translation (eg zoom, other non linear distortion)''' |
530 from numpy.core.multiarray import array | 522 from numpy import median, sum |
531 from numpy.lib.function_base import median | |
532 from numpy.core.fromnumeric import sum | |
533 | 523 |
534 nextPoints = array([]) | 524 nextPoints = array([]) |
535 (img2Points, status, track_error) = cv2.calcOpticalFlowPyrLK(img1, img2, img1Points, nextPoints, winSize=windowSize, maxLevel=level, criteria=criteria) | 525 (img2Points, status, track_error) = cv2.calcOpticalFlowPyrLK(img1, img2, img1Points, nextPoints, winSize=windowSize, maxLevel=level, criteria=criteria) |
536 # calcOpticalFlowPyrLK(prevImg, nextImg, prevPts[, nextPts[, status[, err[, winSize[, maxLevel[, criteria[, derivLambda[, flags]]]]]]]]) -> nextPts, status, err | 526 # calcOpticalFlowPyrLK(prevImg, nextImg, prevPts[, nextPts[, status[, err[, winSize[, maxLevel[, criteria[, derivLambda[, flags]]]]]]]]) -> nextPts, status, err |
537 delta = [] | 527 delta = [] |
566 imshow(hogViz) | 556 imshow(hogViz) |
567 return features | 557 return features |
568 | 558 |
569 def createHOGTrainingSet(imageDirectory, classLabel, rescaleSize = (64, 64), orientations=9, pixelsPerCell=(8, 8), cellsPerBlock=(2, 2), visualize=False, normalize=False): | 559 def createHOGTrainingSet(imageDirectory, classLabel, rescaleSize = (64, 64), orientations=9, pixelsPerCell=(8, 8), cellsPerBlock=(2, 2), visualize=False, normalize=False): |
570 from os import listdir | 560 from os import listdir |
571 from numpy import array, float32 | 561 from numpy import float32 |
572 from matplotlib.pyplot import imread | 562 from matplotlib.pyplot import imread |
573 | 563 |
574 inputData = [] | 564 inputData = [] |
575 for filename in listdir(imageDirectory): | 565 for filename in listdir(imageDirectory): |
576 img = imread(imageDirectory+filename) | 566 img = imread(imageDirectory+filename) |