1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 '''
35 The top level of this package contains some basic types used throughout
36 PyVision. Subpackages some of the more advanced functionality of the
37 PyVision library. These include:
38
39 * Image Processing
40 * Detection
41 * Machine Learning
42 * Optimization/Search
43 * Face Recognition
44 * Analysis
45
46 Typically, all these types are used in a program. A good convention is to
47 import the pyvision library as "pv" and then prefix all function names with "pv."
48 This will avoid possible namespace conflicts. For example::
49
50 import pyvision as pv
51 im = pv.Image(filename)
52 im.annotateLabel(pv.Point(10,10),"Hello, World!")
53 im.show()
54 '''
55
56 '''
57 -----------------------------------------------------------------------------
58 ALGORITHM DIRECTORY
59 Algorithm Name Problem Module
60 -----------------------------------------------------------------------------
61 Support Vector Mach. classify/regression pyvision.vector.SVM
62 PCA
63
64 Cascade Classifier face/object detect pyvision.face.CascadeClassifier
65 PCA (Face) face recognition pyvision.face.PCA
66
67 Genetic Algorithm optimization pyvision.optimize.GeneticAlgorithm
68 '''
69
70 import unittest
71 import sys
72 import cPickle as pkl
73
74 __version__ = "0.9.0 $Rev: 446 $"
75 __info__ = "$Id: __init__.py 446 2012-10-25 03:24:15Z bolme $"
76 __license__= '''
77 PyVision License
78
79 Copyright (c) 2006-2010 David S. Bolme
80 All rights reserved.
81
82 Redistribution and use in source and binary forms, with or without
83 modification, are permitted provided that the following conditions
84 are met:
85
86 1. Redistributions of source code must retain the above copyright
87 notice, this list of conditions and the following disclaimer.
88
89 2. Redistributions in binary form must reproduce the above copyright
90 notice, this list of conditions and the following disclaimer in the
91 documentation and/or other materials provided with the distribution.
92
93 3. Neither name of copyright holders nor the names of its contributors
94 may be used to endorse or promote products derived from this software
95 without specific prior written permission.
96
97
98 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
99 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
100 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
101 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
102 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
103 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
104 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
105 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
106 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
107 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
108 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109
110 Warning: Some parts of PyVision may link to libraries using more
111 restrictive licenses and some algorithms in PyVision by be covered
112 under patents. In these cases PyVision should display a warning
113 for commercial use. If you believe this a warning should be added
114 for any algorithm or interface please contact me at
115 bolme@cs.colostate.edu
116 '''
117
118 __all__ = ['analysis','edge','face','optimize','other','point','types','vector']
119
120 WARN_COMMERCIAL_USE = True
121
123 '''
124 Most of PyVision is released under the BSD license and
125 can therefore be used free of charge in commercial
126 projects. In some limited cases PyVision uses algorithms
127 that are covered by patents or source code released under
128 copy left open source licenses such as GPL which may make
129 software produced using those components unsuitable for
130 commercial distribution.
131
132 When a PyVision module contains or links to non-commercial
133 code a warning message will be printed to stdout. If you
134 would like to disable these warning simply call this function
135 before importing the offending module. The users PyVision are
136 responsible for determining if their use of those components
137 respects all applicable licenses and patents.
138
139 If you believe this a warning should be added for any algorithm
140 or interface please contact me at bolme@cs.colostate.edu
141 '''
142 global WARN_COMMERCIAL_USE
143 WARN_COMMERCIAL_USE = False
144
145
146
147
148
149
150 from pyvision.types.img import Image,OpenCVToNumpy,NumpyToOpenCV
151
152 from pyvision.types.Video import Video, Webcam, VideoFromImages, VideoFromFileList, VideoFromImageStack, FFMPEGVideo, VideoFromDirectory
153
154 from pyvision.types.Point import Point,readPointsFile
155
156 from pyvision.types.Rect import Rect,BoundingRect,CenteredRect
157
158 from pyvision.types.Affine import AffineNormalizePoints, AffineTranslate, AffineScale, AffineNonUniformScale, AffineRotate, AffineFromRect, AffineFromTile, AffineFromPoints, AffineFromPointsLS, AffineFromPointsRANSAC, AffineFromPointsLMeDs, AffinePerturb, AffineTransform
159
160 from pyvision.types.Perspective import PerspectiveTransform, PerspectiveFromPoints
161
162 from pyvision.analysis.ImageLog import ImageLog
163
164 from pyvision.analysis.Montage import ImageMontage, VideoMontage
165
166 try:
167 from pyvision.analysis.plot import Plot
168 except:
169 print "Warning: could not load plotting library."
170
171 from pyvision.analysis.Table import Table
172
173 from pyvision.analysis.Timer import Timer
174
175 from pyvision.analysis.roc import ROC,ROC_LOG_SAMPLED,ROC_MATCH_SAMPLED
176
177 from pyvision.types.ImageBuffer import ImageBuffer
178
179 from pyvision.surveillance.BackgroundSubtraction import AbstractBGModel, FrameDifferencer, MedianFilter, ApproximateMedianFilter, MotionCompensatedFrameDifferencer, BG_SUBTRACT_FD, BG_SUBTRACT_MCFD, BG_SUBTRACT_MF, BG_SUBTRACT_AMF
180
181 from pyvision.surveillance.MotionDetector import MotionDetector,BOUNDING_RECTS,STANDARDIZED_RECTS
182
183 from pyvision.surveillance.optical_flow import OpticalFlow
184
185 from pyvision.other.normalize import clipRange, meanStd, meanUnit, unit, selfQuotientImage, lowPassFilter, highPassFilter, bandPassFilter, gaussianFilter
186
187 from pyvision.other.distance import boolToUbyte, ubyteToBool, hamming, hamming_table
188
189 from pyvision.ml.knn import RobustPNorm,PNorm,correlation,chisquared,KNearestNeighbors,FLANNTree,FLANN_IMPORTED
190
191 try:
192 from pyvision.util.fast_util import LocalMaximumDetector
193 except:
194 print "Warning: could not import fast_util."
195
196 from pyvision.util.windows import cosineWindow, hammingWindow, hannWindow
197
198 from pyvision.analysis.stats import pbinom, qbinom, cibinom, mcnemar_test, SummaryStats, cor, cov, cov2cor
199
200 from pyvision.point.GaborJets import GaborFilters, GaborImage, GaborJet, FilterBank, GaborWavelet
201
202 from pyvision.other.color import Histogram, hsBackProjectHist, rgbBackProjectHist, RGBHist, HSHist, HIST_HS, HIST_RGB
203
204 from pyvision.ml.pca import prcomp, pca
205
206 from pyvision.ml.lda import lda
207
208 from pyvision.ml.regression import LogisticRegression
209
210 from pyvision.other.surf import surf
211
212 from pyvision.other.texture import lbp,LBP_CLASSIC,LBP_RAD1,LBP_RAD2,LBP_RAD3,LBP_RAD4,LBP_RAD8
213
214 from pyvision.analysis.bee import parseSigSet,saveSigset,computeMaskMatrix,BEE_CODE_MAP,BEE_DONTCARE,BEE_MATCH,BEE_NONMATCH,BEEDistanceMatrix
215
216 try:
217 from pyvision.data import AIRPLANE,BABOON,FRUITS,LENA,LOGO,TAZ_IMAGE,TAZ_VIDEO,FONT_ARIAL,BUGS_VIDEO,CAR_VIDEO, IRIS_DATA, IRIS_LABELS
218 except:
219 print "Warning: could not import data."
220 from pyvision.surveillance.VideoStreamProcessor import *
221
222 from analysis.progress_bar import ProgressBar
223
224 from analysis.gui_tools import capturePointsFromMouse
225
226 from pyvision.face import REDUCED_LEYE, REDUCED_REYE, REDUCED_SIZE
227
228 from pyvision.types.kinect import Kinect
229
230 from pyvision.surveillance.kalman import KalmanFilter
231
232 from pyvision.ml.opencv_ml import svc_linear, svc_rbf, svr_linear, svr_rbf, random_forest, boost, gbtrees
233
234 from pyvision.beta.vtm import VideoTaskManager, VideoTask, _VideoDataItem
235
236 from pyvision.analysis.html_report import HtmlReport
237
238 import beta
239
240 IMAGE_EXTENSIONS = ['.JPG','.JPEG','.GIF','.TIF','.TIFF','.PNG','.BMP','.PGM','.PPM',]
241 VIDEO_EXTENSIONS = ['.MOV','.M4V','.FLV','.AVI','.MPEG','.MJPEG','.MP4','.MPG','.WMV',]
242
243
244
245
247 '''Search dir(object) for patterns matching text'''
248 for name in dir(item):
249 if text.upper() in name.upper():
250 print name
251
253 '''
254 Return a short name describing the type.
255 '''
256 try:
257 if isinstance(item,list):
258 type_list = set([getTypeName(each) for each in item])
259 type_name = 'list:%d('%len(item)
260 for each in type_list:
261 type_name += each+","
262 type_name = type_name[:-1]
263 type_name += ")"
264 elif isinstance(item,tuple):
265 type_list = set([getTypeName(each) for each in item])
266 type_name = 'tuple:%d('%len(item)
267 for each in type_list:
268 type_name += each+","
269 type_name = type_name[:-1]
270 type_name += ")"
271 elif isinstance(item,dict):
272 type_list = set([getTypeName(each) for key,each in item.iteritems()])
273 type_name = 'dict:%d('%len(item)
274 for each in type_list:
275 type_name += each+","
276 type_name = type_name[:-1]
277 type_name += ")"
278 elif isinstance(item,str):
279 type_name = 'str'
280 elif isinstance(item,int):
281 type_name = 'int'
282 elif isinstance(item,float):
283 type_name = 'float'
284 elif 'instance' in repr(type(item)):
285 type_name = 'instance'
286 else:
287 type_name = str(type(item))
288 if type_name.startswith('<class'):
289 type_name = type_name[8:-2]
290 type_name = type_name.split('.')[-1]
291 if type_name.startswith('<type'):
292 type_name = type_name[7:-2]
293 type_name = type_name.split('.')[-1]
294
295 if type_name == 'ndarray':
296 type_name += ":%s:%s"%(item.shape,item.dtype)
297 type_name = "".join(type_name.split())
298 except:
299 type_name = 'unknown'
300
301 return type_name
302
303
304 -def inspectObject(item,name='<top>',max_depth=5,verbose=False,print_depth=0,info=None):
305 '''
306 Produce a pv.Table describing this object and its members.
307 '''
308 if max_depth < 0:
309 return
310
311 if not verbose and name[:2] == '__':
312 return
313 if 'function' in str(type(item)):
314 return
315 if 'method' in str(type(item)):
316 return
317
318 if info == None:
319 info = pv.Table()
320 info.setColumnFormat('name','%s')
321 print dir(info)
322 i = info.nRows()
323
324 info[i,'name'] = (' '*print_depth) + name
325 try:
326
327
328 type_name = getTypeName(item)
329 info[i,'type'] = type_name
330
331 value = " ".join(repr(item).split())
332 if len(value) > 30:
333 value = value[:27]+'...'
334 info[i,'value'] = value
335
336 try:
337 item_size = len(pkl.dumps(item, protocol=2))
338 except:
339 item_size = 'error'
340
341 info[i,'pickle size'] = item_size
342
343 if type_name in ['int','float','str']:
344 return info
345 if type_name.startswith('ndarray'):
346 return info
347
348 for each in dir(item):
349 inspectObject(getattr(item,each),name=each,max_depth=max_depth-1,verbose=verbose,print_depth=print_depth+1,info=info)
350
351
352 if isinstance(item,list) or isinstance(item,tuple):
353 processed_types = set()
354 for each in item:
355 if type(each) in processed_types:
356 continue
357 processed_types.add(type(each))
358 inspectObject(each,name='<sample item>',max_depth=max_depth-1,verbose=verbose,print_depth=print_depth+1,info=info)
359
360 if isinstance(item,dict):
361 processed_types = set()
362 for key,each in item.iteritems():
363 if type(each) in processed_types:
364 continue
365 processed_types.add(type(each))
366 inspectObject(each,name='<sample item>',max_depth=max_depth-1,verbose=verbose,print_depth=print_depth+1,info=info)
367 except:
368 info[i,'error'] = "Could not process this object."
369 return info
370
372 '''
373 Determines if the filename corresponds to a known image extension.
374 '''
375 for ext in IMAGE_EXTENSIONS:
376 if filename.upper().endswith(ext):
377 return True
378 return False
379
381 '''
382 Determines if the filename corresponds to a known image extension.
383 '''
384 for ext in VIDEO_EXTENSIONS:
385 if filename.upper().endswith(ext):
386 return True
387 return False
388
389
391 '''
392 @return: True if python interpreter is running in an iPython HTML Notebook.
393 (This may not work on all platforms.)
394 '''
395
396 try:
397 import IPython
398 gui = IPython.core.pylabtools.find_gui_and_backend()
399 if 'inline' not in gui:
400
401 return False
402 except:
403
404 return False
405
406
407 return True
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
462 ''' Check the installed versions of the dependencies '''
463
465 major,minor,sub = sys.version.split(' ')[0].split('.')[:3]
466 rmajor,rminor,rsub = 2,3,0
467 major,minor,sub = int(major),int(minor),int(sub)
468 print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
469 sys.stderr.flush()
470 self.assert_(major > rmajor
471 or major == rmajor and minor >= rminor
472 or major == rmajor and minor == rminor and sub >= sub)
473
475 import PIL.Image
476 major,minor,sub = PIL.Image.VERSION.split('.')[:3]
477 rmajor,rminor,rsub = 1,1,5
478 major,minor,sub = int(major),int(minor),int(sub)
479 print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
480 sys.stderr.flush()
481 self.assert_(major > rmajor
482 or major == rmajor and minor >= rminor
483 or major == rmajor and minor == rminor and sub >= sub)
484
486 import cv2
487 major,minor,sub = cv2.__version__.split('.')[:3]
488 rmajor,rminor,rsub = 2,4,2
489 major,minor,sub = int(major),int(minor),int(sub)
490 print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
491 sys.stderr.flush()
492 self.assert_(major > rmajor
493 or major == rmajor and minor >= rminor
494 or major == rmajor and minor == rminor and sub >= sub)
495
497 import scipy
498 major,minor,sub = scipy.__version__.split('.')[:3]
499 rmajor,rminor,rsub = 0,7,0
500 major,minor,sub = int(major),int(minor),int(sub)
501 print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
502 sys.stderr.flush()
503 self.assert_(major > rmajor
504 or major == rmajor and minor >= rminor
505 or major == rmajor and minor == rminor and sub >= sub)
506
508 import numpy
509 major,minor,sub = numpy.__version__.split('.')[:3]
510 rmajor,rminor,rsub = 1,0,4
511 major,minor,sub = int(major),int(minor),int(sub)
512 print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
513 sys.stderr.flush()
514 self.assert_(major > rmajor
515 or major == rmajor and minor >= rminor
516 or major == rmajor and minor == rminor and sub >= sub)
517
519 import svm
520
521 rmajor,rminor,_ = 2,86,0
522
523
524 print >> sys.stderr, "No way to get version numbers >= %d.%d "%(rmajor,rminor),
525 sys.stderr.flush()
526
527
528
529 self.assert_(True)
530
532 disableCommercialUseWarnings()
533
534 version_suite = unittest.TestLoader().loadTestsFromTestCase(_VersionTest)
535
536 from pyvision.types.Affine import _AffineTest
537 affine_suite = unittest.TestLoader().loadTestsFromTestCase(_AffineTest)
538
539 from pyvision.types.testsuite import _TestImage
540 image_suite = unittest.TestLoader().loadTestsFromTestCase(_TestImage)
541
542 from pyvision.vector.VectorClassifier import _TestVectorClassifier
543 vc_suite = unittest.TestLoader().loadTestsFromTestCase(_TestVectorClassifier)
544
545
546
547
548 from pyvision.vector.Polynomial import _PolyTest
549 poly_suite = unittest.TestLoader().loadTestsFromTestCase(_PolyTest)
550
551 from pyvision.point.DetectorCorner import _CornerTest
552 corner_suite = unittest.TestLoader().loadTestsFromTestCase(_CornerTest)
553
554 from pyvision.point.DetectorDOG import _DetectorDOGTestCase
555 dog_suite = unittest.TestLoader().loadTestsFromTestCase(_DetectorDOGTestCase)
556
557 from pyvision.point.DetectorHarris import _HarrisTest
558 harris_suite = unittest.TestLoader().loadTestsFromTestCase(_HarrisTest)
559
560 from pyvision.point.PhaseCorrelation import _TestPhaseCorrelation
561 pc_suite = unittest.TestLoader().loadTestsFromTestCase(_TestPhaseCorrelation)
562
563 from pyvision.optimize.testsuite import GeneticAlgorithmTest
564 ga_suite = unittest.TestLoader().loadTestsFromTestCase(GeneticAlgorithmTest)
565
566 from pyvision.face.CascadeDetector import _TestCascadeDetector
567 cd_suite = unittest.TestLoader().loadTestsFromTestCase(_TestCascadeDetector)
568
569 from pyvision.face.PCA import _TestFacePCA
570 fpca_suite = unittest.TestLoader().loadTestsFromTestCase(_TestFacePCA)
571
572 from pyvision.face.FilterEyeLocator import _TestFilterEyeLocator
573 asefed_suite = unittest.TestLoader().loadTestsFromTestCase(_TestFilterEyeLocator)
574
575
576
577
578
579 from pyvision.edge.canny import _TestCanny
580 canny_suite = unittest.TestLoader().loadTestsFromTestCase(_TestCanny)
581
582 from pyvision.analysis.stats import _TestStats
583 stats_suite = unittest.TestLoader().loadTestsFromTestCase(_TestStats)
584
585 from pyvision.analysis.Table import _TestTable
586 table_suite = unittest.TestLoader().loadTestsFromTestCase(_TestTable)
587
588 from pyvision.analysis.classifier.ConfusionMatrix import _TestConfusionMatrix
589 cm_suite = unittest.TestLoader().loadTestsFromTestCase(_TestConfusionMatrix)
590
591 from pyvision.other.testsuite import _TestDistance
592 dist_suite = unittest.TestLoader().loadTestsFromTestCase(_TestDistance)
593
594 from pyvision.other.testsuite import _TestNormalize
595 norm_suite = unittest.TestLoader().loadTestsFromTestCase(_TestNormalize)
596
597 from pyvision.other.testsuite import _TestSURF
598 surf_suite = unittest.TestLoader().loadTestsFromTestCase(_TestSURF)
599
600
601 test_suites = [
602 version_suite,
603 affine_suite,
604 image_suite,
605 vc_suite,
606
607 poly_suite,
608 corner_suite,
609 dog_suite,
610 harris_suite,
611 pc_suite,
612 ga_suite,
613 cd_suite,
614 fpca_suite,
615 asefed_suite,
616
617 canny_suite,
618 stats_suite,
619 table_suite,
620 cm_suite,
621 dist_suite,
622 norm_suite,
623 surf_suite,
624 ]
625
626 pyvision_suite = unittest.TestSuite(test_suites)
627
628 unittest.TextTestRunner(verbosity=2).run(pyvision_suite)
629
630
631 if __name__ == '__main__':
632 test()
633