From d2b52faccfa57f40f6f55071ef9fe3d0227d8604 Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Wed, 12 Aug 2015 18:31:00 -0700 Subject: [PATCH 1/3] Apply futurize stage 1. --- SimpleCV/Camera.py | 103 +- SimpleCV/Color.py | 3 +- SimpleCV/ColorModel.py | 2 +- SimpleCV/Display.py | 3 +- SimpleCV/DrawingLayer.py | 3 +- SimpleCV/EXIF.py | 49 +- SimpleCV/Features/BOFFeatureExtractor.py | 11 +- SimpleCV/Features/BlobMaker.py | 2 +- SimpleCV/Features/FaceRecognizer.py | 2 +- SimpleCV/Features/Features.py | 2 +- SimpleCV/Features/HaarCascade.py | 4 +- .../PlayingCards/CardDataCollection.py | 12 +- SimpleCV/Features/PlayingCards/CardUtil.py | 3 +- .../PlayingCards/PlayingCardFactory.py | 3 +- SimpleCV/Features/PlayingCards/TestScript.py | 8 +- SimpleCV/Font.py | 9 +- SimpleCV/ImageClass.py | 130 +- SimpleCV/LineScan.py | 15 +- SimpleCV/MachineLearning/KNNClassifier.py | 19 +- SimpleCV/MachineLearning/MLTestSuite.py | 23 +- .../MachineLearning/NaiveBayesClassifier.py | 19 +- SimpleCV/MachineLearning/SVMClassifier.py | 17 +- .../MachineLearning/ShapeContextClassifier.py | 9 +- .../MachineLearning/TemporalColorTracker.py | 29 +- SimpleCV/MachineLearning/TreeClassifier.py | 29 +- SimpleCV/MachineLearning/TurkingModule.py | 11 +- .../MachineLearning/TurkingModuleExample.py | 9 +- .../MachineLearning/query_imgs/flickrapi2.py | 1069 +++++++++-------- .../query_imgs/get_imgs_geo_gps_search.py | 51 +- SimpleCV/Shell/Example.py | 41 +- SimpleCV/Shell/Shell.py | 7 +- SimpleCV/Shell/Tutorial.py | 451 +++---- SimpleCV/Shell/__init__.py | 3 +- SimpleCV/Stream.py | 4 +- SimpleCV/Tracking/LKTracker.py | 3 +- SimpleCV/Tracking/SURFTracker.py | 3 +- SimpleCV/base.py | 50 +- .../examples/arduino/CannyStream-arduino.py | 5 +- SimpleCV/examples/detection/CannyCam.py | 3 +- SimpleCV/examples/detection/CoinDetector.py | 3 +- SimpleCV/examples/detection/EdgeSnap.py | 3 +- .../examples/detection/FeatureDetection.py | 3 +- .../detection/FisherFaceRecognizer.py | 3 +- .../detection/Least-Squares-Circle.py | 7 +- SimpleCV/examples/detection/MotionTracker.py | 3 +- .../examples/detection/TemplateMatching.py | 5 +- .../detection/TrainFacialRecognition.py | 3 +- SimpleCV/examples/detection/balltrack.py | 5 +- SimpleCV/examples/detection/barcode_reader.py | 7 +- SimpleCV/examples/detection/dealwithit.py | 3 +- .../examples/detection/face-substition.py | 3 +- SimpleCV/examples/detection/facetrack.py | 3 +- SimpleCV/examples/detection/pills.py | 3 +- SimpleCV/examples/detection/x-ray.py | 3 +- SimpleCV/examples/display/RenderExample.py | 25 +- .../examples/display/gtk-example-camera.py | 3 +- SimpleCV/examples/display/gtk-example.py | 3 +- SimpleCV/examples/display/simplecam.py | 3 +- .../examples/kinect/kinect-motion-blur.py | 1 + .../machine-learning/color_cluster.py | 3 +- .../machine-learning_nuts-vs-bolts.py | 19 +- SimpleCV/examples/manipulation/GreenScreen.py | 3 +- .../examples/manipulation/ImageMotionBlur.py | 3 +- .../manipulation/MorphologyExample.py | 3 +- SimpleCV/examples/manipulation/Partycam.py | 3 +- .../examples/manipulation/RotationExample.py | 3 +- .../manipulation/colorsegmentation.py | 5 +- SimpleCV/examples/manipulation/motionblur.py | 4 +- SimpleCV/examples/manipulation/threedee.py | 9 +- SimpleCV/examples/manipulation/tvexample.py | 3 +- SimpleCV/examples/tracking/camshift.py | 11 +- SimpleCV/examples/tracking/lk.py | 3 +- SimpleCV/examples/tracking/mftrack.py | 7 +- SimpleCV/examples/tracking/surftest.py | 3 +- SimpleCV/examples/util/CaptureEncodeUpload.py | 3 +- .../web-based/cloudanimator/cloudanimator.py | 5 +- .../web-based/cloudanimator/images2gif.py | 3 +- .../examples/web-based/cloudcam/cloudcam.py | 5 +- .../web-based/webdisplay/flask-server.py | 7 +- SimpleCV/tests/ShapeContext/test_c.py | 9 +- SimpleCV/tests/ShapeContext/test_multi.py | 23 +- SimpleCV/tests/YCrCbtests.py | 23 +- SimpleCV/tests/test_cameras.py | 3 +- SimpleCV/tests/test_display.py | 10 +- SimpleCV/tests/test_optional.py | 3 +- SimpleCV/tests/test_stereovision.py | 3 +- SimpleCV/tests/test_vimba.py | 27 +- SimpleCV/tests/test_vimba_async.py | 5 +- SimpleCV/tests/test_vimba_manyshots.py | 9 +- SimpleCV/tests/tests.py | 36 +- SimpleCV/tests/vcamera_tests.py | 3 +- SimpleCV/tools/Calibrate.py | 5 +- scripts/install/mac/findmods.py | 3 +- .../freenect-examples/demo_cv_async.py | 67 +- .../freenect-examples/demo_cv_sync.py | 47 +- .../freenect-examples/demo_cv_sync_multi.py | 79 +- .../freenect-examples/demo_cv_thresh_sweep.py | 65 +- .../freenect-examples/demo_cv_threshold.py | 109 +- .../freenect-examples/demo_mp_async.py | 99 +- .../freenect-examples/demo_mp_sync.py | 79 +- .../OpenKinect/freenect-examples/demo_tilt.py | 63 +- scripts/mkvirt.py | 3 +- 102 files changed, 1648 insertions(+), 1541 deletions(-) diff --git a/SimpleCV/Camera.py b/SimpleCV/Camera.py index fb799def7..4890a54b4 100644 --- a/SimpleCV/Camera.py +++ b/SimpleCV/Camera.py @@ -1,3 +1,4 @@ +from __future__ import print_function # SimpleCV Cameras & Devices #load system libraries @@ -369,7 +370,7 @@ def live(self): i.dl().text(txt, (10,i.height / 2), color=col) txt = "color: " + str(i.getPixel(d.mouseX,d.mouseY)) i.dl().text(txt, (10,(i.height / 2) + 10), color=col) - print "coord: (" + str(d.mouseX) + "," + str(d.mouseY) + "), color: " + str(i.getPixel(d.mouseX,d.mouseY)) + print("coord: (" + str(d.mouseX) + "," + str(d.mouseY) + "), color: " + str(i.getPixel(d.mouseX,d.mouseY))) if elapsed_time > 0 and elapsed_time < 5: @@ -381,7 +382,7 @@ def live(self): i.save(d) if d.mouseRight: - print "Closing Window" + print("Closing Window") d.done = True @@ -483,7 +484,7 @@ def __init__(self, camera_index = -1, prop_set = {}, threaded = True, calibratio if "delay" in prop_set: time.sleep(prop_set['delay']) - if platform.system() == "Linux" and (prop_set.has_key("height") or cv.GrabFrame(self.capture) == False): + if platform.system() == "Linux" and ("height" in prop_set or cv.GrabFrame(self.capture) == False): import pygame.camera pygame.camera.init() threaded = True #pygame must be threaded @@ -491,8 +492,8 @@ def __init__(self, camera_index = -1, prop_set = {}, threaded = True, calibratio camera_index = 0 self.index = camera_index _index.append(camera_index) - print _index - if(prop_set.has_key("height") and prop_set.has_key("width")): + print(_index) + if("height" in prop_set and "width" in prop_set): self.capture = pygame.camera.Camera("/dev/video" + str(camera_index), (prop_set['width'], prop_set['height'])) else: self.capture = pygame.camera.Camera("/dev/video" + str(camera_index)) @@ -682,16 +683,16 @@ def __init__(self, s, st, start=1): self.start = start if self.sourcetype not in ["video", "image", "imageset", "directory"]: - print 'Error: In VirtualCamera(), Incorrect Source option. "%s" \nUsage:' % self.sourcetype - print '\tVirtualCamera("filename","video")' - print '\tVirtualCamera("filename","image")' - print '\tVirtualCamera("./path_to_images","imageset")' - print '\tVirtualCamera("./path_to_images","directory")' + print('Error: In VirtualCamera(), Incorrect Source option. "%s" \nUsage:' % self.sourcetype) + print('\tVirtualCamera("filename","video")') + print('\tVirtualCamera("filename","image")') + print('\tVirtualCamera("./path_to_images","imageset")') + print('\tVirtualCamera("./path_to_images","directory")') return None else: if isinstance(self.source,str) and not os.path.exists(self.source): - print 'Error: In VirtualCamera()\n\t"%s" was not found.' % self.source + print('Error: In VirtualCamera()\n\t"%s" was not found.' % self.source) return None if (self.sourcetype == "imageset"): @@ -737,7 +738,7 @@ def getImage(self): return Image(self.source, self) elif (self.sourcetype == 'imageset'): - print len(self.source) + print(len(self.source)) img = self.source[self.counter % len(self.source)] self.counter = self.counter + 1 return img @@ -1084,10 +1085,10 @@ def run(self): f = urllib2.urlopen(self.url) headers = f.info() - if (headers.has_key("content-type")): + if ("content-type" in headers): headers['Content-type'] = headers['content-type'] #force ucase first char - if not headers.has_key("Content-type"): + if "Content-type" not in headers: logger.warning("Tried to load a JpegStream from " + self.url + ", but didn't find a content-type header!") return @@ -1335,7 +1336,7 @@ def printProperties(self): """ for prop in self.device.optlist: try: - print self.device[prop] + print(self.device[prop]) except: pass @@ -1589,7 +1590,7 @@ def getImage(self): if self._roi : img = img.crop(self._roi,centered=True) except : - print "Error croping the image. ROI specified is not correct." + print("Error croping the image. ROI specified is not correct.") return None return img @@ -2241,7 +2242,7 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri frameRight = cv.QueryFrame(captureRight) cv.FindChessboardCorners(frameRight, (chessboard)) except : - print "Error Initialising the Left and Right camera" + print("Error Initialising the Left and Right camera") return None imagePoints1 = cv.CreateMat(1, nboards * chessboard[0] * chessboard[1], cv.CV_64FC2) @@ -2284,7 +2285,7 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri cv.ShowImage(n2, frameRight) if cor1[0] and cor2[0] and k==0x20: - print count + print(count) for i in range(0, len(cor1[1])): cv.Set1D(imagePoints1, count * chessboard[0] * chessboard[1] + i, cv.Scalar(cor1[1][i][0], cor1[1][i][1])) cv.Set1D(imagePoints2, count * chessboard[0] * chessboard[1] + i, cv.Scalar(cor2[1][i][0], cor2[1][i][1])) @@ -2307,19 +2308,19 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri cv.Zero(D1) cv.Zero(D2) - print "Running stereo calibration..." + print("Running stereo calibration...") del(camLeft) del(camRight) cv.StereoCalibrate(objectPoints, imagePoints1, imagePoints2, nPoints, CM1, D1, CM2, D2, WinSize, R, T, E, F, flags=cv.CV_CALIB_SAME_FOCAL_LENGTH | cv.CV_CALIB_ZERO_TANGENT_DIST) - print "Done." + print("Done.") return (CM1, CM2, D1, D2, R, T, E, F) cv.ShowImage(n1, frameLeft) cv.ShowImage(n2, frameRight) if k == 0x1b: - print "ESC pressed. Exiting. WARNING: NOT ENOUGH CHESSBOARDS FOUND YET" + print("ESC pressed. Exiting. WARNING: NOT ENOUGH CHESSBOARDS FOUND YET") cv.DestroyAllWindows() break @@ -2373,7 +2374,7 @@ def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): cv.Save("{0}/{1}".format(cdir, filenames[5]), T) cv.Save("{0}/{1}".format(cdir, filenames[6]), E) cv.Save("{0}/{1}".format(cdir, filenames[7]), F) - print "Calibration parameters written to directory '{0}'.".format(cdir) + print("Calibration parameters written to directory '{0}'.".format(cdir)) return True except : @@ -2421,7 +2422,7 @@ def loadCalibration(self,fname="Stereo",dir="."): T = cv.Load("{0}/{1}".format(dir, filenames[5])) E = cv.Load("{0}/{1}".format(dir, filenames[6])) F = cv.Load("{0}/{1}".format(dir, filenames[7])) - print "Calibration files loaded from dir '{0}'.".format(dir) + print("Calibration files loaded from dir '{0}'.".format(dir)) return (CM1, CM2, D1, D2, R, T, E, F) except : @@ -2469,7 +2470,7 @@ def stereoRectify(self,calib=None,WinSize=(352,288)): P2 = cv.CreateMat(3, 4, cv.CV_64F) Q = cv.CreateMat(4, 4, cv.CV_64F) - print "Running stereo rectification..." + print("Running stereo rectification...") (leftroi, rightroi) = cv.StereoRectify(CM1, CM2, D1, D2, WinSize, R, T, R1, R2, P1, P2, Q) roi = [] @@ -2477,7 +2478,7 @@ def stereoRectify(self,calib=None,WinSize=(352,288)): roi.append(max(leftroi[1], rightroi[1])) roi.append(min(leftroi[2], rightroi[2])) roi.append(min(leftroi[3], rightroi[3])) - print "Done." + print("Done.") return (R1, R2, P1, P2, Q, roi) def getImagesUndistort(self,imgLeft, imgRight, calibration, rectification, WinSize=(352,288)): @@ -3206,9 +3207,9 @@ def getImage(self, timeout = 5000): st = time.time() try: pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(self.frame), timeout) ) - except Exception, e: - print "Exception waiting for frame:", e - print "Time taken:",time.time() - st + except Exception as e: + print("Exception waiting for frame:", e) + print("Time taken:",time.time() - st) self.frame = None raise(e) img = self.unbuffer() @@ -3267,13 +3268,13 @@ def _getFrame(self, timeout = 5000): st = time.time() try: pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(frame), timeout) ) - except Exception, e: - print "Exception waiting for frame:", e - print "Time taken:",time.time() - st + except Exception as e: + print("Exception waiting for frame:", e) + print("Time taken:",time.time() - st) raise(e) - except Exception, e: - print "Exception aquiring frame:", e + except Exception as e: + print("Exception aquiring frame:", e) raise(e) return frame @@ -3284,8 +3285,8 @@ def acquire(self): self.runCommand("AcquisitionStart") pverr( self.dll.PvCaptureQueueFrame(self.handle, ct.byref(self.frame), None) ) self.runCommand("AcquisitionStop") - except Exception, e: - print "Exception aquiring frame:", e + except Exception as e: + print("Exception aquiring frame:", e) raise(e) @@ -3298,8 +3299,8 @@ def __init__(self, camera_id = None, properties = {}, threaded = False): try: from gi.repository import Aravis except: - print "GigE is supported by the Aravis library, download and build from https://github.com/sightmachine/aravis" - print "Note that you need to set GI_TYPELIB_PATH=$GI_TYPELIB_PATH:(PATH_TO_ARAVIS)/src for the GObject Introspection" + print("GigE is supported by the Aravis library, download and build from https://github.com/sightmachine/aravis") + print("Note that you need to set GI_TYPELIB_PATH=$GI_TYPELIB_PATH:(PATH_TO_ARAVIS)/src for the GObject Introspection") sys.exit() self._cam = Aravis.Camera.new (None) @@ -3387,17 +3388,17 @@ def getProperty(self, name = None): see function camera.getPropertyList() ''' if name == None: - print "You need to provide a property, available properties are:" - print "" + print("You need to provide a property, available properties are:") + print("") for p in self.getPropertyList(): - print p + print(p) return stringval = "get_{}".format(name) try: return getattr(self._cam, stringval)() except: - print 'Property {} does not appear to exist'.format(name) + print('Property {} does not appear to exist'.format(name)) return None def setProperty(self, name = None, *args): @@ -3413,21 +3414,21 @@ def setProperty(self, name = None, *args): ''' if name == None: - print "You need to provide a property, available properties are:" - print "" + print("You need to provide a property, available properties are:") + print("") for p in self.getPropertyList(): - print p + print(p) return if len(args) <= 0: - print "You must provide a value to set" + print("You must provide a value to set") return stringval = "set_{}".format(name) try: return getattr(self._cam, stringval)(*args) except: - print 'Property {} does not appear to exist or value is not in correct format'.format(name) + print('Property {} does not appear to exist or value is not in correct format'.format(name)) return None @@ -3437,7 +3438,7 @@ def getAllProperties(self): ''' for p in self.getPropertyList(): - print "{}: {}".format(p,self.getProperty(p)) + print("{}: {}".format(p,self.getProperty(p))) class VimbaCameraThread(threading.Thread): camera = None @@ -3805,8 +3806,8 @@ def _captureFrame(self, timeout = 5000): c.runFeatureCommand('AcquisitionStop') try: f.waitFrameCapture(timeout) - except Exception, e: - print "Exception waiting for frame: %s: %s" % (e, traceback.format_exc()) + except Exception as e: + print("Exception waiting for frame: %s: %s" % (e, traceback.format_exc())) raise(e) imgData = f.getBufferByteData() @@ -3819,7 +3820,7 @@ def _captureFrame(self, timeout = 5000): return Image(rgb, colorSpace=colorSpace, cv2image=imgData) - except Exception, e: - print "Exception acquiring frame: %s: %s" % (e, traceback.format_exc()) + except Exception as e: + print("Exception acquiring frame: %s: %s" % (e, traceback.format_exc())) raise(e) diff --git a/SimpleCV/Color.py b/SimpleCV/Color.py index 6d6a26a2e..748d1a743 100644 --- a/SimpleCV/Color.py +++ b/SimpleCV/Color.py @@ -1,3 +1,4 @@ +from __future__ import print_function # SimpleCV Color Library # # This library is used to modify different color properties of images @@ -213,7 +214,7 @@ def getHueFromBGR(self,color_tuple): """ a = color_tuple - print a + print(a) h_float = colorsys.rgb_to_hsv(*tuple(reversed(color_tuple)))[0] return h_float*180 diff --git a/SimpleCV/ColorModel.py b/SimpleCV/ColorModel.py index 1a5fe625f..40b956b54 100644 --- a/SimpleCV/ColorModel.py +++ b/SimpleCV/ColorModel.py @@ -198,7 +198,7 @@ def contains(self, c): """ #reverse the color, cast to uint8, right shift, convert to string, check dict - return self.mData.has_key(np.right_shift(np.cast['uint8'](c[::-1]), self.mBits).tostring()) + return np.right_shift(np.cast['uint8'](c[::-1]), self.mBits).tostring() in self.mData def setIsForeground(self): """ diff --git a/SimpleCV/Display.py b/SimpleCV/Display.py index 47a8b1a8d..785ff3e04 100644 --- a/SimpleCV/Display.py +++ b/SimpleCV/Display.py @@ -1,7 +1,8 @@ +from __future__ import absolute_import from SimpleCV.base import * import SimpleCV.ImageClass import Queue -from base import * +from .base import * PYGAME_INITIALIZED = False diff --git a/SimpleCV/DrawingLayer.py b/SimpleCV/DrawingLayer.py index a1cd9e60e..286cbb401 100644 --- a/SimpleCV/DrawingLayer.py +++ b/SimpleCV/DrawingLayer.py @@ -39,8 +39,9 @@ class DrawingLayer: width = 0 height = 0 - def __init__(self, (width, height)): + def __init__(self, xxx_todo_changeme): #pg.init() + (width, height) = xxx_todo_changeme if( not pg.font.get_init() ): pg.font.init() diff --git a/SimpleCV/EXIF.py b/SimpleCV/EXIF.py index 973696605..d0dbb86ce 100755 --- a/SimpleCV/EXIF.py +++ b/SimpleCV/EXIF.py @@ -84,6 +84,7 @@ # Don't throw an exception when given an out of range character. +from __future__ import print_function def make_string(seq): str = '' for c in seq: @@ -1179,7 +1180,7 @@ def s2n_motorola(str): # extract multibyte integer in Intel format (big endian) def s2n_intel(str): x = 0 - y = 0L + y = 0 for c in str: x = x | (ord(c) << y) y = y + 8 @@ -1260,7 +1261,7 @@ def s2n(self, offset, length, signed=0): val=s2n_motorola(slice) # Sign extension ? if signed: - msb=1L << (8*length-1) + msb=1 << (8*length-1) if val & msb: val=val-(msb << 1) return val @@ -1409,8 +1410,8 @@ def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0, stop_tag='UNDEF'): values, field_offset, count * typelen) if self.debug: - print ' debug: %s: %s' % (tag_name, - repr(self.tags[ifd_name + ' ' + tag_name])) + print(' debug: %s: %s' % (tag_name, + repr(self.tags[ifd_name + ' ' + tag_name]))) if tag_name == stop_tag: break @@ -1510,13 +1511,13 @@ def decode_maker_note(self): if 'NIKON' in make: if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]: if self.debug: - print "Looks like a type 1 Nikon MakerNote." + print("Looks like a type 1 Nikon MakerNote.") self.dump_IFD(note.field_offset+8, 'MakerNote', dict=MAKERNOTE_NIKON_OLDER_TAGS) elif note.values[0:7] == [78, 105, 107, 111, 110, 0, 2]: if self.debug: - print "Looks like a labeled type 2 Nikon MakerNote" - if note.values[12:14] != [0, 42] and note.values[12:14] != [42L, 0L]: + print("Looks like a labeled type 2 Nikon MakerNote") + if note.values[12:14] != [0, 42] and note.values[12:14] != [42, 0]: raise ValueError("Missing marker tag '42' in MakerNote.") # skip the Makernote label and the TIFF header self.dump_IFD(note.field_offset+10+8, 'MakerNote', @@ -1524,7 +1525,7 @@ def decode_maker_note(self): else: # E99x or D1 if self.debug: - print "Looks like an unlabeled type 2 Nikon MakerNote" + print("Looks like an unlabeled type 2 Nikon MakerNote") self.dump_IFD(note.field_offset, 'MakerNote', dict=MAKERNOTE_NIKON_NEWER_TAGS) return @@ -1581,7 +1582,7 @@ def canon_decode_tag(self, value, dict): for i in range(1, len(value)): x=dict.get(i, ('Unknown', )) if self.debug: - print i, x + print(i, x) name=x[0] if len(x) > 1: val=x[1].get(value[i], 'Unknown') @@ -1632,7 +1633,7 @@ def process_file(f, stop_tag='UNDEF', details=True, strict=False, debug=False): # deal with the EXIF info we found if debug: - print {'I': 'Intel', 'M': 'Motorola'}[endian], 'format' + print({'I': 'Intel', 'M': 'Motorola'}[endian], 'format') hdr = EXIF_header(f, endian, offset, fake_exif, strict, debug) ifd_list = hdr.list_IFDs() ctr = 0 @@ -1645,27 +1646,27 @@ def process_file(f, stop_tag='UNDEF', details=True, strict=False, debug=False): else: IFD_name = 'IFD %d' % ctr if debug: - print ' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i) + print(' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i)) hdr.dump_IFD(i, IFD_name, stop_tag=stop_tag) # EXIF IFD exif_off = hdr.tags.get(IFD_name+' ExifOffset') if exif_off: if debug: - print ' EXIF SubIFD at offset %d:' % exif_off.values[0] + print(' EXIF SubIFD at offset %d:' % exif_off.values[0]) hdr.dump_IFD(exif_off.values[0], 'EXIF', stop_tag=stop_tag) # Interoperability IFD contained in EXIF IFD intr_off = hdr.tags.get('EXIF SubIFD InteroperabilityOffset') if intr_off: if debug: - print ' EXIF Interoperability SubSubIFD at offset %d:' \ - % intr_off.values[0] + print(' EXIF Interoperability SubSubIFD at offset %d:' \ + % intr_off.values[0]) hdr.dump_IFD(intr_off.values[0], 'EXIF Interoperability', dict=INTR_TAGS, stop_tag=stop_tag) # GPS IFD gps_off = hdr.tags.get(IFD_name+' GPSInfo') if gps_off: if debug: - print ' GPS SubIFD at offset %d:' % gps_off.values[0] + print(' GPS SubIFD at offset %d:' % gps_off.values[0]) hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS, stop_tag=stop_tag) ctr += 1 @@ -1706,7 +1707,7 @@ def usage(exit_status): msg += '-t TAG --stop-tag TAG Stop processing when this tag is retrieved.\n' msg += '-s --strict Run in strict mode (stop on errors).\n' msg += '-d --debug Run in debug mode (display extra info).\n' - print msg + print(msg) sys.exit(exit_status) # library test/debug function (dump given files) @@ -1742,13 +1743,13 @@ def usage(exit_status): try: file=open(filename, 'rb') except: - print "'%s' is unreadable\n"%filename + print("'%s' is unreadable\n"%filename) continue - print filename + ':' + print(filename + ':') # get the tags data = process_file(file, stop_tag=stop_tag, details=detailed, strict=strict, debug=debug) if not data: - print 'No EXIF information found' + print('No EXIF information found') continue x=data.keys() @@ -1757,10 +1758,10 @@ def usage(exit_status): if i in ('JPEGThumbnail', 'TIFFThumbnail'): continue try: - print ' %s (%s): %s' % \ - (i, FIELD_TYPES[data[i].field_type][2], data[i].printable) + print(' %s (%s): %s' % \ + (i, FIELD_TYPES[data[i].field_type][2], data[i].printable)) except: - print 'error', i, '"', data[i], '"' + print('error', i, '"', data[i], '"') if 'JPEGThumbnail' in data: - print 'File has JPEG thumbnail' - print + print('File has JPEG thumbnail') + print() diff --git a/SimpleCV/Features/BOFFeatureExtractor.py b/SimpleCV/Features/BOFFeatureExtractor.py index 8cdacd2be..316e73439 100644 --- a/SimpleCV/Features/BOFFeatureExtractor.py +++ b/SimpleCV/Features/BOFFeatureExtractor.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import Image from SimpleCV.Features.FeatureExtractorBase import * @@ -71,18 +72,18 @@ def generate(self,imgdirs,numcodes=128,sz=(11,11),imgs_per_dir=50,img_layout=(8, infile = files[i] if verbose: print(path+" "+str(i)+" of "+str(imgs_per_dir)) - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) newFeat = self._getPatches(img,sz) if verbose: - print " Got " + str(len(newFeat)) + " features." + print(" Got " + str(len(newFeat)) + " features.") rawFeatures = np.vstack((rawFeatures,newFeat)) del img rawFeatures = rawFeatures[1:,:] # pop the fake value we put on the top if verbose: - print "==================================" - print "Got " + str(len(rawFeatures)) + " features " - print "Doing K-Means .... this will take a long time" + print("==================================") + print("Got " + str(len(rawFeatures)) + " features ") + print("Doing K-Means .... this will take a long time") self.mCodebook = self._makeCodebook(rawFeatures,self.mNumCodes) self.mCodebookImg = self._codebook2Img(self.mCodebook,self.mPatchSize,self.mNumCodes,self.mLayout,self.mPadding) self.mCodebookImg.save('codebook.png') diff --git a/SimpleCV/Features/BlobMaker.py b/SimpleCV/Features/BlobMaker.py index 32278c26d..b9bb176df 100644 --- a/SimpleCV/Features/BlobMaker.py +++ b/SimpleCV/Features/BlobMaker.py @@ -97,7 +97,7 @@ def extractFromBinary(self,binaryImg,colorImg, minsize = 5, maxsize = -1,appx_le # note to self # http://code.activestate.com/recipes/474088-tail-call-optimization-decorator/ retVal = self._extractFromBinary(seq,False,colorImg,minsize,maxsize,appx_level) - except RuntimeError,e: + except RuntimeError as e: logger.warning("You exceeded the recursion limit. This means you probably have too many blobs in your image. We suggest you do some morphological operations (erode/dilate) to reduce the number of blobs in your image. This function was designed to max out at about 5000 blobs per image.") except e: logger.warning("SimpleCV Find Blobs Failed - This could be an OpenCV python binding issue") diff --git a/SimpleCV/Features/FaceRecognizer.py b/SimpleCV/Features/FaceRecognizer.py index 6c4606c26..85e298ccb 100644 --- a/SimpleCV/Features/FaceRecognizer.py +++ b/SimpleCV/Features/FaceRecognizer.py @@ -27,7 +27,7 @@ def __init__(self): try: import cv2 self.model = cv2.createFisherFaceRecognizer() - except ImportError, AttributeError: + except ImportError as AttributeError: self.supported = False warnings.warn("Fisher Recognizer is supported by OpenCV >= 2.4.4") diff --git a/SimpleCV/Features/Features.py b/SimpleCV/Features/Features.py index 4899c6d67..842a992f4 100644 --- a/SimpleCV/Features/Features.py +++ b/SimpleCV/Features/Features.py @@ -44,7 +44,7 @@ def __getitem__(self,key): functions on sub-lists """ - if type(key) is types.SliceType: #Or can use 'try:' for speed + if type(key) is slice: #Or can use 'try:' for speed return FeatureSet(list.__getitem__(self, key)) else: return list.__getitem__(self,key) diff --git a/SimpleCV/Features/HaarCascade.py b/SimpleCV/Features/HaarCascade.py index 1e8d8ece6..98f845b29 100644 --- a/SimpleCV/Features/HaarCascade.py +++ b/SimpleCV/Features/HaarCascade.py @@ -34,7 +34,7 @@ def __init__(self, fname=None, name=None): self._mCascade = cv.Load(self._fhandle) - if HaarCascade._cache.has_key(self._fhandle): + if self._fhandle in HaarCascade._cache: self._mCascade = HaarCascade._cache[self._fhandle] return HaarCascade._cache[self._fhandle] = self._mCascade @@ -57,7 +57,7 @@ def load(self, fname=None, name = None): self._mCascade = cv.Load(self._fhandle) - if HaarCascade._cache.has_key(self._fhandle): + if self._fhandle in HaarCascade._cache: self._mCascade = HaarCascade._cache[fname] return HaarCascade._cache[self._fhandle] = self._mCascade diff --git a/SimpleCV/Features/PlayingCards/CardDataCollection.py b/SimpleCV/Features/PlayingCards/CardDataCollection.py index c598ad2c2..d0d3da661 100644 --- a/SimpleCV/Features/PlayingCards/CardDataCollection.py +++ b/SimpleCV/Features/PlayingCards/CardDataCollection.py @@ -1,7 +1,9 @@ +from __future__ import print_function +from __future__ import absolute_import from SimpleCV import Image, Display,Camera,Color import glob,os import pygame as pg -from CardUtil import SUITS, RANKS, MISC +from .CardUtil import SUITS, RANKS, MISC #SUITS = ('c', 'd', 'h', 's') #RANKS = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') #MISC = ( 'none','bad','joker') @@ -20,7 +22,7 @@ directory = path+s+"/"+r+"/" if not os.path.exists(directory): os.makedirs(directory) -print "Current Data: " + str(RANKS[rank_ptr])+str(SUITS[suit_ptr]) +print("Current Data: " + str(RANKS[rank_ptr])+str(SUITS[suit_ptr])) while not allDone : keys = disp.checkEvents() img = cam.getImage() @@ -31,7 +33,7 @@ count = len(files) fname = directory+RANKS[rank_ptr]+SUITS[suit_ptr]+"-"+str(count)+ext img.save(fname) - print "Saved: " + fname + print("Saved: " + fname) if( k == pg.K_n ): if rank_ptr == len(RANKS)-1 and suit_ptr == len(SUITS)-1: allDone = True @@ -39,9 +41,9 @@ rank_ptr = 0 suit_ptr = suit_ptr + 1 else: - print rank_ptr + print(rank_ptr) rank_ptr = rank_ptr + 1 - print "Current Data" + str(RANKS[rank_ptr])+str(SUITS[suit_ptr]) + print("Current Data" + str(RANKS[rank_ptr])+str(SUITS[suit_ptr])) img.drawLine((0,img.height/4),(img.width,img.height/4),color=Color.RED,thickness=3) img.drawLine((0,3*img.height/4),(img.width,3*img.height/4),color=Color.RED,thickness=3) diff --git a/SimpleCV/Features/PlayingCards/CardUtil.py b/SimpleCV/Features/PlayingCards/CardUtil.py index cd0a84fe9..7d50e7fc0 100644 --- a/SimpleCV/Features/PlayingCards/CardUtil.py +++ b/SimpleCV/Features/PlayingCards/CardUtil.py @@ -1,3 +1,4 @@ +from __future__ import print_function from glob import glob from SimpleCV import Image, ImageSet @@ -7,7 +8,7 @@ def GetSpecificCardData(suit,rank,path="./data/",label=True): fullpath = path+"/"+suit+"/"+rank+"/" - print fullpath + print(fullpath) iset = ImageSet(fullpath) if( label ): label_vals = [] diff --git a/SimpleCV/Features/PlayingCards/PlayingCardFactory.py b/SimpleCV/Features/PlayingCards/PlayingCardFactory.py index 59910f4f2..049e88bd6 100644 --- a/SimpleCV/Features/PlayingCards/PlayingCardFactory.py +++ b/SimpleCV/Features/PlayingCards/PlayingCardFactory.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import * from SimpleCV.Color import * @@ -68,7 +69,7 @@ def process(self,img): except: # this means we had an error somewhere # else maybe numpy - print "Generic Error." + print("Generic Error.") return None return FeatureSet([card]) diff --git a/SimpleCV/Features/PlayingCards/TestScript.py b/SimpleCV/Features/PlayingCards/TestScript.py index cef5f5298..6379c1db4 100644 --- a/SimpleCV/Features/PlayingCards/TestScript.py +++ b/SimpleCV/Features/PlayingCards/TestScript.py @@ -1,7 +1,9 @@ +from __future__ import print_function +from __future__ import absolute_import from SimpleCV import * #from FeatureUtils import * -from CardUtil import * -from PlayingCardFactory import * +from .CardUtil import * +from .PlayingCardFactory import * #import FeatureUtils import numpy as np @@ -31,7 +33,7 @@ def GetParallelSets(line_fs,parallel_thresh=25): pcf = PlayingCardFactory() data,labels = GetFullDataSet() -print len(data) +print(len(data)) datapoints = zip(data,labels) datapoints = datapoints[0:200] result = [] diff --git a/SimpleCV/Font.py b/SimpleCV/Font.py index e6c154db4..a4cbb50d7 100644 --- a/SimpleCV/Font.py +++ b/SimpleCV/Font.py @@ -1,3 +1,4 @@ +from __future__ import print_function # SimpleCV Font Library # # This library is used to add fonts to images @@ -65,7 +66,7 @@ def setFont(self, new_font = 'ubuntu'): Example: Font.setFont("/home/simplecv/my_font.ttf") """ if isinstance(new_font, basestring): - print "Please pass a string" + print("Please pass a string") return None if find(new_font, self._fonts): @@ -81,11 +82,11 @@ def setSize(self, size): """ Set the font point size. i.e. 16pt """ - print type(size) + print(type(size)) if type(size) == int: self._fontsize = size else: - print "please provide an integer" + print("please provide an integer") def getSize(self): """ @@ -109,4 +110,4 @@ def printFonts(self): """ for f in self._fonts: - print f + print(f) diff --git a/SimpleCV/ImageClass.py b/SimpleCV/ImageClass.py index 3207a927d..571f57c5e 100644 --- a/SimpleCV/ImageClass.py +++ b/SimpleCV/ImageClass.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from __future__ import absolute_import # Load required libraries from SimpleCV.base import * from SimpleCV.Color import * @@ -6,7 +8,7 @@ from numpy import uint8 import cv2 -from EXIF import * +from .EXIF import * if not init_options_handler.headless: import pygame as pg @@ -143,9 +145,9 @@ def download(self, tag=None, number=10, size='thumb'): from BeautifulSoup import BeautifulSoup except: - print "You need to install Beatutiul Soup to use this function" - print "to install you can use:" - print "easy_install beautifulsoup" + print("You need to install Beatutiul Soup to use this function") + print("to install you can use:") + print("easy_install beautifulsoup") return @@ -165,7 +167,7 @@ def download(self, tag=None, number=10, size='thumb'): elif size == 'large': size_param = '&tbs=isz:l' else: - print INVALID_SIZE_MSG + print(INVALID_SIZE_MSG) return None elif type(size) == tuple: @@ -173,7 +175,7 @@ def download(self, tag=None, number=10, size='thumb'): size_param = '&tbs=isz:ex,iszw:' + str(width) + ',iszh:' + str(height) else: - print INVALID_SIZE_MSG + print(INVALID_SIZE_MSG) return None # Used to extract imgurl parameter value from a URL @@ -213,7 +215,7 @@ def download(self, tag=None, number=10, size='thumb'): add_img = Image(dl_url, verbose=False) # Don't know a better way to check if the image was actually returned - if add_img.height <> 0 and add_img.width <> 0: + if add_img.height != 0 and add_img.width != 0: add_set.append(add_img) except: @@ -458,7 +460,7 @@ def save(self, destination=None, dt=0.2, verbose = False, displaytype=None): try: from IPython.core.display import Image as IPImage except ImportError: - print "You need IPython Notebooks to use this display mode" + print("You need IPython Notebooks to use this display mode") return from IPython.core import display as Idisplay for i in self: @@ -507,7 +509,7 @@ def showPaths(self): """ for i in self: - print i.filename + print(i.filename) def _read_gif(self, filename): """ read_gif(filename) @@ -757,7 +759,7 @@ def __getitem__(self,key): functions on sub-lists """ - if type(key) is types.SliceType: #Or can use 'try:' for speed + if type(key) is slice: #Or can use 'try:' for speed return ImageSet(list.__getitem__(self, key)) else: return list.__getitem__(self,key) @@ -1211,7 +1213,7 @@ def live(self): i.dl().text(txt, (10,i.height / 2), color=col) txt = "color: " + str(i.getPixel(d.mouseX,d.mouseY)) i.dl().text(txt, (10,(i.height / 2) + 10), color=col) - print "coord: (" + str(d.mouseX) + "," + str(d.mouseY) + "), color: " + str(i.getPixel(d.mouseX,d.mouseY)) + print("coord: (" + str(d.mouseX) + "," + str(d.mouseY) + "), color: " + str(i.getPixel(d.mouseX,d.mouseY))) if elapsed_time > 0 and elapsed_time < 5: @@ -1223,7 +1225,7 @@ def live(self): i.save(d) if d.mouseRight: - print "Closing Window" + print("Closing Window") d.done = True @@ -2249,7 +2251,7 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa self.save(self._tempFiles[-1][0]) return self._tempFiles[-1][0] else : - print "Path does not exist!" + print("Path does not exist!") else : if (filename) : @@ -2298,7 +2300,7 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa try: from IPython.core.display import Image as IPImage except ImportError: - print "You need IPython Notebooks to use this display mode" + print("You need IPython Notebooks to use this display mode") return from IPython.core import display as Idisplay @@ -2323,13 +2325,13 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa self.filehandle = fh #set the filename for future save operations self.filename = "" return 1 - except Exception, e: + except Exception as e: if mode.lower() != 'webp': raise e if verbose: - print self.filename + print(self.filename) if not mode.lower() == 'webp': return 1 @@ -2388,7 +2390,7 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa return 0 if verbose: - print self.filename + print(self.filename) if temp: return filename @@ -2483,7 +2485,7 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): try: import pycurl except ImportError: - print "PycURL Library not installed." + print("PycURL Library not installed.") return response = StringIO() @@ -2499,13 +2501,13 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): match = re.search(r'(\w+).*?(\w+).*?(http://[\w.]+/[\w.]+)', response.getvalue() , re.DOTALL) if match: if(verbose): - print "Imgur page: http://imgur.com/" + match.group(1) - print "Original image: " + match.group(3) - print "Delete page: http://imgur.com/delete/" + match.group(2) + print("Imgur page: http://imgur.com/" + match.group(1)) + print("Original image: " + match.group(3)) + print("Delete page: http://imgur.com/delete/" + match.group(2)) return [match.group(1),match.group(3),match.group(2)] else : if(verbose): - print "The API Key given is not valid" + print("The API Key given is not valid") return None elif (dest=='flickr'): @@ -2514,7 +2516,7 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): try : import flickrapi except ImportError: - print "Flickr API is not installed. Please install it from http://pypi.python.org/pypi/flickrapi" + print("Flickr API is not installed. Please install it from http://pypi.python.org/pypi/flickrapi") return False try : if (not(api_key==None and api_secret==None)): @@ -2527,16 +2529,16 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): self.flickr = flickrapi.FlickrAPI(temp_token[0],temp_token[1],cache=True) self.flickr.authenticate_console('write') except NameError : - print "API key and Secret key are not set." + print("API key and Secret key are not set.") return except : - print "The API Key and Secret Key are not valid" + print("The API Key and Secret Key are not valid") return False if (self.filename) : try : self.flickr.upload(self.filename,self.filehandle) except : - print "Uploading Failed !" + print("Uploading Failed !") return False else : tf = self.save(temp=True) @@ -2550,7 +2552,7 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): from dropbox import client, rest, session import webbrowser except ImportError: - print "Dropbox API is not installed. For more info refer : https://www.dropbox.com/developers/start/setup#python " + print("Dropbox API is not installed. For more info refer : https://www.dropbox.com/developers/start/setup#python ") return False try : if ( 'dropbox_token' not in globals() and api_key!=None and api_secret!=None ): @@ -2558,7 +2560,7 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) webbrowser.open(url) - print "Please visit this website and press the 'Allow' button, then hit 'Enter' here." + print("Please visit this website and press the 'Allow' button, then hit 'Enter' here.") raw_input() access_token = sess.obtain_access_token(request_token) dropbox_token = client.DropboxClient(sess) @@ -2568,14 +2570,14 @@ def upload(self,dest,api_key=None,api_secret=None, verbose = True): else : return None except : - print "The API Key and Secret Key are not valid" + print("The API Key and Secret Key are not valid") return False if (self.filename) : try : f = open(self.filename) dropbox_token.put_file('/SimpleCVImages/'+os.path.split(self.filename)[-1], f) except : - print "Uploading Failed !" + print("Uploading Failed !") return False else : tf = self.save(temp=True) @@ -4572,11 +4574,11 @@ def huePeaks(self, bins = 179): #perform some checks if length != len(x_axis): - raise ValueError, "Input vectors y_axis and x_axis must have same length" + raise ValueError("Input vectors y_axis and x_axis must have same length") if lookahead < 1: - raise ValueError, "Lookahead must be above '1' in value" + raise ValueError("Lookahead must be above '1' in value") if not (np.isscalar(delta) and delta >= 0): - raise ValueError, "delta must be a positive number" + raise ValueError("delta must be a positive number") #needs to be a numpy array y_axis = np.asarray(y_axis) @@ -5919,7 +5921,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): if(y == None or w == None or h == None): - print "Please provide an x, y, width, height to function" + print("Please provide an x, y, width, height to function") if( w <= 0 or h <= 0 ): logger.warning("Can't do a negative crop!") @@ -6204,7 +6206,7 @@ def show(self, type = 'window'): self.save(d) return d else: - print "Unknown type to show" + print("Unknown type to show") def _surface2Image(self,surface): imgarray = pg.surfarray.array3d(surface) @@ -6392,7 +6394,7 @@ def removeDrawingLayer(self, index = -1): try: return self._mLayers.pop(index) except IndexError: - print 'Not a valid index or No layers to remove!' + print('Not a valid index or No layers to remove!') def getDrawingLayer(self, index = -1): @@ -6444,7 +6446,7 @@ def getDrawingLayer(self, index = -1): try: return self._mLayers[index] except IndexError: - print 'Not a valid index' + print('Not a valid index') def dl(self, index = -1): @@ -7138,7 +7140,9 @@ def _rectOverlapROIs(self,top, bottom, pos): br = (pos[0]+top[0],pos[1]+top[1]) bl = (pos[0],pos[1]+top[1]) # do an overlap test to weed out corner cases and errors - def inBounds((w,h), (x,y)): + def inBounds(xxx_todo_changeme, xxx_todo_changeme1): + (w,h) = xxx_todo_changeme + (x,y) = xxx_todo_changeme1 retVal = True if( x < 0 or y < 0 or x > w or y > h): retVal = False @@ -10906,7 +10910,7 @@ def applyUnsharpMask(self,boost=1,dia=400,grayscale=False): """ if boost < 0: - print "boost >= 1" + print("boost >= 1") return None lpIm = self.applyGaussianFilter(dia=dia,grayscale=grayscale,highpass=False) @@ -10933,7 +10937,7 @@ def listHaarFeatures(self): features_directory = os.path.join(LAUNCH_PATH, 'Features','HaarCascades') features = os.listdir(features_directory) - print features + print(features) def _CopyAvg(self, src, dst,roi, levels, levels_f, mode): ''' @@ -11183,7 +11187,7 @@ def fillHoles(self): for cnt in contour: cv2.drawContours(des,[cnt],0,255,-1) - print 'yep' + print('yep') gray = cv2.bitwise_not(des) return gray @@ -12079,11 +12083,11 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): points. """ if not ts and not img: - print "Invalid Input. Must provide FeatureSet or Image" + print("Invalid Input. Must provide FeatureSet or Image") return None if not ts and not bb: - print "Invalid Input. Must provide Bounding Box with Image" + print("Invalid Input. Must provide Bounding Box with Image") return None if not ts: @@ -12094,7 +12098,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): try: import cv2 except ImportError: - print "Tracking is available for OpenCV >= 2.3" + print("Tracking is available for OpenCV >= 2.3") return None if type(img) == list: @@ -12436,7 +12440,7 @@ def getLineScan(self,x=None,y=None,pt1=None,pt2=None,channel = -1): try: img = self.getNumpy()[:,:,channel] except IndexError: - print 'Channel missing!' + print('Channel missing!') return None retVal = None @@ -12529,7 +12533,7 @@ def setLineScan(self, linescan,x=None,y=None,pt1=None,pt2=None,channel = -1): try: img = np.copy(self.getNumpy()[:,:,channel]) except IndexError: - print 'Channel missing!' + print('Channel missing!') return None if( x is None and y is None and pt1 is None and pt2 is None): @@ -12643,7 +12647,7 @@ def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel try: img = np.copy(self.getNumpy()[:,:,linescan.channel]) except IndexError: - print 'Channel missing!' + print('Channel missing!') return None if linescan.row is not None: @@ -12717,7 +12721,7 @@ def getPixelsOnLine(self,pt1,pt2): return retVal - def bresenham_line(self, (x,y), (x2,y2)): + def bresenham_line(self, xxx_todo_changeme2, xxx_todo_changeme3): """ Brensenham line algorithm @@ -12725,6 +12729,8 @@ def bresenham_line(self, (x,y), (x2,y2)): This is just a helper method """ + (x,y) = xxx_todo_changeme2 + (x2,y2) = xxx_todo_changeme3 if (not 0 <= x <= self.width-1 or not 0 <= y <= self.height-1 or not 0 <= x2 <= self.width-1 or not 0 <= y2 <= self.height-1): l = Line(self, ((x, y), (x2, y2))).cropToImageEdges() @@ -12894,7 +12900,7 @@ def findGridLines(self): gridIndex = self.getDrawingLayer(self._gridLayer[0]) if self._gridLayer[0]==-1: - print "Cannot find grid on the image, Try adding a grid first" + print("Cannot find grid on the image, Try adding a grid first") lineFS = FeatureSet() try: @@ -12939,12 +12945,12 @@ def logicalAND(self, img, grayscale=True): """ if not self.size() == img.size(): - print "Both images must have same sizes" + print("Both images must have same sizes") return None try: import cv2 except ImportError: - print "This function is available for OpenCV >= 2.3" + print("This function is available for OpenCV >= 2.3") if grayscale: retval = cv2.bitwise_and(self.getGrayNumpyCv2(), img.getGrayNumpyCv2()) else: @@ -12975,12 +12981,12 @@ def logicalNAND(self, img, grayscale=True): """ if not self.size() == img.size(): - print "Both images must have same sizes" + print("Both images must have same sizes") return None try: import cv2 except ImportError: - print "This function is available for OpenCV >= 2.3" + print("This function is available for OpenCV >= 2.3") if grayscale: retval = cv2.bitwise_and(self.getGrayNumpyCv2(), img.getGrayNumpyCv2()) else: @@ -13012,12 +13018,12 @@ def logicalOR(self, img, grayscale=True): """ if not self.size() == img.size(): - print "Both images must have same sizes" + print("Both images must have same sizes") return None try: import cv2 except ImportError: - print "This function is available for OpenCV >= 2.3" + print("This function is available for OpenCV >= 2.3") if grayscale: retval = cv2.bitwise_or(self.getGrayNumpyCv2(), img.getGrayNumpyCv2()) else: @@ -13048,12 +13054,12 @@ def logicalXOR(self, img, grayscale=True): """ if not self.size() == img.size(): - print "Both images must have same sizes" + print("Both images must have same sizes") return None try: import cv2 except ImportError: - print "This function is available for OpenCV >= 2.3" + print("This function is available for OpenCV >= 2.3") if grayscale: retval = cv2.bitwise_xor(self.getGrayNumpyCv2(), img.getGrayNumpyCv2()) else: @@ -13742,11 +13748,11 @@ def grayPeaks(self, bins = 255, delta = 0, lookahead = 15): #perform some checks if length != len(x_axis): - raise ValueError, "Input vectors y_axis and x_axis must have same length" + raise ValueError("Input vectors y_axis and x_axis must have same length") if lookahead < 1: - raise ValueError, "Lookahead must be above '1' in value" + raise ValueError("Lookahead must be above '1' in value") if not (np.isscalar(delta) and delta >= 0): - raise ValueError, "delta must be a positive number" + raise ValueError("delta must be a positive number") #needs to be a numpy array y_axis = np.asarray(y_axis) @@ -13835,7 +13841,7 @@ def tvDenoising(self, gray=False, weight=50, eps=0.0002, max_iter=200, resize=1) img = self.copy() if resize <= 0: - print 'Enter a valid resize value' + print('Enter a valid resize value') return None if resize != 1: @@ -14140,7 +14146,7 @@ def edgeSnap(self,pointList,step = 1): #checking that all values are 0 and 255 if( c1 + c2 != imgArray.size): - raise ValueError,"Image must be binary" + raise ValueError("Image must be binary") if(len(pointList) < 2 ): return None diff --git a/SimpleCV/LineScan.py b/SimpleCV/LineScan.py index 5fd84fd5a..242eec29d 100644 --- a/SimpleCV/LineScan.py +++ b/SimpleCV/LineScan.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * import scipy.signal as sps @@ -76,7 +77,7 @@ def __getitem__(self,key): functions on sub-lists """ - if type(key) is types.SliceType: #Or can use 'try:' for speed + if type(key) is slice: #Or can use 'try:' for speed return LineScan(list.__getitem__(self, key)) else: return list.__getitem__(self,key) @@ -92,7 +93,7 @@ def __sub__(self,other): if len(self) == len(other): retVal = LineScan(map(operator.sub,self,other)) else: - print 'Size mismatch' + print('Size mismatch') return None retVal._update(self) return retVal @@ -102,7 +103,7 @@ def __add__(self,other): if len(self) == len(other): retVal = LineScan(map(operator.add,self,other)) else: - print 'Size mismatch' + print('Size mismatch') return None retVal._update(self) return retVal @@ -112,7 +113,7 @@ def __mul__(self,other): if len(self) == len(other): retVal = LineScan(map(operator.mul,self,other)) else: - print 'Size mismatch' + print('Size mismatch') return None retVal._update(self) @@ -124,10 +125,10 @@ def __div__(self,other): try: retVal = LineScan(map(operator.div,self,other)) except ZeroDivisionError: - print 'Second LineScan contains zeros' + print('Second LineScan contains zeros') return None else: - print 'Size mismatch' + print('Size mismatch') return None retVal._update(self) @@ -1083,7 +1084,7 @@ def medianFilter(self, kernel_size=5): return None if kernel_size % 2 == 0: kernel_size-=1 - print "Kernel Size should be odd. New kernel size =" , (kernel_size) + print("Kernel Size should be odd. New kernel size =" , (kernel_size)) medfilt_array = medfilt(np.asarray(self[:]), kernel_size) retVal = LineScan(medfilt_array.astype("uint8").tolist(), image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2, x=self.col, y=self.row) diff --git a/SimpleCV/MachineLearning/KNNClassifier.py b/SimpleCV/MachineLearning/KNNClassifier.py index f250009c3..f257325af 100644 --- a/SimpleCV/MachineLearning/KNNClassifier.py +++ b/SimpleCV/MachineLearning/KNNClassifier.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet from SimpleCV.DrawingLayer import * @@ -150,7 +151,7 @@ def _trainPath(self,path,className,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -179,7 +180,7 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) @@ -255,7 +256,7 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) c = self.mClassifier(self.mDataSetOrange[i]) test = self.mDataSetOrange[i].getclass() if verbose: - print "original", test, "classified as", c + print("original", test, "classified as", c) if(test==c): correct = correct + 1 else: @@ -273,9 +274,9 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions))) return [good, bad, confusion] @@ -338,9 +339,9 @@ def test(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True): print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions))) return [good, bad, confusion] @@ -358,7 +359,7 @@ def _testPath(self,path,className,dataset,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -396,7 +397,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) diff --git a/SimpleCV/MachineLearning/MLTestSuite.py b/SimpleCV/MachineLearning/MLTestSuite.py index 6ff8bddea..1621862c1 100644 --- a/SimpleCV/MachineLearning/MLTestSuite.py +++ b/SimpleCV/MachineLearning/MLTestSuite.py @@ -1,18 +1,19 @@ +from __future__ import print_function from SimpleCV import * -print "" -print "This program runs a list of test for machine learning on" -print "the SimpleCV library. Not all scores will be high, this" -print "is just to ensure that the libraries are functioning correctly" -print "on your system" -print "" -print "***** WARNING *****" -print "This program is about to download a large data set to run it's test" +print("") +print("This program runs a list of test for machine learning on") +print("the SimpleCV library. Not all scores will be high, this") +print("is just to ensure that the libraries are functioning correctly") +print("on your system") +print("") +print("***** WARNING *****") +print("This program is about to download a large data set to run it's test") inp = raw_input("Do you want to continue [Y/n]") if not (inp == "" or inp.lower() == "y"): - print "Exiting the program" + print("Exiting the program") sys.exit() @@ -295,5 +296,5 @@ print(files[i]+' -> '+cname) -print "" -print "All the machine learning test have ran correctly" +print("") +print("All the machine learning test have ran correctly") diff --git a/SimpleCV/MachineLearning/NaiveBayesClassifier.py b/SimpleCV/MachineLearning/NaiveBayesClassifier.py index ae821d553..5d3e33a60 100644 --- a/SimpleCV/MachineLearning/NaiveBayesClassifier.py +++ b/SimpleCV/MachineLearning/NaiveBayesClassifier.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet from SimpleCV.DrawingLayer import * @@ -117,7 +118,7 @@ def _trainPath(self,path,className,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -146,7 +147,7 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) @@ -218,7 +219,7 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) c = self.mClassifier(self.mDataSetOrange[i]) test = self.mDataSetOrange[i].getclass() if verbose: - print "original", test, "classified as", c + print("original", test, "classified as", c) if(test==c): correct = correct + 1 else: @@ -236,9 +237,9 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions))) return [good, bad, confusion] @@ -302,9 +303,9 @@ def test(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True): print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions))) return [good, bad, confusion] @@ -322,7 +323,7 @@ def _testPath(self,path,className,dataset,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -360,7 +361,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) diff --git a/SimpleCV/MachineLearning/SVMClassifier.py b/SimpleCV/MachineLearning/SVMClassifier.py index 447034ead..e14ec181e 100644 --- a/SimpleCV/MachineLearning/SVMClassifier.py +++ b/SimpleCV/MachineLearning/SVMClassifier.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet from SimpleCV.DrawingLayer import * @@ -178,7 +179,7 @@ def _trainPath(self,path,className,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -207,7 +208,7 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) @@ -279,7 +280,7 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) c = self.mClassifier(self.mDataSetOrange[i]) test = self.mDataSetOrange[i].getclass() if verbose: - print "original", test, "classified as", c + print("original", test, "classified as", c) if(test==c): correct = correct + 1 else: @@ -297,7 +298,7 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print confusion + print(confusion) #print "\t"+"\t".join(classes) #for className, classConfusions in zip(classes, confusion): # print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) @@ -364,9 +365,9 @@ def test(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True): print("Correct: "+str(good)) print("Incorrect: "+str(bad)) classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple(classConfusions))) return [good, bad, confusion] @@ -384,7 +385,7 @@ def _testPath(self,path,className,dataset,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -422,7 +423,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) diff --git a/SimpleCV/MachineLearning/ShapeContextClassifier.py b/SimpleCV/MachineLearning/ShapeContextClassifier.py index 8f89921d4..9f9d0b2b5 100644 --- a/SimpleCV/MachineLearning/ShapeContextClassifier.py +++ b/SimpleCV/MachineLearning/ShapeContextClassifier.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.Features.Features import Feature, FeatureSet from SimpleCV.Color import Color @@ -25,7 +26,7 @@ def __init__(self,images,labels): try: from sklearn import neighbors except: - print "Need scikits learn installed" + print("Need scikits learn installed") self.imgMap = {} self.ptMap = {} @@ -37,7 +38,7 @@ def __init__(self,images,labels): import warnings warnings.simplefilter("ignore") for i in range(0,len(images)): - print "precomputing " + images[i].filename + print("precomputing " + images[i].filename) self.imgMap[labels[i]] = images[i] pts,desc,count = self._image2FeatureVector(images[i]) @@ -87,7 +88,7 @@ def _doMatching(self,model_name,test_scd): temp = np.sqrt(np.sum(((sample-scd)**2))) #temp = 0.5*np.sum((sample-scd)**2)/np.sum((sample+scd)) if( math.isnan(temp) ): - temp = sys.maxint + temp = sys.maxsize distance.append(temp) return [otherIdx,distance] @@ -137,7 +138,7 @@ def classify(self,image, blobFilter=True): and match quality. """ points,descriptors,count,matchDict,matchStd = self._buildMatchDict(image, blobFilter) - best = sys.maxint + best = sys.maxsize best_name = "No Match" for k,v in matchDict.items(): if ( v < best ): diff --git a/SimpleCV/MachineLearning/TemporalColorTracker.py b/SimpleCV/MachineLearning/TemporalColorTracker.py index 4f5f5326a..67d4f28e5 100644 --- a/SimpleCV/MachineLearning/TemporalColorTracker.py +++ b/SimpleCV/MachineLearning/TemporalColorTracker.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import Image, ImageSet, Camera, VirtualCamera, ROI, Color, LineScan import numpy as np import scipy.signal as sps @@ -109,17 +110,17 @@ def train(self,src,roi=None, extractor=None, doCorr=False, maxFrames=1000, self._buildSignalProfile() if verbose: for key in self.data.keys(): - print 30*'-' - print "Channel: {0}".format(key) - print "Data Points: {0}".format(len(self.data[key])) - print "Steady State: {0}+/-{1}".format(self._steadyState[key][0],self._steadyState[key][1]) - print "Peaks: {0}".format(self.peaks[key]) - print "Valleys: {0}".format(self.valleys[key]) - print "Use Peaks: {0}".format(self.doPeaks[key]) - print 30*'-' - print "BEST SIGNAL: {0}".format(self._bestKey) - print "BEST WINDOW: {0}".format(self._window) - print "BEST CUTOFF: {0}".format(self._cutoff) + print(30*'-') + print("Channel: {0}".format(key)) + print("Data Points: {0}".format(len(self.data[key]))) + print("Steady State: {0}+/-{1}".format(self._steadyState[key][0],self._steadyState[key][1])) + print("Peaks: {0}".format(self.peaks[key])) + print("Valleys: {0}".format(self.valleys[key])) + print("Use Peaks: {0}".format(self.doPeaks[key])) + print(30*'-') + print("BEST SIGNAL: {0}".format(self._bestKey)) + print("BEST WINDOW: {0}".format(self._window)) + print("BEST CUTOFF: {0}".format(self._cutoff)) def _getDataFromImg(self,img): """ @@ -150,7 +151,7 @@ def _extract(self,src,maxFrames,verbose): img = src.getImage() count = count + 1 if( verbose ): - print "Got Frame {0}".format(count) + print("Got Frame {0}".format(count)) if( isinstance(src,Camera) ): time.sleep(0.05) # let the camera sleep if( img is None ): @@ -233,7 +234,7 @@ def _extractSignalInfo(self,forceChannel): # Now we know which signal has the most spread # and what direction we are looking for. if( forceChannel is not None ): - if(self.data.has_key(forceChannel)): + if(forceChannel in self.data): self._bestKey = forceChannel else: raise Exception('That is not a valid data channel') @@ -299,7 +300,7 @@ def _doCorr(self): self._template = sig / len(self.corrTemplates) self._template /= np.max(self._template) corrVals = [np.correlate(peak/np.max(peak),self._template) for peak in self.corrTemplates] - print corrVals + print(corrVals) self.corrThresh = (np.mean(corrVals),np.std(corrVals)) def _getBestValue(self,img): diff --git a/SimpleCV/MachineLearning/TreeClassifier.py b/SimpleCV/MachineLearning/TreeClassifier.py index 9cec21f57..a4d2030b8 100644 --- a/SimpleCV/MachineLearning/TreeClassifier.py +++ b/SimpleCV/MachineLearning/TreeClassifier.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet from SimpleCV.DrawingLayer import * @@ -187,7 +188,7 @@ def _trainPath(self,path,className,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -216,7 +217,7 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) @@ -305,7 +306,7 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) c = self.mClassifier(self.mDataSetOrange[i]) test = self.mDataSetOrange[i].getclass() if verbose: - print "original", test, "classified as", c + print("original", test, "classified as", c) if(test==c): correct = correct + 1 else: @@ -324,9 +325,9 @@ def train(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True) print("Incorrect: "+str(bad)) if( confusion != 0 ): classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple( classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple( classConfusions))) if(self.mFlavor == 0): self._PrintTree(self.mClassifier) @@ -395,9 +396,9 @@ def test(self,images,classNames,disp=None,subset=-1,savedata=None,verbose=True): print("Incorrect: "+str(bad)) if( confusion != 0 ): classes = self.mDataSetOrange.domain.classVar.values - print "\t"+"\t".join(classes) + print("\t"+"\t".join(classes)) for className, classConfusions in zip(classes, confusion): - print ("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple( classConfusions)) + print(("%s" + ("\t%i" * len(classes))) % ((className, ) + tuple( classConfusions))) return [good, bad, confusion] def _testPath(self,path,className,dataset,subset,disp,verbose): @@ -414,7 +415,7 @@ def _testPath(self,path,className,dataset,subset,disp,verbose): for i in range(nfiles): infile = files[i] if verbose: - print "Opening file: " + infile + print("Opening file: " + infile) img = Image(infile) featureVector = [] for extractor in self.mFeatureExtractors: @@ -452,7 +453,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): imageset = imageset[0:subset] for img in imageset: if verbose: - print "Opening file: " + img.filename + print("Opening file: " + img.filename) featureVector = [] for extractor in self.mFeatureExtractors: feats = extractor.extract(img) @@ -499,22 +500,22 @@ def _PrintTree(self,x): elif type(x) == orange.TreeNode: self._PrintTree0(x, 0) else: - raise TypeError, "invalid parameter" + raise TypeError("invalid parameter") def _PrintTree0(self,node,level): #adapted from the orange documentation if not node: - print " "*level + "" + print(" "*level + "") return if node.branchSelector: nodeDesc = node.branchSelector.classVar.name nodeCont = node.distribution - print "\n" + " "*level + "%s (%s)" % (nodeDesc, nodeCont), + print("\n" + " "*level + "%s (%s)" % (nodeDesc, nodeCont), end=' ') for i in range(len(node.branches)): - print "\n" + " "*level + ": %s" % node.branchDescriptions[i], + print("\n" + " "*level + ": %s" % node.branchDescriptions[i], end=' ') self._PrintTree0(node.branches[i], level+1) else: nodeCont = node.distribution majorClass = node.nodeClassifier.defaultValue - print "--> %s (%s) " % (majorClass, nodeCont) + print("--> %s (%s) " % (majorClass, nodeCont)) diff --git a/SimpleCV/MachineLearning/TurkingModule.py b/SimpleCV/MachineLearning/TurkingModule.py index 906ad63f9..df5f0a671 100644 --- a/SimpleCV/MachineLearning/TurkingModule.py +++ b/SimpleCV/MachineLearning/TurkingModule.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import Display, Image, Color, ImageSet import os import os.path as osp @@ -67,7 +68,7 @@ def __init__(self,source_paths,out_path,classList,key_bindings,preprocess=None, self.out_path = out_path self.keyMap = {} if( len(classList)!=len(key_bindings)): - print "Must have a key for each class." + print("Must have a key for each class.") raise Exception("Must have a key for each class.") for key,cls in zip(key_bindings,classList): self.keyMap[key] = cls @@ -92,9 +93,9 @@ def fakePostProcess(img): self.srcImgs = source_path else: for sp in source_paths: - print "Loading " + sp + print("Loading " + sp) imgSet = ImageSet(sp) - print "Loaded " + str(len(imgSet)) + print("Loaded " + str(len(imgSet))) self.srcImgs += imgSet if( not osp.exists(out_path) ): @@ -114,7 +115,7 @@ def fakePostProcess(img): def _saveIt(self,img,classType): img.clearLayers() path = self.out_path + classType + "/" + classType+str(self.countMap[classType])+".png" - print "Saving: " + path + print("Saving: " + path) img = self.postProcess(img) self.classMap[classType].append(img) img.save(path) @@ -200,7 +201,7 @@ def turk(self,saveOriginal=False,disp_size=(800,600),showKeys=True,font_size=16, disp = Display(disp_size) bail = False for img in self.srcImgs: - print img.filename + print(img.filename) samples = self.preProcess(img) for sample in samples: if( showKeys ): diff --git a/SimpleCV/MachineLearning/TurkingModuleExample.py b/SimpleCV/MachineLearning/TurkingModuleExample.py index 480e6bd23..ab55e0ccc 100644 --- a/SimpleCV/MachineLearning/TurkingModuleExample.py +++ b/SimpleCV/MachineLearning/TurkingModuleExample.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import Image, Features, Color, ImageSet, Display from SimpleCV.MachineLearning import TurkingModule # This example shows how to use the turking module. @@ -30,11 +31,11 @@ def postprocess(img): turker.turk(font_size=16, color = Color.BLUE, spacing=18) # show what we got -print "="*30 -print "TURKING DONE!" +print("="*30) +print("TURKING DONE!") for c in classes: - print "="*30 - print "Showing " + c + print("="*30) + print("Showing " + c) iset = turker.getClass(c) iset.show(0.1) diff --git a/SimpleCV/MachineLearning/query_imgs/flickrapi2.py b/SimpleCV/MachineLearning/query_imgs/flickrapi2.py index efe93c46d..2d1eacb95 100644 --- a/SimpleCV/MachineLearning/query_imgs/flickrapi2.py +++ b/SimpleCV/MachineLearning/query_imgs/flickrapi2.py @@ -1,534 +1,535 @@ -#!/usr/bin/python -# -# Flickr API implementation -# -# Inspired largely by Michele Campeotto's flickrclient and Aaron Swartz' -# xmltramp... but I wanted to get a better idea of how python worked in -# those regards, so I mostly worked those components out for myself. -# -# http://micampe.it/things/flickrclient -# http://www.aaronsw.com/2002/xmltramp/ -# -# Release 1: initial release -# Release 2: added upload functionality -# Release 3: code cleanup, convert to doc strings -# Release 4: better permission support -# Release 5: converted into fuller-featured "flickrapi" -# Release 6: fix upload sig bug (thanks Deepak Jois), encode test output -# Release 7: fix path construction, Manish Rai Jain's improvements, exceptions -# Release 8: change API endpoint to "api.flickr.com" -# -# Work by (or inspired by) Manish Rai Jain : -# -# improved error reporting, proper multipart MIME boundary creation, -# use of urllib2 to allow uploads through a proxy, upload accepts -# raw data as well as a filename -# -# Copyright 2005 Brian "Beej Jorgensen" Hall -# -# This work is licensed under the Creative Commons -# Attribution License. To view a copy of this license, -# visit http://creativecommons.org/licenses/by/2.5/ or send -# a letter to Creative Commons, 543 Howard Street, 5th -# Floor, San Francisco, California, 94105, USA. -# -# This license says that I must be credited for any derivative works. -# You do not need to credit me to simply use the FlickrAPI classes in -# your Python scripts--you only need to credit me if you're taking this -# FlickrAPI class and modifying it or redistributing it. -# -# Previous versions of this API were granted to the public domain. -# You're free to use those as you please. -# -# Beej Jorgensen, Maintainer, November 2005 -# beej@beej.us -# - -import sys -import md5 -import string -import urllib -import urllib2 -import mimetools -import httplib -import os.path -import xml.dom.minidom - -######################################################################## -# Exceptions -######################################################################## - -class UploadException(Exception): - pass - -######################################################################## -# XML functionality -######################################################################## - -#----------------------------------------------------------------------- -class XMLNode: - """XMLNode -- generic class for holding an XML node - - xmlStr = \"\"\" - Name0 - Name1 - \"\"\" - - f = XMLNode.parseXML(xmlStr) - - print f.elementName # xml - print f['foo'] # 32 - print f.name # [, ] - print f.name[0].elementName # name - print f.name[0]["bar"] # 10 - print f.name[0].elementText # Name0 - print f.name[1].elementName # name - print f.name[1]["bar"] # 11 - print f.name[1]["baz"] # 12 - - """ - - def __init__(self): - """Construct an empty XML node.""" - self.elementName="" - self.elementText="" - self.attrib={} - self.xml="" - - def __setitem__(self, key, item): - """Store a node's attribute in the attrib hash.""" - self.attrib[key] = item - - def __getitem__(self, key): - """Retrieve a node's attribute from the attrib hash.""" - try: - return self.attrib[key] - except: - return "null" - #----------------------------------------------------------------------- - #@classmethod - def parseXML(cls, xmlStr, storeXML=False): - """Convert an XML string into a nice instance tree of XMLNodes. - - xmlStr -- the XML to parse - storeXML -- if True, stores the XML string in the root XMLNode.xml - - """ - - def __parseXMLElement(element, thisNode): - """Recursive call to process this XMLNode.""" - thisNode.elementName = element.nodeName - - #print element.nodeName - - # add element attributes as attributes to this node - for i in range(element.attributes.length): - an = element.attributes.item(i) - thisNode[an.name] = an.nodeValue - - for a in element.childNodes: - if a.nodeType == xml.dom.Node.ELEMENT_NODE: - - child = XMLNode() - try: - list = getattr(thisNode, a.nodeName) - except AttributeError: - setattr(thisNode, a.nodeName, []) - - # add the child node as an attrib to this node - list = getattr(thisNode, a.nodeName); - #print "appending child: %s to %s" % (a.nodeName, thisNode.elementName) - list.append(child); - - __parseXMLElement(a, child) - - elif a.nodeType == xml.dom.Node.TEXT_NODE: - thisNode.elementText += a.nodeValue - - return thisNode - - dom = xml.dom.minidom.parseString(xmlStr) - - # get the root - rootNode = XMLNode() - if storeXML: rootNode.xml = xmlStr - - return __parseXMLElement(dom.firstChild, rootNode) - parseXML = classmethod(parseXML) - -######################################################################## -# Flickr functionality -######################################################################## - -#----------------------------------------------------------------------- -class FlickrAPI: - """Encapsulated flickr functionality. - - Example usage: - - flickr = FlickrAPI(flickrAPIKey, flickrSecret) - rsp = flickr.auth_checkToken(api_key=flickrAPIKey, auth_token=token) - - """ - flickrHost = "api.flickr.com" - flickrRESTForm = "/services/rest/" - flickrAuthForm = "/services/auth/" - flickrUploadForm = "/services/upload/" - - #------------------------------------------------------------------- - def __init__(self, apiKey, secret): - """Construct a new FlickrAPI instance for a given API key and secret.""" - self.apiKey = apiKey - self.secret = secret - - self.__handlerCache={} - - #------------------------------------------------------------------- - def __sign(self, data): - """Calculate the flickr signature for a set of params. - - data -- a hash of all the params and values to be hashed, e.g. - {"api_key":"AAAA", "auth_token":"TTTT"} - - """ - dataName = self.secret - keys = data.keys() - keys.sort() - for a in keys: dataName += (a + data[a]) - #print dataName - hash = md5.new() - hash.update(dataName) - return hash.hexdigest() - - #------------------------------------------------------------------- - def __getattr__(self, method, **arg): - """Handle all the flickr API calls. - - This is Michele Campeotto's cleverness, wherein he writes a - general handler for methods not defined, and assumes they are - flickr methods. He then converts them to a form to be passed as - the method= parameter, and goes from there. - - http://micampe.it/things/flickrclient - - My variant is the same basic thing, except it tracks if it has - already created a handler for a specific call or not. - - example usage: - - flickr.auth_getFrob(api_key="AAAAAA") - rsp = flickr.favorites_getList(api_key=flickrAPIKey, \\ - auth_token=token) - - """ - - if not self.__handlerCache.has_key(method): - def handler(_self = self, _method = method, **arg): - _method = "flickr." + _method.replace("_", ".") - url = "http://" + FlickrAPI.flickrHost + \ - FlickrAPI.flickrRESTForm - arg["method"] = _method - postData = urllib.urlencode(arg) + "&api_sig=" + \ - _self.__sign(arg) - #print "--url---------------------------------------------" - #print url - #print "--postData----------------------------------------" - #print postData - f = urllib.urlopen(url, postData) - data = f.read() - #print "--response----------------------------------------" - #print data - f.close() - return XMLNode.parseXML(data, True) - - self.__handlerCache[method] = handler; - - return self.__handlerCache[method] - - #------------------------------------------------------------------- - def __getAuthURL(self, perms, frob): - """Return the authorization URL to get a token. - - This is the URL the app will launch a browser toward if it - needs a new token. - - perms -- "read", "write", or "delete" - frob -- picked up from an earlier call to FlickrAPI.auth_getFrob() - - """ - - data = {"api_key": self.apiKey, "frob": frob, "perms": perms} - data["api_sig"] = self.__sign(data) - return "http://%s%s?%s" % (FlickrAPI.flickrHost, \ - FlickrAPI.flickrAuthForm, urllib.urlencode(data)) - - #------------------------------------------------------------------- - def upload(self, filename=None, jpegData=None, **arg): - """Upload a file to flickr. - - Be extra careful you spell the parameters correctly, or you will - get a rather cryptic "Invalid Signature" error on the upload! - - Supported parameters: - - One of filename or jpegData must be specified by name when - calling this method: - - filename -- name of a file to upload - jpegData -- array of jpeg data to upload - - api_key - auth_token - title - description - tags -- space-delimited list of tags, "tag1 tag2 tag3" - is_public -- "1" or "0" - is_friend -- "1" or "0" - is_family -- "1" or "0" - - """ - - if filename == None and jpegData == None or \ - filename != None and jpegData != None: - - raise UploadException("filename OR jpegData must be specified") - - # verify key names - for a in arg.keys(): - if a != "api_key" and a != "auth_token" and a != "title" and \ - a != "description" and a != "tags" and a != "is_public" and \ - a != "is_friend" and a != "is_family": - - sys.stderr.write("FlickrAPI: warning: unknown parameter " \ - "\"%s\" sent to FlickrAPI.upload\n" % (a)) - - arg["api_sig"] = self.__sign(arg) - url = "http://" + FlickrAPI.flickrHost + FlickrAPI.flickrUploadForm - - # construct POST data - boundary = mimetools.choose_boundary() - body = "" - - # required params - for a in ('api_key', 'auth_token', 'api_sig'): - body += "--%s\r\n" % (boundary) - body += "Content-Disposition: form-data; name=\""+a+"\"\r\n\r\n" - body += "%s\r\n" % (arg[a]) - - # optional params - for a in ('title', 'description', 'tags', 'is_public', \ - 'is_friend', 'is_family'): - - if arg.has_key(a): - body += "--%s\r\n" % (boundary) - body += "Content-Disposition: form-data; name=\""+a+"\"\r\n\r\n" - body += "%s\r\n" % (arg[a]) - - body += "--%s\r\n" % (boundary) - body += "Content-Disposition: form-data; name=\"photo\";" - body += " filename=\"%s\"\r\n" % filename - body += "Content-Type: image/jpeg\r\n\r\n" - - #print body - - if filename != None: - fp = file(filename, "rb") - data = fp.read() - fp.close() - else: - data = jpegData - - postData = body.encode("utf_8") + data + \ - ("--%s--" % (boundary)).encode("utf_8") - - request = urllib2.Request(url) - request.add_data(postData) - request.add_header("Content-Type", \ - "multipart/form-data; boundary=%s" % boundary) - response = urllib2.urlopen(request) - rspXML = response.read() - - return XMLNode.parseXML(rspXML) - - - #----------------------------------------------------------------------- - #@classmethod - def testFailure(cls, rsp, exit=True): - """Exit app if the rsp XMLNode indicates failure.""" - if rsp['stat'] == "fail": - sys.stderr.write("%s\n" % (cls.getPrintableError(rsp))) - if exit: sys.exit(1) - testFailure = classmethod(testFailure) - - #----------------------------------------------------------------------- - #@classmethod - def getPrintableError(cls, rsp): - """Return a printed error message string.""" - return "%s: error %s: %s" % (rsp.elementName, \ - cls.getRspErrorCode(rsp), cls.getRspErrorMsg(rsp)) - getPrintableError = classmethod(getPrintableError) - - #----------------------------------------------------------------------- - #@classmethod - def getRspErrorCode(cls, rsp): - """Return the error code of a response, or 0 if no error.""" - if rsp['stat'] == "fail": - return rsp.err[0]['code'] - - return 0 - getRspErrorCode = classmethod(getRspErrorCode) - - #----------------------------------------------------------------------- - #@classmethod - def getRspErrorMsg(cls, rsp): - """Return the error message of a response, or "Success" if no error.""" - if rsp['stat'] == "fail": - return rsp.err[0]['msg'] - - return "Success" - getRspErrorMsg = classmethod(getRspErrorMsg) - - #----------------------------------------------------------------------- - def __getCachedTokenPath(self): - """Return the directory holding the app data.""" - return os.path.expanduser(os.path.sep.join(["~", ".flickr", \ - self.apiKey])) - - #----------------------------------------------------------------------- - def __getCachedTokenFilename(self): - """Return the full pathname of the cached token file.""" - return os.path.sep.join([self.__getCachedTokenPath(), "auth.xml"]) - - #----------------------------------------------------------------------- - def __getCachedToken(self): - """Read and return a cached token, or None if not found. - - The token is read from the cached token file, which is basically the - entire RSP response containing the auth element. - """ - - try: - f = file(self.__getCachedTokenFilename(), "r") - - data = f.read() - f.close() - - rsp = XMLNode.parseXML(data) - - return rsp.auth[0].token[0].elementText - - except IOError: - return None - - #----------------------------------------------------------------------- - def __setCachedToken(self, xml): - """Cache a token for later use. - - The cached tag is stored by simply saving the entire RSP response - containing the auth element. - - """ - - path = self.__getCachedTokenPath() - if not os.path.exists(path): - os.makedirs(path) - - f = file(self.__getCachedTokenFilename(), "w") - f.write(xml) - f.close() - - - #----------------------------------------------------------------------- - def getToken(self, perms="read", browser="lynx"): - """Get a token either from the cache, or make a new one from the - frob. - - This first attempts to find a token in the user's token cache on - disk. - - If that fails (or if the token is no longer valid based on - flickr.auth.checkToken) a new frob is acquired. The frob is - validated by having the user log into flickr (with lynx), and - subsequently a valid token is retrieved. - - The newly minted token is then cached locally for the next run. - - perms--"read", "write", or "delete" - browser--whatever browser should be used in the system() call - - """ - - # see if we have a saved token - token = self.__getCachedToken() - - # see if it's valid - if token != None: - rsp = self.auth_checkToken(api_key=self.apiKey, auth_token=token) - if rsp['stat'] != "ok": - token = None - else: - # see if we have enough permissions - tokenPerms = rsp.auth[0].perms[0].elementText - if tokenPerms == "read" and perms != "read": token = None - elif tokenPerms == "write" and perms == "delete": token = None - - # get a new token if we need one - if token == None: - # get the frob - rsp = self.auth_getFrob(api_key=self.apiKey) - self.testFailure(rsp) - - frob = rsp.frob[0].elementText - - # validate online - os.system("%s '%s'" % (browser, self.__getAuthURL(perms, frob))) - - # get a token - rsp = self.auth_getToken(api_key=self.apiKey, frob=frob) - self.testFailure(rsp) - - token = rsp.auth[0].token[0].elementText - - # store the auth info for next time - self.__setCachedToken(rsp.xml) - - return token - -######################################################################## -# App functionality -######################################################################## - -def main(argv): - # flickr auth information: - flickrAPIKey = "fa33550d413b36b3fddc473a931a3b3b" # API key - flickrSecret = "7fd481bff0916055" # shared "secret" - - # make a new FlickrAPI instance - fapi = FlickrAPI(flickrAPIKey, flickrSecret) - - # do the whole whatever-it-takes to get a valid token: - token = fapi.getToken(browser="chrome") - - # get my favorites - rsp = fapi.favorites_getList(api_key=flickrAPIKey,auth_token=token) - fapi.testFailure(rsp) - - # and print them - for a in rsp.photos[0].photo: - print "%10s: %s" % (a['id'], a['title'].encode("ascii", "replace")) - - # upload the file foo.jpg - #rsp = fapi.upload(filename="foo.jpg", \ - # api_key=flickrAPIKey, auth_token=token, \ - # title="This is the title", description="This is the description", \ - # tags="tag1 tag2 tag3", is_public="1") - #if rsp == None: - # sys.stderr.write("can't find file\n") - #else: - # fapi.testFailure(rsp) - - return 0 - -# run the main if we're not being imported: -if __name__ == "__main__": sys.exit(main(sys.argv)) - +#!/usr/bin/python +# +# Flickr API implementation +# +# Inspired largely by Michele Campeotto's flickrclient and Aaron Swartz' +# xmltramp... but I wanted to get a better idea of how python worked in +# those regards, so I mostly worked those components out for myself. +# +# http://micampe.it/things/flickrclient +# http://www.aaronsw.com/2002/xmltramp/ +# +# Release 1: initial release +# Release 2: added upload functionality +# Release 3: code cleanup, convert to doc strings +# Release 4: better permission support +# Release 5: converted into fuller-featured "flickrapi" +# Release 6: fix upload sig bug (thanks Deepak Jois), encode test output +# Release 7: fix path construction, Manish Rai Jain's improvements, exceptions +# Release 8: change API endpoint to "api.flickr.com" +# +# Work by (or inspired by) Manish Rai Jain : +# +# improved error reporting, proper multipart MIME boundary creation, +# use of urllib2 to allow uploads through a proxy, upload accepts +# raw data as well as a filename +# +# Copyright 2005 Brian "Beej Jorgensen" Hall +# +# This work is licensed under the Creative Commons +# Attribution License. To view a copy of this license, +# visit http://creativecommons.org/licenses/by/2.5/ or send +# a letter to Creative Commons, 543 Howard Street, 5th +# Floor, San Francisco, California, 94105, USA. +# +# This license says that I must be credited for any derivative works. +# You do not need to credit me to simply use the FlickrAPI classes in +# your Python scripts--you only need to credit me if you're taking this +# FlickrAPI class and modifying it or redistributing it. +# +# Previous versions of this API were granted to the public domain. +# You're free to use those as you please. +# +# Beej Jorgensen, Maintainer, November 2005 +# beej@beej.us +# + +from __future__ import print_function +import sys +import md5 +import string +import urllib +import urllib2 +import mimetools +import httplib +import os.path +import xml.dom.minidom + +######################################################################## +# Exceptions +######################################################################## + +class UploadException(Exception): + pass + +######################################################################## +# XML functionality +######################################################################## + +#----------------------------------------------------------------------- +class XMLNode: + """XMLNode -- generic class for holding an XML node + + xmlStr = \"\"\" + Name0 + Name1 + \"\"\" + + f = XMLNode.parseXML(xmlStr) + + print f.elementName # xml + print f['foo'] # 32 + print f.name # [, ] + print f.name[0].elementName # name + print f.name[0]["bar"] # 10 + print f.name[0].elementText # Name0 + print f.name[1].elementName # name + print f.name[1]["bar"] # 11 + print f.name[1]["baz"] # 12 + + """ + + def __init__(self): + """Construct an empty XML node.""" + self.elementName="" + self.elementText="" + self.attrib={} + self.xml="" + + def __setitem__(self, key, item): + """Store a node's attribute in the attrib hash.""" + self.attrib[key] = item + + def __getitem__(self, key): + """Retrieve a node's attribute from the attrib hash.""" + try: + return self.attrib[key] + except: + return "null" + #----------------------------------------------------------------------- + #@classmethod + def parseXML(cls, xmlStr, storeXML=False): + """Convert an XML string into a nice instance tree of XMLNodes. + + xmlStr -- the XML to parse + storeXML -- if True, stores the XML string in the root XMLNode.xml + + """ + + def __parseXMLElement(element, thisNode): + """Recursive call to process this XMLNode.""" + thisNode.elementName = element.nodeName + + #print element.nodeName + + # add element attributes as attributes to this node + for i in range(element.attributes.length): + an = element.attributes.item(i) + thisNode[an.name] = an.nodeValue + + for a in element.childNodes: + if a.nodeType == xml.dom.Node.ELEMENT_NODE: + + child = XMLNode() + try: + list = getattr(thisNode, a.nodeName) + except AttributeError: + setattr(thisNode, a.nodeName, []) + + # add the child node as an attrib to this node + list = getattr(thisNode, a.nodeName); + #print "appending child: %s to %s" % (a.nodeName, thisNode.elementName) + list.append(child); + + __parseXMLElement(a, child) + + elif a.nodeType == xml.dom.Node.TEXT_NODE: + thisNode.elementText += a.nodeValue + + return thisNode + + dom = xml.dom.minidom.parseString(xmlStr) + + # get the root + rootNode = XMLNode() + if storeXML: rootNode.xml = xmlStr + + return __parseXMLElement(dom.firstChild, rootNode) + parseXML = classmethod(parseXML) + +######################################################################## +# Flickr functionality +######################################################################## + +#----------------------------------------------------------------------- +class FlickrAPI: + """Encapsulated flickr functionality. + + Example usage: + + flickr = FlickrAPI(flickrAPIKey, flickrSecret) + rsp = flickr.auth_checkToken(api_key=flickrAPIKey, auth_token=token) + + """ + flickrHost = "api.flickr.com" + flickrRESTForm = "/services/rest/" + flickrAuthForm = "/services/auth/" + flickrUploadForm = "/services/upload/" + + #------------------------------------------------------------------- + def __init__(self, apiKey, secret): + """Construct a new FlickrAPI instance for a given API key and secret.""" + self.apiKey = apiKey + self.secret = secret + + self.__handlerCache={} + + #------------------------------------------------------------------- + def __sign(self, data): + """Calculate the flickr signature for a set of params. + + data -- a hash of all the params and values to be hashed, e.g. + {"api_key":"AAAA", "auth_token":"TTTT"} + + """ + dataName = self.secret + keys = data.keys() + keys.sort() + for a in keys: dataName += (a + data[a]) + #print dataName + hash = md5.new() + hash.update(dataName) + return hash.hexdigest() + + #------------------------------------------------------------------- + def __getattr__(self, method, **arg): + """Handle all the flickr API calls. + + This is Michele Campeotto's cleverness, wherein he writes a + general handler for methods not defined, and assumes they are + flickr methods. He then converts them to a form to be passed as + the method= parameter, and goes from there. + + http://micampe.it/things/flickrclient + + My variant is the same basic thing, except it tracks if it has + already created a handler for a specific call or not. + + example usage: + + flickr.auth_getFrob(api_key="AAAAAA") + rsp = flickr.favorites_getList(api_key=flickrAPIKey, \\ + auth_token=token) + + """ + + if method not in self.__handlerCache: + def handler(_self = self, _method = method, **arg): + _method = "flickr." + _method.replace("_", ".") + url = "http://" + FlickrAPI.flickrHost + \ + FlickrAPI.flickrRESTForm + arg["method"] = _method + postData = urllib.urlencode(arg) + "&api_sig=" + \ + _self.__sign(arg) + #print "--url---------------------------------------------" + #print url + #print "--postData----------------------------------------" + #print postData + f = urllib.urlopen(url, postData) + data = f.read() + #print "--response----------------------------------------" + #print data + f.close() + return XMLNode.parseXML(data, True) + + self.__handlerCache[method] = handler; + + return self.__handlerCache[method] + + #------------------------------------------------------------------- + def __getAuthURL(self, perms, frob): + """Return the authorization URL to get a token. + + This is the URL the app will launch a browser toward if it + needs a new token. + + perms -- "read", "write", or "delete" + frob -- picked up from an earlier call to FlickrAPI.auth_getFrob() + + """ + + data = {"api_key": self.apiKey, "frob": frob, "perms": perms} + data["api_sig"] = self.__sign(data) + return "http://%s%s?%s" % (FlickrAPI.flickrHost, \ + FlickrAPI.flickrAuthForm, urllib.urlencode(data)) + + #------------------------------------------------------------------- + def upload(self, filename=None, jpegData=None, **arg): + """Upload a file to flickr. + + Be extra careful you spell the parameters correctly, or you will + get a rather cryptic "Invalid Signature" error on the upload! + + Supported parameters: + + One of filename or jpegData must be specified by name when + calling this method: + + filename -- name of a file to upload + jpegData -- array of jpeg data to upload + + api_key + auth_token + title + description + tags -- space-delimited list of tags, "tag1 tag2 tag3" + is_public -- "1" or "0" + is_friend -- "1" or "0" + is_family -- "1" or "0" + + """ + + if filename == None and jpegData == None or \ + filename != None and jpegData != None: + + raise UploadException("filename OR jpegData must be specified") + + # verify key names + for a in arg.keys(): + if a != "api_key" and a != "auth_token" and a != "title" and \ + a != "description" and a != "tags" and a != "is_public" and \ + a != "is_friend" and a != "is_family": + + sys.stderr.write("FlickrAPI: warning: unknown parameter " \ + "\"%s\" sent to FlickrAPI.upload\n" % (a)) + + arg["api_sig"] = self.__sign(arg) + url = "http://" + FlickrAPI.flickrHost + FlickrAPI.flickrUploadForm + + # construct POST data + boundary = mimetools.choose_boundary() + body = "" + + # required params + for a in ('api_key', 'auth_token', 'api_sig'): + body += "--%s\r\n" % (boundary) + body += "Content-Disposition: form-data; name=\""+a+"\"\r\n\r\n" + body += "%s\r\n" % (arg[a]) + + # optional params + for a in ('title', 'description', 'tags', 'is_public', \ + 'is_friend', 'is_family'): + + if a in arg: + body += "--%s\r\n" % (boundary) + body += "Content-Disposition: form-data; name=\""+a+"\"\r\n\r\n" + body += "%s\r\n" % (arg[a]) + + body += "--%s\r\n" % (boundary) + body += "Content-Disposition: form-data; name=\"photo\";" + body += " filename=\"%s\"\r\n" % filename + body += "Content-Type: image/jpeg\r\n\r\n" + + #print body + + if filename != None: + fp = file(filename, "rb") + data = fp.read() + fp.close() + else: + data = jpegData + + postData = body.encode("utf_8") + data + \ + ("--%s--" % (boundary)).encode("utf_8") + + request = urllib2.Request(url) + request.add_data(postData) + request.add_header("Content-Type", \ + "multipart/form-data; boundary=%s" % boundary) + response = urllib2.urlopen(request) + rspXML = response.read() + + return XMLNode.parseXML(rspXML) + + + #----------------------------------------------------------------------- + #@classmethod + def testFailure(cls, rsp, exit=True): + """Exit app if the rsp XMLNode indicates failure.""" + if rsp['stat'] == "fail": + sys.stderr.write("%s\n" % (cls.getPrintableError(rsp))) + if exit: sys.exit(1) + testFailure = classmethod(testFailure) + + #----------------------------------------------------------------------- + #@classmethod + def getPrintableError(cls, rsp): + """Return a printed error message string.""" + return "%s: error %s: %s" % (rsp.elementName, \ + cls.getRspErrorCode(rsp), cls.getRspErrorMsg(rsp)) + getPrintableError = classmethod(getPrintableError) + + #----------------------------------------------------------------------- + #@classmethod + def getRspErrorCode(cls, rsp): + """Return the error code of a response, or 0 if no error.""" + if rsp['stat'] == "fail": + return rsp.err[0]['code'] + + return 0 + getRspErrorCode = classmethod(getRspErrorCode) + + #----------------------------------------------------------------------- + #@classmethod + def getRspErrorMsg(cls, rsp): + """Return the error message of a response, or "Success" if no error.""" + if rsp['stat'] == "fail": + return rsp.err[0]['msg'] + + return "Success" + getRspErrorMsg = classmethod(getRspErrorMsg) + + #----------------------------------------------------------------------- + def __getCachedTokenPath(self): + """Return the directory holding the app data.""" + return os.path.expanduser(os.path.sep.join(["~", ".flickr", \ + self.apiKey])) + + #----------------------------------------------------------------------- + def __getCachedTokenFilename(self): + """Return the full pathname of the cached token file.""" + return os.path.sep.join([self.__getCachedTokenPath(), "auth.xml"]) + + #----------------------------------------------------------------------- + def __getCachedToken(self): + """Read and return a cached token, or None if not found. + + The token is read from the cached token file, which is basically the + entire RSP response containing the auth element. + """ + + try: + f = file(self.__getCachedTokenFilename(), "r") + + data = f.read() + f.close() + + rsp = XMLNode.parseXML(data) + + return rsp.auth[0].token[0].elementText + + except IOError: + return None + + #----------------------------------------------------------------------- + def __setCachedToken(self, xml): + """Cache a token for later use. + + The cached tag is stored by simply saving the entire RSP response + containing the auth element. + + """ + + path = self.__getCachedTokenPath() + if not os.path.exists(path): + os.makedirs(path) + + f = file(self.__getCachedTokenFilename(), "w") + f.write(xml) + f.close() + + + #----------------------------------------------------------------------- + def getToken(self, perms="read", browser="lynx"): + """Get a token either from the cache, or make a new one from the + frob. + + This first attempts to find a token in the user's token cache on + disk. + + If that fails (or if the token is no longer valid based on + flickr.auth.checkToken) a new frob is acquired. The frob is + validated by having the user log into flickr (with lynx), and + subsequently a valid token is retrieved. + + The newly minted token is then cached locally for the next run. + + perms--"read", "write", or "delete" + browser--whatever browser should be used in the system() call + + """ + + # see if we have a saved token + token = self.__getCachedToken() + + # see if it's valid + if token != None: + rsp = self.auth_checkToken(api_key=self.apiKey, auth_token=token) + if rsp['stat'] != "ok": + token = None + else: + # see if we have enough permissions + tokenPerms = rsp.auth[0].perms[0].elementText + if tokenPerms == "read" and perms != "read": token = None + elif tokenPerms == "write" and perms == "delete": token = None + + # get a new token if we need one + if token == None: + # get the frob + rsp = self.auth_getFrob(api_key=self.apiKey) + self.testFailure(rsp) + + frob = rsp.frob[0].elementText + + # validate online + os.system("%s '%s'" % (browser, self.__getAuthURL(perms, frob))) + + # get a token + rsp = self.auth_getToken(api_key=self.apiKey, frob=frob) + self.testFailure(rsp) + + token = rsp.auth[0].token[0].elementText + + # store the auth info for next time + self.__setCachedToken(rsp.xml) + + return token + +######################################################################## +# App functionality +######################################################################## + +def main(argv): + # flickr auth information: + flickrAPIKey = "fa33550d413b36b3fddc473a931a3b3b" # API key + flickrSecret = "7fd481bff0916055" # shared "secret" + + # make a new FlickrAPI instance + fapi = FlickrAPI(flickrAPIKey, flickrSecret) + + # do the whole whatever-it-takes to get a valid token: + token = fapi.getToken(browser="chrome") + + # get my favorites + rsp = fapi.favorites_getList(api_key=flickrAPIKey,auth_token=token) + fapi.testFailure(rsp) + + # and print them + for a in rsp.photos[0].photo: + print("%10s: %s" % (a['id'], a['title'].encode("ascii", "replace"))) + + # upload the file foo.jpg + #rsp = fapi.upload(filename="foo.jpg", \ + # api_key=flickrAPIKey, auth_token=token, \ + # title="This is the title", description="This is the description", \ + # tags="tag1 tag2 tag3", is_public="1") + #if rsp == None: + # sys.stderr.write("can't find file\n") + #else: + # fapi.testFailure(rsp) + + return 0 + +# run the main if we're not being imported: +if __name__ == "__main__": sys.exit(main(sys.argv)) + diff --git a/SimpleCV/MachineLearning/query_imgs/get_imgs_geo_gps_search.py b/SimpleCV/MachineLearning/query_imgs/get_imgs_geo_gps_search.py index bba10c7fb..8b5b17c34 100644 --- a/SimpleCV/MachineLearning/query_imgs/get_imgs_geo_gps_search.py +++ b/SimpleCV/MachineLearning/query_imgs/get_imgs_geo_gps_search.py @@ -21,6 +21,7 @@ # now uses date_taken instead of date_upload to get more diverse blocks of images # 1/13/2009 - uses the original im2gps keywords, not as negative constraints though +from __future__ import print_function import sys, string, math, time, socket from flickrapi2 import FlickrAPI from datetime import datetime @@ -55,8 +56,8 @@ def DoSearch(fapi,query_string,desired_photos): - print datetime.fromtimestamp(mintime) - print datetime.fromtimestamp(endtime) + print(datetime.fromtimestamp(mintime)) + print(datetime.fromtimestamp(endtime)) while (maxtime < endtime): @@ -69,9 +70,9 @@ def DoSearch(fapi,query_string,desired_photos): upper_bound = mintime + timeskip * 20 #upper bound of the upper time limit maxtime = .95 * lower_bound + .05 * upper_bound - print '\nBinary search on time range upper bound' - print 'Lower bound is ' + str(datetime.fromtimestamp(lower_bound)) - print 'Upper bound is ' + str(datetime.fromtimestamp(upper_bound)) + print('\nBinary search on time range upper bound') + print('Lower bound is ' + str(datetime.fromtimestamp(lower_bound))) + print('Upper bound is ' + str(datetime.fromtimestamp(upper_bound))) keep_going = 6 #search stops after a fixed number of iterations while( keep_going > 0 and maxtime < endtime): @@ -94,21 +95,21 @@ def DoSearch(fapi,query_string,desired_photos): null_test = int(total_images); #want to make sure this won't crash later on for some reason null_test = float(total_images); - print '\nnumimgs: ' + total_images - print 'mintime: ' + str(mintime) + ' maxtime: ' + str(maxtime) + ' timeskip: ' + str(maxtime - mintime) + print('\nnumimgs: ' + total_images) + print('mintime: ' + str(mintime) + ' maxtime: ' + str(maxtime) + ' timeskip: ' + str(maxtime - mintime)) if( int(total_images) > desired_photos ): - print 'too many photos in block, reducing maxtime' + print('too many photos in block, reducing maxtime') upper_bound = maxtime maxtime = (lower_bound + maxtime) / 2 #midpoint between current value and lower bound. if( int(total_images) < desired_photos): - print 'too few photos in block, increasing maxtime' + print('too few photos in block, increasing maxtime') lower_bound = maxtime maxtime = (upper_bound + maxtime) / 2 - print 'Lower bound is ' + str(datetime.fromtimestamp(lower_bound)) - print 'Upper bound is ' + str(datetime.fromtimestamp(upper_bound)) + print('Lower bound is ' + str(datetime.fromtimestamp(lower_bound))) + print('Upper bound is ' + str(datetime.fromtimestamp(upper_bound))) if( int(total_images) > 0): #only if we're not in a degenerate case keep_going = keep_going - 1 @@ -119,14 +120,14 @@ def DoSearch(fapi,query_string,desired_photos): print('Keyboard exception while querying for images, exiting\n') raise except: - print sys.exc_info()[0] + print(sys.exc_info()[0]) #print type(inst) # the exception instance #print inst.args # arguments stored in .args #print inst # __str__ allows args to printed directly print ('Exception encountered while querying for images\n') #end of while binary search - print 'finished binary search' + print('finished binary search') return([mintime,maxtime,total_images,rsp]) @@ -154,7 +155,7 @@ def DoSearch(fapi,query_string,desired_photos): for line in query_file: if line[0] != '#' and len(line) > 1: #line end character is 2 long? - print line[0:len(line)-1] + print(line[0:len(line)-1]) if line[0] != '-': pos_queries = pos_queries + [line[0:len(line)-1]] num_queries = num_queries + 1 @@ -162,10 +163,10 @@ def DoSearch(fapi,query_string,desired_photos): neg_queries = neg_queries + ' ' + line[0:len(line)-1] query_file.close() -print 'positive queries: ' -print pos_queries -print 'negative queries: ' + neg_queries -print 'num_queries = ' + str(num_queries) +print('positive queries: ') +print(pos_queries) +print('negative queries: ' + neg_queries) +print('num_queries = ' + str(num_queries)) #this is the desired number of photos in each block @@ -193,27 +194,27 @@ def DoSearch(fapi,query_string,desired_photos): #form the query string. query_string = pos_queries[current_tag] + ' ' + neg_queries - print '\n\nquery_string is ' + query_string + print('\n\nquery_string is ' + query_string) total_images_queried = 0; [mintime,maxtime,total_images,rsp] = DoSearch(fapi,query_string,desired_photos) print('GETTING TOTATL IMAGES:'+str(total_images)) s = '\nmintime: ' + str(mintime) + ' maxtime: ' + str(maxtime) - print s + print(s) out_file.write(s + '\n') i = getattr(rsp,'photos',None) if i: s = 'numimgs: ' + total_images - print s + print(s) out_file.write(s + '\n') current_image_num = 1; num = 4 # CHANGE THIS BACK int(rsp.photos[0]['pages']) s = 'total pages: ' + str(num) - print s + print(s) out_file.write(s + '\n') #only visit 16 pages max, to try and avoid the dreaded duplicate bug @@ -222,7 +223,7 @@ def DoSearch(fapi,query_string,desired_photos): num_visit_pages = min(16,num) s = 'visiting only ' + str(num_visit_pages) + ' pages ( up to ' + str(num_visit_pages * 250) + ' images)' - print s + print(s) out_file.write(s + '\n') total_images_queried = total_images_queried + min((num_visit_pages * 250), int(total_images)) @@ -235,7 +236,7 @@ def DoSearch(fapi,query_string,desired_photos): while( pagenum <= num_visit_pages ): #for pagenum in range(1, num_visit_pages + 1): #page one is searched twice - print ' page number ' + str(pagenum) + print(' page number ' + str(pagenum)) try: print("PAGE") @@ -273,7 +274,7 @@ def DoSearch(fapi,query_string,desired_photos): print('Keyboard exception while querying for images, exiting\n') raise except: - print sys.exc_info()[0] + print(sys.exc_info()[0]) #print type(inst) # the exception instance #print inst.args # arguments stored in .args #print inst # __str__ allows args to printed directly diff --git a/SimpleCV/Shell/Example.py b/SimpleCV/Shell/Example.py index 229d65036..2251e22fa 100644 --- a/SimpleCV/Shell/Example.py +++ b/SimpleCV/Shell/Example.py @@ -1,4 +1,5 @@ #!/usr/bin/python +from __future__ import print_function import os import glob from subprocess import call @@ -26,37 +27,37 @@ def magic_examples(self, arg): if isinstance(arg, str) and arg == "": counter = 0 - print "Available Examples:" - print "--------------------------------------------" + print("Available Examples:") + print("--------------------------------------------") for file in file_names: - print "[",counter,"]:",file + print("[",counter,"]:",file) counter += 1 - print "Just type example #, to run the example on the list" - print "for instance: example 1" - print "" - print "Close the window or press ctrl+c to stop the example" + print("Just type example #, to run the example on the list") + print("for instance: example 1") + print("") + print("Close the window or press ctrl+c to stop the example") elif isinstance(iarg, int): - print "running example:", files[iarg] + print("running example:", files[iarg]) try: call([sys.executable, files[iarg]]) except: - print "Couldn't run example:", files[iarg] + print("Couldn't run example:", files[iarg]) elif isinstance(arg, str) and arg.lower() == "joshua": - print "GREETINGS PROFESSOR FALKEN" - print "" - print "HELLO" - print "" - print "A STRANGE GAME." - print "THE ONLY WINNING MOVE IS" - print "NOT TO PLAY." - print "" - print "HOW ABOUT A NICE GAME OF CHESS?" - print "" + print("GREETINGS PROFESSOR FALKEN") + print("") + print("HELLO") + print("") + print("A STRANGE GAME.") + print("THE ONLY WINNING MOVE IS") + print("NOT TO PLAY.") + print("") + print("HOW ABOUT A NICE GAME OF CHESS?") + print("") else: - print "Example: " + arg + " does not exist, or an error occurred" + print("Example: " + arg + " does not exist, or an error occurred") diff --git a/SimpleCV/Shell/Shell.py b/SimpleCV/Shell/Shell.py index 569dae1b9..3a76a074f 100755 --- a/SimpleCV/Shell/Shell.py +++ b/SimpleCV/Shell/Shell.py @@ -18,6 +18,7 @@ #load system libraries +from __future__ import print_function from subprocess import call import platform import webbrowser @@ -58,8 +59,8 @@ def plot(arg): logger.warning("Matplotlib is not installed and required") return - print "args", arg - print "type", type(arg) + print("args", arg) + print("type", type(arg)) plt.plot(arg) plt.show() @@ -230,7 +231,7 @@ def main(*args): sys.exit() elif flag == 'update': - print "Updating SimpleCV....." + print("Updating SimpleCV.....") self_update() if flag in ['--headless', 'headless']: diff --git a/SimpleCV/Shell/Tutorial.py b/SimpleCV/Shell/Tutorial.py index 944ef2930..8f4e35f49 100644 --- a/SimpleCV/Shell/Tutorial.py +++ b/SimpleCV/Shell/Tutorial.py @@ -3,6 +3,7 @@ # A Basic SimpleCV interactive shell tutorial #load required libraries +from __future__ import print_function from SimpleCV import * from subprocess import call @@ -32,10 +33,10 @@ def attempt(variable_name, desired_class): if isinstance(variable,desired_class): if desired_class == Image: if variable.isEmpty(): - print lb - print "Although you can create empty Images on SimpleCV, let's not" - print "play with that now!" - print lb + print(lb) + print("Although you can create empty Images on SimpleCV, let's not") + print("play with that now!") + print(lb) return False return True @@ -54,112 +55,112 @@ def request_show_command(): return def end_tutorial(): - print lb - print "Type 'quit' to leave the tutorials, or press Enter to move on!" + print(lb) + print("Type 'quit' to leave the tutorials, or press Enter to move on!") command = raw_input("SimpleCV:> ") return command.lower() == 'quit' def end_of_tutorial(): - print lb - print "This is the end of our tutorial!" - print lb - print "For more help, go to www.simplecv.org, and don't forget about the" - print "help function!" - print lb + print(lb) + print("This is the end of our tutorial!") + print(lb) + print("For more help, go to www.simplecv.org, and don't forget about the") + print("help function!") + print(lb) def command_loop(command, desired_tuple): while True: - print command - print lb + print(command) + print(lb) if attempt(desired_tuple[0], desired_tuple[1]): return - print lb - print "Oops! %s is still not %s" % (desired_tuple[0], str(desired_tuple[1])) + print(lb) + print("Oops! %s is still not %s" % (desired_tuple[0], str(desired_tuple[1]))) def tutorial_image(): shellclear() - print "SimpleCV Image tutorial" - print "-----------------------" - print lb - print "Using images is simple, in SimpleCV." - print lb - print "First thing we are going to do is load an image. Try it yourself:" - print lb + print("SimpleCV Image tutorial") + print("-----------------------") + print(lb) + print("Using images is simple, in SimpleCV.") + print(lb) + print("First thing we are going to do is load an image. Try it yourself:") + print(lb) cmd = "logo = Image(\"simplecv\")" desired_tuple = ('logo', Image) command_loop(cmd, desired_tuple) - print lb - print "Correct! You just loaded SimpleCV logo into memory." - print "Let's try it to use one of your images. There are different ways to" - print "do that. You can try, for example:" - print lb - print "img = Image(URL_TO_MY_PICTURE) or img = Image(PATH_TO_MY_PICTURE)" - print lb + print(lb) + print("Correct! You just loaded SimpleCV logo into memory.") + print("Let's try it to use one of your images. There are different ways to") + print("do that. You can try, for example:") + print(lb) + print("img = Image(URL_TO_MY_PICTURE) or img = Image(PATH_TO_MY_PICTURE)") + print(lb) cmd = "Example: img = Image('http://simplecv.org/logo.jpg')" desired_tuple = ('img', Image) command_loop(cmd, desired_tuple) - print lb - print "Perfect! Now we want to see it:" - print lb + print(lb) + print("Perfect! Now we want to see it:") + print(lb) cmd = "img.show()" - print cmd - print lb + print(cmd) + print(lb) request_show_command() - print lb - print "Alright! This was tutorial 1/6." - print "Next tutorial: Saving Images" + print(lb) + print("Alright! This was tutorial 1/6.") + print("Next tutorial: Saving Images") if not end_tutorial(): tutorial_save() return def tutorial_save(): shellclear() - print "Saving Images" - print lb - print "Once you have an Image Object loaded in memory you can" - print "now save it to disk." - print lb + print("Saving Images") + print(lb) + print("Once you have an Image Object loaded in memory you can") + print("now save it to disk.") + print(lb) raw_input("[Press enter to continue]") - print lb - print "Saving an image is very simple, pardon the pun. Once it's loaded" - print "into memory, it's literally just:" - print "img.save()" - print lb - print "This will save the image back to the location it was loaded from" - print "so if you did img = Image('/tmp/test.jpg'), then it would save" - print "it back there, otherwise you can do:" - print "img.save('/any/path/you/want')" - print lb - print "So try it now and save an image somewhere on your system" - print lb + print(lb) + print("Saving an image is very simple, pardon the pun. Once it's loaded") + print("into memory, it's literally just:") + print("img.save()") + print(lb) + print("This will save the image back to the location it was loaded from") + print("so if you did img = Image('/tmp/test.jpg'), then it would save") + print("it back there, otherwise you can do:") + print("img.save('/any/path/you/want')") + print(lb) + print("So try it now and save an image somewhere on your system") + print(lb) if platform.system() == "Windows": - print "img.save('C:/myimg.jpg')" + print("img.save('C:/myimg.jpg')") else: - print "img.save('/tmp/new.jpg')" + print("img.save('/tmp/new.jpg')") - print lb + print(lb) while True: if prompt_and_run().startswith('img.save'): break - print "Please try to save img!" - print lb + print("Please try to save img!") + print(lb) - print "Correct, you just saved a new copy of your image!" - print "As you can see in SimpleCV most of the functions are intuitive." + print("Correct, you just saved a new copy of your image!") + print("As you can see in SimpleCV most of the functions are intuitive.") - print lb - print "Alright! This was tutorial 2/6." - print "Next tutorial: Camera" + print(lb) + print("Alright! This was tutorial 2/6.") + print("Next tutorial: Camera") if not end_tutorial(): tutorial_camera() return @@ -167,56 +168,56 @@ def tutorial_save(): def tutorial_camera(): shellclear() - print "Camera" - print lb - print "As long as your camera driver is supported then you shouldn't have a" - print "problem. Type 'skip' to skip the camera tutorial, or press Enter to" - print "continue." - print lb + print("Camera") + print(lb) + print("As long as your camera driver is supported then you shouldn't have a") + print("problem. Type 'skip' to skip the camera tutorial, or press Enter to") + print("continue.") + print(lb) command = raw_input("SimpleCV:> ") if command.lower() != 'skip': - print lb - print "To load the camera, just type:" - print lb + print(lb) + print("To load the camera, just type:") + print(lb) cmd = "cam = Camera()" desired_tuple = ('cam', Camera) command_loop(cmd, desired_tuple) - print lb - print "Next, to grab an image from the Camera we type:" + print(lb) + print("Next, to grab an image from the Camera we type:") cmd = "img = cam.getImage()" tutorial_interpreter.runsource("del(img)") desired_tuple = ('img', Image) command_loop(cmd, desired_tuple) - print "Just as before, if we want to display it, we just type:" - print lb - print "img.show()" - print lb + print("Just as before, if we want to display it, we just type:") + print(lb) + print("img.show()") + print(lb) request_show_command() - print lb - print "Alright! This was tutorial 3/6." - print "Next tutorial: Copying Images" + print(lb) + print("Alright! This was tutorial 3/6.") + print("Next tutorial: Copying Images") if not end_tutorial(): tutorial_copy() return def tutorial_copy(): shellclear() - print "Copying Images" - print lb - print "If you need a copy of an image, this is also very simple:" - print "Let's try to clone img, which we already have." + print("Copying Images") + print(lb) + print("If you need a copy of an image, this is also very simple:") + print("Let's try to clone img, which we already have.") global img if not img: img = Image("lenna") - print lb + print(lb) cmd = "clone = img.copy()" desired_tuple = ('clone', Image) @@ -225,37 +226,37 @@ def tutorial_copy(): if clone != img: #Returns False if they have different addresses. break - print "You have to use the copy() function!" + print("You have to use the copy() function!") - print lb - print "Correct, you just cloned an image into memory." - print "You need to be careful when using this method though as using as a" - print "reference vs. a copy. For instance, if you just typed:" - print lb - print "clone = img" - print lb - print "clone would actually point at the same thing in memory as img." + print(lb) + print("Correct, you just cloned an image into memory.") + print("You need to be careful when using this method though as using as a") + print("reference vs. a copy. For instance, if you just typed:") + print(lb) + print("clone = img") + print(lb) + print("clone would actually point at the same thing in memory as img.") - print lb - print "Alright! This was tutorial 4/6." - print "Next tutorial: Manipulating Images" + print(lb) + print("Alright! This was tutorial 4/6.") + print("Next tutorial: Manipulating Images") if not end_tutorial(): tutorial_manipulation() return def tutorial_manipulation(): shellclear() - print "Manipulating Images" - print lb - print "Now we can easily load and save images. It's time to start doing some" - print "image processing with them. Let's make img, which we already have, a" - print "90x90 thumbnail:" + print("Manipulating Images") + print(lb) + print("Now we can easily load and save images. It's time to start doing some") + print("image processing with them. Let's make img, which we already have, a") + print("90x90 thumbnail:") global img if not img: img = Image("lenna") - print lb + print(lb) cmd = "thumb = img.scale(90,90)" desired_tuple = ('thumb', Image) @@ -264,45 +265,45 @@ def tutorial_manipulation(): if thumb.size() == (90,90): break - print "Your thumbnail's size isn't 90x90! Try again!" + print("Your thumbnail's size isn't 90x90! Try again!") - print lb - print "Now display it with thumb.show()" - print lb + print(lb) + print("Now display it with thumb.show()") + print(lb) request_show_command() - print lb - print "Now let's erode the picture some:" - print lb + print(lb) + print("Now let's erode the picture some:") + print(lb) cmd = "eroded = img.erode()" desired_tuple = ('eroded', Image) command_loop(cmd, desired_tuple) - print lb - print "Display it with eroded.show(). It should look almost as if the image" - print "was made if ink and had water spoiled on it." - print lb + print(lb) + print("Display it with eroded.show(). It should look almost as if the image") + print("was made if ink and had water spoiled on it.") + print(lb) request_show_command() - print lb - print "Last but not least, let's crop a section of the image out:" - print lb + print(lb) + print("Last but not least, let's crop a section of the image out:") + print(lb) cmd = "cropped = img.crop(100, 100, 50, 50)" desired_tuple = ('cropped', Image) command_loop(cmd, desired_tuple) - print lb - print "Use cropped.show() to display it." - print lb + print(lb) + print("Use cropped.show() to display it.") + print(lb) request_show_command() - print lb - print "That went from the coordinate in (X,Y), which is (0,0) and is the" - print "top left corner of the picture, to coordinates (100,100) in the" - print "(X,Y) and cropped a picture from that which is 50 pixels by 50 pixels." - - print lb - print "Alright! This was tutorial 5/6." - print "Next tutorial: Features" + print(lb) + print("That went from the coordinate in (X,Y), which is (0,0) and is the") + print("top left corner of the picture, to coordinates (100,100) in the") + print("(X,Y) and cropped a picture from that which is 50 pixels by 50 pixels.") + + print(lb) + print("Alright! This was tutorial 5/6.") + print("Next tutorial: Features") if not end_tutorial(): tutorial_features() return @@ -311,127 +312,127 @@ def tutorial_manipulation(): def tutorial_slicing(): shellclear() - print "Slicing Images" - print lb - print "Slicing is sort of a new paradigm to access parts of an image." - print "Typically in vision a region of interest (ROI) is given. " - print "In this case, slicing is a very powerful way to access parts" - print "of an image, or basically any matrix in SimpleCV in general." - print lb - print "This is done by using:" - print "section = img[1:10,1:10]" - print lb - print "What is returned is an image object with that window." - print "the slicing basically acts like a ROI but returns an image" - print "so if you wanted to say run edge detection on a 20x20 box" - print "in the picture that started at x=5,y=10 you use:" - print "foundedges = img[5:25,10:30].edges()" - print lb + print("Slicing Images") + print(lb) + print("Slicing is sort of a new paradigm to access parts of an image.") + print("Typically in vision a region of interest (ROI) is given. ") + print("In this case, slicing is a very powerful way to access parts") + print("of an image, or basically any matrix in SimpleCV in general.") + print(lb) + print("This is done by using:") + print("section = img[1:10,1:10]") + print(lb) + print("What is returned is an image object with that window.") + print("the slicing basically acts like a ROI but returns an image") + print("so if you wanted to say run edge detection on a 20x20 box") + print("in the picture that started at x=5,y=10 you use:") + print("foundedges = img[5:25,10:30].edges()") + print(lb) raw_input("[Press enter to continue]") shellclear() in_text = "" shouldbe = "ROI = img[1:6,1:6]" - print "Please type this now:" - print shouldbe - print lb + print("Please type this now:") + print(shouldbe) + print(lb) while (in_text != shouldbe): in_text = raw_input("SimpleCV:>") if(in_text != shouldbe): - print "sorry, that is incorrect" - print "please type:" - print shouldbe + print("sorry, that is incorrect") + print("please type:") + print(shouldbe) shellclear() - print "Correct, you just returned a 5 pixel by 5 pixel image object" - print lb + print("Correct, you just returned a 5 pixel by 5 pixel image object") + print(lb) return def tutorial_features(): shellclear() - print "Features" - print lb - print "Features are things you are looking for in the picture. They can be" - print "blobs, corners, lines, etc. Features are sometimes referred to as a" - print "fiducial in computer vision. These features are something that is" - print "measurable, and something that makes images unique. Features are" - print "something like when comparing things like fruit. In this case the" - print "features could be the shape and the color, amongst others." - print lb - print "What features are in SimpleCV is an abstract representation of that." - print "You take your image, then perform a function on it, and get back" - print "features or another image with them applied. The crop example is" - print "a case where an image is returned after we perform something." - print lb - print "In a simple example we will use the famous 'lenna' image, and find" - print "corners in the picture." - print lb + print("Features") + print(lb) + print("Features are things you are looking for in the picture. They can be") + print("blobs, corners, lines, etc. Features are sometimes referred to as a") + print("fiducial in computer vision. These features are something that is") + print("measurable, and something that makes images unique. Features are") + print("something like when comparing things like fruit. In this case the") + print("features could be the shape and the color, amongst others.") + print(lb) + print("What features are in SimpleCV is an abstract representation of that.") + print("You take your image, then perform a function on it, and get back") + print("features or another image with them applied. The crop example is") + print("a case where an image is returned after we perform something.") + print(lb) + print("In a simple example we will use the famous 'lenna' image, and find") + print("corners in the picture.") + print(lb) tutorial_interpreter.runsource("img = Image('lenna')") - print "img = Image('lenna') (already done for you)" - print lb - print "Try it yourself:" - print lb + print("img = Image('lenna') (already done for you)") + print(lb) + print("Try it yourself:") + print(lb) cmd = "corners = img.findCorners()" desired_tuple = ('corners', FeatureSet) command_loop(cmd, desired_tuple) - print lb - print "Correct, you just got a featureset object which contains" - print "feature objects. These feature objects contain data from the" - print "found corners" - print lb + print(lb) + print("Correct, you just got a featureset object which contains") + print("feature objects. These feature objects contain data from the") + print("found corners") + print(lb) - print "Tip: If your are unsure what parameters to pass, you can always use" - print "the built in help support by typing help(Image.findCorners). Keep in" - print "mind that this help works for all of the functions available in" - print "SimpleCV" - print lb + print("Tip: If your are unsure what parameters to pass, you can always use") + print("the built in help support by typing help(Image.findCorners). Keep in") + print("mind that this help works for all of the functions available in") + print("SimpleCV") + print(lb) - print "We can also do that with blobs. Try it:" - print lb + print("We can also do that with blobs. Try it:") + print(lb) cmd = "blobs = img.findBlobs()" desired_tuple = ('blobs', FeatureSet) command_loop(cmd, desired_tuple) - print lb - print "Great, but..." - print "When we show the image we won't notice anything different. This" - print "is because we have to actually tell the blobs to draw themselves" - print "on the image:" - print lb - print "blobs.draw()" - print lb + print(lb) + print("Great, but...") + print("When we show the image we won't notice anything different. This") + print("is because we have to actually tell the blobs to draw themselves") + print("on the image:") + print(lb) + print("blobs.draw()") + print(lb) while True: if prompt_and_run().endswith('.draw()'): break - print "No blobs have been drawn!" - print lb + print("No blobs have been drawn!") + print(lb) - print "Now use img.show() to see the changes!" - print lb + print("Now use img.show() to see the changes!") + print(lb) request_show_command() - print lb + print(lb) raw_input("[Press enter to continue]") - print lb - print lb - print "There's also a small trick built into SimpleCV to do this even faster" - print lb + print(lb) + print(lb) + print("There's also a small trick built into SimpleCV to do this even faster") + print(lb) tutorial_interpreter.runsource("img = Image('lenna')") - print "img = Image('lenna') (already done for you)" - print lb + print("img = Image('lenna') (already done for you)") + print(lb) while True: - print "img.findBlobs().show()" - print lb + print("img.findBlobs().show()") + print(lb) if prompt_and_run().endswith('.show()'): break - print "Nothing has been shown!" - print lb + print("Nothing has been shown!") + print(lb) - print lb - print "Alright! This was tutorial 6/6." + print(lb) + print("Alright! This was tutorial 6/6.") #print "Next tutorial: ..." return @@ -443,17 +444,17 @@ def magic_tutorial(self,arg): if (arg == ""): shellclear() - print "+--------------------------------+" - print " Welcome to the SimpleCV tutorial " - print "+--------------------------------+" - print lb - print "At anytime on the SimpleCV Interactive Shell you can type tutorial," - print "then press the tab key and it will autocomplete any tutorial that" - print "is currently available." - print lb - print "Let's start off with Loading and Saving images!" - print lb - print lb + print("+--------------------------------+") + print(" Welcome to the SimpleCV tutorial ") + print("+--------------------------------+") + print(lb) + print("At anytime on the SimpleCV Interactive Shell you can type tutorial,") + print("then press the tab key and it will autocomplete any tutorial that") + print("is currently available.") + print(lb) + print("Let's start off with Loading and Saving images!") + print(lb) + print(lb) raw_input("[Press enter to continue]") tutorial_image() end_of_tutorial() @@ -462,4 +463,4 @@ def magic_tutorial(self,arg): if arg in tutorials_dict: tutorials_dict[arg]() else: - print "%s is not a tutorial!" % arg + print("%s is not a tutorial!" % arg) diff --git a/SimpleCV/Shell/__init__.py b/SimpleCV/Shell/__init__.py index b7f24e3d7..0d82f713d 100644 --- a/SimpleCV/Shell/__init__.py +++ b/SimpleCV/Shell/__init__.py @@ -1 +1,2 @@ -from Shell import * +from __future__ import absolute_import +from .Shell import * diff --git a/SimpleCV/Stream.py b/SimpleCV/Stream.py index 7c8fd4b6d..b5cec521f 100644 --- a/SimpleCV/Stream.py +++ b/SimpleCV/Stream.py @@ -59,9 +59,9 @@ def do_GET(self): self.end_headers() self.wfile.write(_jpegstreamers[port].jpgdata.getvalue() + "\r\n") lasttimeserved = time.time() - except socket.error, e: + except socket.error as e: return - except IOError, e: + except IOError as e: return count = count + 1 diff --git a/SimpleCV/Tracking/LKTracker.py b/SimpleCV/Tracking/LKTracker.py index fa3a81ddd..a4c204844 100644 --- a/SimpleCV/Tracking/LKTracker.py +++ b/SimpleCV/Tracking/LKTracker.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import np, itertools try: import cv2 @@ -102,7 +103,7 @@ def lkTracker(img, bb, ts, oldimg, **kwargs): pt = cv2.goodFeaturesToTrack(g, maxCorners = maxCorners, qualityLevel = qualityLevel, minDistance = minDistance, blockSize = blockSize) if type(pt) == type(None): - print "no points" + print("no points") track = LK(img, bb, pt) return track diff --git a/SimpleCV/Tracking/SURFTracker.py b/SimpleCV/Tracking/SURFTracker.py index f14fe7fc2..d8657c911 100644 --- a/SimpleCV/Tracking/SURFTracker.py +++ b/SimpleCV/Tracking/SURFTracker.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV.base import np, itertools try: import cv2 @@ -105,7 +106,7 @@ def surfTracker(img, bb, ts, **kwargs): skp, sd = descriptor.compute(newimg, skp) if td is None: - print "Descriptors are Empty" + print("Descriptors are Empty") return None if sd is None: diff --git a/SimpleCV/base.py b/SimpleCV/base.py index 972e31e65..bff98f11f 100644 --- a/SimpleCV/base.py +++ b/SimpleCV/base.py @@ -1,6 +1,8 @@ #!/usr/bin/python # SimpleCV system includes +from __future__ import print_function +from __future__ import absolute_import import os import sys import warnings @@ -46,7 +48,7 @@ from cStringIO import StringIO from numpy import int32 from numpy import uint8 -from EXIF import * +from .EXIF import * from pygame import gfxdraw from pickle import * @@ -195,7 +197,7 @@ def test(): This function is meant to run builtin unittests """ - print 'unit test' + print('unit test') def download_and_extract(URL): @@ -212,12 +214,12 @@ def download_and_extract(URL): path = tmpdir + "/" + filename zdata = urllib2.urlopen(URL) - print "Saving file to disk please wait...." + print("Saving file to disk please wait....") with open(path, "wb") as local_file: local_file.write(zdata.read()) zfile = zipfile.ZipFile(path) - print "Extracting zipfile" + print("Extracting zipfile") try: zfile.extractall(tmpdir) except: @@ -309,7 +311,7 @@ def read_logging_level(log_level): if log_level in levels_dict: return levels_dict[log_level] else: - print "The logging level given is not valid" + print("The logging level given is not valid") return None def get_logging_level(): @@ -324,7 +326,7 @@ def get_logging_level(): 50: "CRITICAL" } - print "The current logging level is:", levels_dict[logger.getEffectiveLevel()] + print("The current logging level is:", levels_dict[logger.getEffectiveLevel()]) def set_logging(log_level,myfilename = None): """ @@ -361,9 +363,9 @@ def set_logging(log_level,myfilename = None): fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.removeHandler(consoleHandler) #Console logging is disabled. - print "Now logging to",myfilename,"with level",log_level + print("Now logging to",myfilename,"with level",log_level) elif level: - print "Now logging with level",log_level + print("Now logging with level",log_level) logger.setLevel(level) @@ -391,37 +393,37 @@ def system(): """ try : import platform - print "System : ", platform.system() - print "OS version : ", platform.version() - print "Python version :", platform.python_version() + print("System : ", platform.system()) + print("OS version : ", platform.version()) + print("Python version :", platform.python_version()) try : from cv2 import __version__ - print "Open CV version : " + __version__ + print("Open CV version : " + __version__) except ImportError : - print "Open CV2 version : " + "2.1" + print("Open CV2 version : " + "2.1") if (PIL_ENABLED) : - print "PIL version : ", pil.VERSION + print("PIL version : ", pil.VERSION) else : - print "PIL module not installed" + print("PIL module not installed") if (ORANGE_ENABLED) : - print "Orange Version : " + orange.version + print("Orange Version : " + orange.version) else : - print "Orange module not installed" + print("Orange module not installed") try : import pygame as pg - print "PyGame Version : " + pg.__version__ + print("PyGame Version : " + pg.__version__) except ImportError: - print "PyGame module not installed" + print("PyGame module not installed") try : import pickle - print "Pickle Version : " + pickle.__version__ + print("Pickle Version : " + pickle.__version__) except : - print "Pickle module not installed" + print("Pickle module not installed") except ImportError : - print "You need to install Platform to use this function" - print "to install you can use:" - print "easy_install platform" + print("You need to install Platform to use this function") + print("to install you can use:") + print("easy_install platform") return class LazyProperty(object): diff --git a/SimpleCV/examples/arduino/CannyStream-arduino.py b/SimpleCV/examples/arduino/CannyStream-arduino.py index 1d4d458ac..11bbc00af 100644 --- a/SimpleCV/examples/arduino/CannyStream-arduino.py +++ b/SimpleCV/examples/arduino/CannyStream-arduino.py @@ -15,8 +15,9 @@ but the Arduino IDE should tell you where you should mount the Arduino from. """ +from __future__ import print_function -print __doc__ +print(__doc__) import time from SimpleCV import Camera @@ -49,7 +50,7 @@ else: t2 *= multiplier - print "t1 " + str(t1) + ", t2 " + str(t2) + ", b13 " + str(b13) + print("t1 " + str(t1) + ", t2 " + str(t2) + ", b13 " + str(b13)) img = cam.getImage().flipHorizontal() edged_img = img.edges(int(t1), int(t2)).invert().smooth() edged_img.show() diff --git a/SimpleCV/examples/detection/CannyCam.py b/SimpleCV/examples/detection/CannyCam.py index 52ee3042d..951e62fc9 100644 --- a/SimpleCV/examples/detection/CannyCam.py +++ b/SimpleCV/examples/detection/CannyCam.py @@ -5,7 +5,8 @@ max_threshold and threshhold_step values and run the program you will see it change over time ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * diff --git a/SimpleCV/examples/detection/CoinDetector.py b/SimpleCV/examples/detection/CoinDetector.py index 0bf4e477f..d11a425d9 100644 --- a/SimpleCV/examples/detection/CoinDetector.py +++ b/SimpleCV/examples/detection/CoinDetector.py @@ -12,8 +12,9 @@ quarter - 24.26 mm ''' +from __future__ import print_function -print __doc__ +print(__doc__) from SimpleCV import * # A quarter is 24.26mm or 0.955in diff --git a/SimpleCV/examples/detection/EdgeSnap.py b/SimpleCV/examples/detection/EdgeSnap.py index 806a356d5..06fc05d5d 100644 --- a/SimpleCV/examples/detection/EdgeSnap.py +++ b/SimpleCV/examples/detection/EdgeSnap.py @@ -5,7 +5,8 @@ Right-click to start the process, Detected Edge points will be shown in Red ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * diff --git a/SimpleCV/examples/detection/FeatureDetection.py b/SimpleCV/examples/detection/FeatureDetection.py index 79739c2e8..42c9dd86d 100644 --- a/SimpleCV/examples/detection/FeatureDetection.py +++ b/SimpleCV/examples/detection/FeatureDetection.py @@ -11,8 +11,9 @@ want to retrain then just right click to reset. ''' +from __future__ import print_function -print __doc__ +print(__doc__) import time from SimpleCV import Color, Image, np, Camera diff --git a/SimpleCV/examples/detection/FisherFaceRecognizer.py b/SimpleCV/examples/detection/FisherFaceRecognizer.py index f710ba1f2..1c09a095c 100644 --- a/SimpleCV/examples/detection/FisherFaceRecognizer.py +++ b/SimpleCV/examples/detection/FisherFaceRecognizer.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * import time """ @@ -20,7 +21,7 @@ def identifyGender(): w, h = f.imageSize crop_image = crop_image.resize(w, h) label, confidence = f.predict(crop_image) - print label + print(label) if label == 0: img.drawText("Female", fontsize=48) diff --git a/SimpleCV/examples/detection/Least-Squares-Circle.py b/SimpleCV/examples/detection/Least-Squares-Circle.py index bf8819a23..525eb60f6 100644 --- a/SimpleCV/examples/detection/Least-Squares-Circle.py +++ b/SimpleCV/examples/detection/Least-Squares-Circle.py @@ -5,7 +5,8 @@ The program basically takes in a shape and tries to find the size of it. ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * from scipy import optimize @@ -31,8 +32,8 @@ def f_2(c): R_2 = Ri_2.mean() residu_2 = sum((Ri_2 - R_2)**2) -print xc_2,yc_2 -print R_2 +print(xc_2,yc_2) +print(R_2) img.drawCircle((xc_2,yc_2),R_2,color=Color.RED,thickness=3) img.show() time.sleep(10) diff --git a/SimpleCV/examples/detection/MotionTracker.py b/SimpleCV/examples/detection/MotionTracker.py index ed25aa2e2..118d5e1b3 100644 --- a/SimpleCV/examples/detection/MotionTracker.py +++ b/SimpleCV/examples/detection/MotionTracker.py @@ -6,6 +6,7 @@ this are typically blobs on the images, so we do a blob search to count the number of blobs and if they exist then motion has occured ''' +from __future__ import print_function import sys, time, socket from SimpleCV import * @@ -40,7 +41,7 @@ #Draw the message on the screen if(draw_message): newImg.drawText(message_text, 5,5) - print message_text + print(message_text) lastImg = newImg # update the image diff --git a/SimpleCV/examples/detection/TemplateMatching.py b/SimpleCV/examples/detection/TemplateMatching.py index 7f5b8052b..08e0304bc 100644 --- a/SimpleCV/examples/detection/TemplateMatching.py +++ b/SimpleCV/examples/detection/TemplateMatching.py @@ -6,7 +6,8 @@ matching SimpleCV offers. If you are looking for something more complex you will probably want to look into img.findKeypoints() ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * @@ -18,7 +19,7 @@ methods = ["SQR_DIFF","SQR_DIFF_NORM","CCOEFF","CCOEFF_NORM","CCORR","CCORR_NORM"] # the various types of template matching available for m in methods: - print "current method:", m # print the method being used + print("current method:", m) # print the method being used result = Image("templatetest.png", sample=True) dl = DrawingLayer((source.width,source.height)) fs = source.findTemplate(template,threshold=t,method=m) diff --git a/SimpleCV/examples/detection/TrainFacialRecognition.py b/SimpleCV/examples/detection/TrainFacialRecognition.py index 0251dee47..2d20718af 100644 --- a/SimpleCV/examples/detection/TrainFacialRecognition.py +++ b/SimpleCV/examples/detection/TrainFacialRecognition.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * import time @@ -44,7 +45,7 @@ def getFaceSet(cam,myStr=""): # Create, train, and save the recognizer. f = FaceRecognizer() -print f.train(imgs, labels) +print(f.train(imgs, labels)) f.save(outfile) # Now show us the results disp = Display((640,480)) diff --git a/SimpleCV/examples/detection/balltrack.py b/SimpleCV/examples/detection/balltrack.py index 8b29d340d..4b9eafad9 100644 --- a/SimpleCV/examples/detection/balltrack.py +++ b/SimpleCV/examples/detection/balltrack.py @@ -7,7 +7,8 @@ The demo video can be found at: ''' -print __doc__ +from __future__ import print_function +print(__doc__) import SimpleCV @@ -19,7 +20,7 @@ if display.mouseRight: # if right mouse clicked, change mode normaldisplay = not(normaldisplay) - print "Display Mode:", "Normal" if normaldisplay else "Segmented" + print("Display Mode:", "Normal" if normaldisplay else "Segmented") img = cam.getImage().flipHorizontal() # grab image from camera dist = img.colorDistance(SimpleCV.Color.BLACK).dilate(2) # try to separate colors in image diff --git a/SimpleCV/examples/detection/barcode_reader.py b/SimpleCV/examples/detection/barcode_reader.py index 8ad8f80a7..334cec40f 100644 --- a/SimpleCV/examples/detection/barcode_reader.py +++ b/SimpleCV/examples/detection/barcode_reader.py @@ -11,8 +11,9 @@ Then line up the item in the red box and left click the mouse to tell the program to try and read the barcode ''' +from __future__ import print_function -print __doc__ +print(__doc__) import time @@ -36,8 +37,8 @@ barcode = img.findBarcode() if barcode: # if we have a barcode data = str(barcode.data) - print data - if mydict.has_key(data): + print(data) + if data in mydict: mydict[data] = mydict[data] + 1 else: mydict[data] = 1 diff --git a/SimpleCV/examples/detection/dealwithit.py b/SimpleCV/examples/detection/dealwithit.py index 6781a465a..7f069c7cf 100755 --- a/SimpleCV/examples/detection/dealwithit.py +++ b/SimpleCV/examples/detection/dealwithit.py @@ -21,7 +21,8 @@ def process_eyes(image, eyes): return (None, None, None) -def draw_glasses(image, (dx, dy, right_eye), glasses): +def draw_glasses(image, xxx_todo_changeme, glasses): + (dx, dy, right_eye) = xxx_todo_changeme rotation = 0.5*dy try: new_glasses = glasses.scale(int(2.75*dx), right_eye.height()) diff --git a/SimpleCV/examples/detection/face-substition.py b/SimpleCV/examples/detection/face-substition.py index 81cb9afc8..adbd64d23 100644 --- a/SimpleCV/examples/detection/face-substition.py +++ b/SimpleCV/examples/detection/face-substition.py @@ -5,7 +5,8 @@ All this example does is find a face and replace it with another image. The image should auto scale to match the size of the face. """ -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import Camera, Display, HaarCascade, Image diff --git a/SimpleCV/examples/detection/facetrack.py b/SimpleCV/examples/detection/facetrack.py index 7627eed48..dc2740c40 100644 --- a/SimpleCV/examples/detection/facetrack.py +++ b/SimpleCV/examples/detection/facetrack.py @@ -4,7 +4,8 @@ """ This program basically does face detection an blurs the face out. """ -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import Camera, Display, HaarCascade diff --git a/SimpleCV/examples/detection/pills.py b/SimpleCV/examples/detection/pills.py index b9dc55b3e..39cbe695a 100644 --- a/SimpleCV/examples/detection/pills.py +++ b/SimpleCV/examples/detection/pills.py @@ -3,6 +3,7 @@ it would be used in quality control in manufacturing type of application were you are verifying that the correct number of pills are present ''' +from __future__ import print_function from SimpleCV import * @@ -29,7 +30,7 @@ pillcount = len(pills) if pillcount != expected_pillcount: - print "pack at %d, %d had %d pills" % (packblobs[idx].x, packblobs[idx].y, pillcount) + print("pack at %d, %d had %d pills" % (packblobs[idx].x, packblobs[idx].y, pillcount)) i.drawText("Pills Found: " + str(pillcount), 10, 10, fontsize = 20) i.drawText("Pills Expected: " + str(expected_pillcount), 10, 30, fontsize = 20) for p in pills: diff --git a/SimpleCV/examples/detection/x-ray.py b/SimpleCV/examples/detection/x-ray.py index 55e10ce75..28f0fad8a 100644 --- a/SimpleCV/examples/detection/x-ray.py +++ b/SimpleCV/examples/detection/x-ray.py @@ -6,7 +6,8 @@ illusion of X-ray vision. It is mearly meant to show how to perform a basic image operation and overlay back onto the original image. """ -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import Camera, Display diff --git a/SimpleCV/examples/display/RenderExample.py b/SimpleCV/examples/display/RenderExample.py index 471b608f6..ecea1caa3 100644 --- a/SimpleCV/examples/display/RenderExample.py +++ b/SimpleCV/examples/display/RenderExample.py @@ -1,4 +1,5 @@ #!/usr/bin/python +from __future__ import print_function from SimpleCV import * from SimpleCV.DrawingLayer import DrawingLayer import os @@ -17,7 +18,7 @@ lineL.line(b,d,width=5) img.addDrawingLayer(lineL) temp = img.applyLayers() -print "line: %s" % temp.save(temp=True) +print("line: %s" % temp.save(temp=True)) img.clearLayers() linesL = DrawingLayer((img.width,img.height)) @@ -35,7 +36,7 @@ linesL.lines(pts,antialias=True) img.addDrawingLayer(linesL) temp = img.applyLayers() -print "lines: %s" % temp.save(temp=True) +print("lines: %s" % temp.save(temp=True)) img.clearLayers() rectTR = DrawingLayer((img.width,img.height)) @@ -50,7 +51,7 @@ rectTR.rectangle(tr,wh,color=Color.GREEN,filled=True) img.addDrawingLayer(rectTR) temp = img.applyLayers() -print "rectTR: %s" % temp.save(temp=True) +print("rectTR: %s" % temp.save(temp=True)) img.clearLayers() rectC = DrawingLayer((img.width,img.height)) @@ -65,7 +66,7 @@ rectC.centeredRectangle(cxy,wh,color=Color.GREEN,filled=True) img.addDrawingLayer(rectC) temp = img.applyLayers() -print "rectC: %s" % temp.save(temp=True) +print("rectC: %s" % temp.save(temp=True)) img.clearLayers() polyL = DrawingLayer((img.width,img.height)) @@ -84,7 +85,7 @@ polyL.polygon(pts,antialias=True,width=3,alpha=210) img.addDrawingLayer(polyL) temp = img.applyLayers() -print "poly: %s" % temp.save(temp=True) +print("poly: %s" % temp.save(temp=True)) img.clearLayers() circleL = DrawingLayer((img.width,img.height)) @@ -101,7 +102,7 @@ circleL.circle(c,r,color=Color.BLUE,alpha=172) img.addDrawingLayer(circleL) temp = img.applyLayers() -print "circle: %s" % temp.save(temp=True) +print("circle: %s" % temp.save(temp=True)) img.clearLayers() ellipseL = DrawingLayer((img.width,img.height)) @@ -116,7 +117,7 @@ ellipseL.ellipse(cxy,wh,color=Color.GREEN,filled=True) img.addDrawingLayer(ellipseL) temp = img.applyLayers() -print "ellipse: %s" % temp.save(temp=True) +print("ellipse: %s" % temp.save(temp=True)) img.clearLayers() bez = DrawingLayer((img.width,img.height)) @@ -136,7 +137,7 @@ bez.bezier(pts,30,color=Color.GREEN, alpha=128) img.addDrawingLayer(bez) temp = img.applyLayers() -print "bez: %s" % temp.save(temp=True) +print("bez: %s" % temp.save(temp=True)) img.clearLayers() words = DrawingLayer((img.width,img.height)) @@ -170,7 +171,7 @@ words.ezViewText("Can you read this better?",pos) img.addDrawingLayer(words) temp = img.applyLayers() -print "words: %s" % temp.save(temp=True) +print("words: %s" % temp.save(temp=True)) img.clearLayers() #Now lets do some layer stuff @@ -179,7 +180,7 @@ img.addDrawingLayer(bez) img.addDrawingLayer(words) temp = img.applyLayers([0,2,3]) -print "layers: %s" % temp.save(temp=True) +print("layers: %s" % temp.save(temp=True)) img.clearLayers() #now lets do some blanket alpha work @@ -192,7 +193,7 @@ img.addDrawingLayer(bez) img.addDrawingLayer(words) temp = img.applyLayers() -print "flatlayers: %s" % temp.save(temp=True) +print("flatlayers: %s" % temp.save(temp=True)) img.clearLayers() sprites = DrawingLayer((img.width,img.height)) @@ -203,5 +204,5 @@ sprites.sprite(mySprite,(0,200), rot=45,scale=1) img.addDrawingLayer(sprites) temp = img.applyLayers() -print "sprites: %s" % temp.save(temp=True) +print("sprites: %s" % temp.save(temp=True)) img.clearLayers() diff --git a/SimpleCV/examples/display/gtk-example-camera.py b/SimpleCV/examples/display/gtk-example-camera.py index 21f1513f8..5ba12f35d 100644 --- a/SimpleCV/examples/display/gtk-example-camera.py +++ b/SimpleCV/examples/display/gtk-example-camera.py @@ -9,8 +9,9 @@ The only amount of SimpleCV code is found in the process_image() function ''' +from __future__ import print_function -print __doc__ +print(__doc__) import gtk import SimpleCV diff --git a/SimpleCV/examples/display/gtk-example.py b/SimpleCV/examples/display/gtk-example.py index fd9acc650..6e8e3d68e 100644 --- a/SimpleCV/examples/display/gtk-example.py +++ b/SimpleCV/examples/display/gtk-example.py @@ -7,8 +7,9 @@ The only amount of SimpleCV code is found in the process_image() function ''' +from __future__ import print_function -print __doc__ +print(__doc__) import gtk import SimpleCV diff --git a/SimpleCV/examples/display/simplecam.py b/SimpleCV/examples/display/simplecam.py index 4dfe5d285..333598705 100644 --- a/SimpleCV/examples/display/simplecam.py +++ b/SimpleCV/examples/display/simplecam.py @@ -3,7 +3,8 @@ This program is basically the hello world in SimpleCV all it does is grab an image from the camera and display it ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * cam = Camera() diff --git a/SimpleCV/examples/kinect/kinect-motion-blur.py b/SimpleCV/examples/kinect/kinect-motion-blur.py index f44a2e777..1267ddffa 100644 --- a/SimpleCV/examples/kinect/kinect-motion-blur.py +++ b/SimpleCV/examples/kinect/kinect-motion-blur.py @@ -3,6 +3,7 @@ from operator import add from SimpleCV import * from SimpleCV.Display import Display +from functools import reduce d = Display(flags = pg.FULLSCREEN) #create video streams diff --git a/SimpleCV/examples/machine-learning/color_cluster.py b/SimpleCV/examples/machine-learning/color_cluster.py index 43e88d1d9..d14d87895 100644 --- a/SimpleCV/examples/machine-learning/color_cluster.py +++ b/SimpleCV/examples/machine-learning/color_cluster.py @@ -2,7 +2,8 @@ This program trys to extract the color pallette from an image it could be used in machine learning as a color classifier ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * disp = Display((640,528)) diff --git a/SimpleCV/examples/machine-learning/machine-learning_nuts-vs-bolts.py b/SimpleCV/examples/machine-learning/machine-learning_nuts-vs-bolts.py index f70d0bb29..17da7a511 100644 --- a/SimpleCV/examples/machine-learning/machine-learning_nuts-vs-bolts.py +++ b/SimpleCV/examples/machine-learning/machine-learning_nuts-vs-bolts.py @@ -9,7 +9,8 @@ The data set should auto download, if not you can get it from: https://github.com/downloads/sightmachine/SimpleCV/nuts_bolts.zip ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression @@ -18,12 +19,12 @@ #Download the dataset machine_learning_data_set = 'https://github.com/downloads/sightmachine/SimpleCV/nuts_bolts.zip' data_path = download_and_extract(machine_learning_data_set) -print 'Test Images Downloaded at:', data_path +print('Test Images Downloaded at:', data_path) display = Display((800,600)) #Display to show the images target_names = ['bolt', 'nut'] -print 'Loading Bolts for Training' +print('Loading Bolts for Training') bolts = ImageSet(data_path + '/data/supervised/bolts') #Load Bolts for training bolt_blobs = [b.findBlobs()[0] for b in bolts] #exact the blobs for our features tmp_data = [] #array to store data features @@ -33,7 +34,7 @@ tmp_data.append([b.area(), b.height(), b.width()]) tmp_target.append(0) -print 'Loading Nuts for Training' +print('Loading Nuts for Training') nuts = ImageSet(data_path + '/data/supervised/nuts') nut_blobs = [n.invert().findBlobs()[0] for n in nuts] for n in nut_blobs: @@ -43,12 +44,12 @@ dataset = np.array(tmp_data) targets = np.array(tmp_target) -print 'Training Machine Learning' +print('Training Machine Learning') clf = LinearSVC() clf = clf.fit(dataset, targets) clf2 = LogisticRegression().fit(dataset, targets) -print 'Running prediction on bolts now' +print('Running prediction on bolts now') untrained_bolts = ImageSet(data_path + '/data/unsupervised/bolts') unbolt_blobs = [b.findBlobs()[0] for b in untrained_bolts] for b in unbolt_blobs: @@ -58,9 +59,9 @@ img = b.image img.drawText(name) img.save(display) - print "Predicted:",name,", Guess:",probability[0], target_names[0],",", probability[1], target_names[1] + print("Predicted:",name,", Guess:",probability[0], target_names[0],",", probability[1], target_names[1]) -print 'Running prediction on nuts now' +print('Running prediction on nuts now') untrained_nuts = ImageSet(data_path + '/data/unsupervised/nuts') unnut_blobs = [n.invert().findBlobs()[0] for n in untrained_nuts] for n in unnut_blobs: @@ -70,4 +71,4 @@ img = n.image img.drawText(name) img.save(display) - print "Predicted:",name,", Guess:",probability[0], target_names[0],",", probability[1], target_names[1] + print("Predicted:",name,", Guess:",probability[0], target_names[0],",", probability[1], target_names[1]) diff --git a/SimpleCV/examples/manipulation/GreenScreen.py b/SimpleCV/examples/manipulation/GreenScreen.py index ea94a0927..c6bec9d4a 100644 --- a/SimpleCV/examples/manipulation/GreenScreen.py +++ b/SimpleCV/examples/manipulation/GreenScreen.py @@ -5,7 +5,8 @@ this should even work with a camera is the user is standing in front of a green background ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * diff --git a/SimpleCV/examples/manipulation/ImageMotionBlur.py b/SimpleCV/examples/manipulation/ImageMotionBlur.py index 720ab3421..3fb52ea65 100644 --- a/SimpleCV/examples/manipulation/ImageMotionBlur.py +++ b/SimpleCV/examples/manipulation/ImageMotionBlur.py @@ -3,7 +3,8 @@ Use Up/Down Arrow keys to change power Use Left/Right Arrow keys to change angle """ -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * import pygame diff --git a/SimpleCV/examples/manipulation/MorphologyExample.py b/SimpleCV/examples/manipulation/MorphologyExample.py index 4dea8bc49..22ca4b053 100644 --- a/SimpleCV/examples/manipulation/MorphologyExample.py +++ b/SimpleCV/examples/manipulation/MorphologyExample.py @@ -5,7 +5,8 @@ for more information see: http://en.wikipedia.org/wiki/Mathematical_morphology ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * display = Display(resolution = (800, 600)) #create a new display to draw images on diff --git a/SimpleCV/examples/manipulation/Partycam.py b/SimpleCV/examples/manipulation/Partycam.py index 0d313ddb7..1cbcc11c6 100644 --- a/SimpleCV/examples/manipulation/Partycam.py +++ b/SimpleCV/examples/manipulation/Partycam.py @@ -2,7 +2,8 @@ ''' This program basically simulates some kind of 80's music video. ''' -print __doc__ +from __future__ import print_function +print(__doc__) import sys, time, socket from SimpleCV import * diff --git a/SimpleCV/examples/manipulation/RotationExample.py b/SimpleCV/examples/manipulation/RotationExample.py index 825a7ccdf..21b822d4a 100644 --- a/SimpleCV/examples/manipulation/RotationExample.py +++ b/SimpleCV/examples/manipulation/RotationExample.py @@ -3,7 +3,8 @@ This example shows how to perform various rotations and warps on images and put back into a display. ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import * diff --git a/SimpleCV/examples/manipulation/colorsegmentation.py b/SimpleCV/examples/manipulation/colorsegmentation.py index 506e5936e..96387a4d7 100644 --- a/SimpleCV/examples/manipulation/colorsegmentation.py +++ b/SimpleCV/examples/manipulation/colorsegmentation.py @@ -2,7 +2,8 @@ ''' This program uses a Color model to try and do segmentation based on color ''' -print __doc__ +from __future__ import print_function +print(__doc__) import time from SimpleCV import * @@ -20,6 +21,6 @@ time.sleep(0.01) ticks = ticks + 1 if (int(time.time()) > t): - print str(ticks) + " fps" + print(str(ticks) + " fps") ticks = 0 t = int(time.time()) diff --git a/SimpleCV/examples/manipulation/motionblur.py b/SimpleCV/examples/manipulation/motionblur.py index da303d3c8..a2bee602e 100644 --- a/SimpleCV/examples/manipulation/motionblur.py +++ b/SimpleCV/examples/manipulation/motionblur.py @@ -3,7 +3,9 @@ This program does basic motion blurring. It averages the number of maxframes that are set using some basic image math ''' -print __doc__ +from __future__ import print_function +from functools import reduce +print(__doc__) from operator import add from SimpleCV import * diff --git a/SimpleCV/examples/manipulation/threedee.py b/SimpleCV/examples/manipulation/threedee.py index fdb2c97ff..9c3ce4c05 100644 --- a/SimpleCV/examples/manipulation/threedee.py +++ b/SimpleCV/examples/manipulation/threedee.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from __future__ import print_function import sys import os from SimpleCV import * @@ -17,8 +18,8 @@ def threedee_me(left, right, offset): output = output.crop(offset[0],y=offset[1],w=left.width-offset[0],h=left.height-offset[1]) return output -print "Taking pictures. Please move your camera slightly to its right" -print "after every picture." +print("Taking pictures. Please move your camera slightly to its right") +print("after every picture.") c = Camera() time.sleep(1) @@ -26,7 +27,7 @@ def threedee_me(left, right, offset): for i in range(5): images.append(c.getImage()) - print "Picture %d taken" % (i + 1) + print("Picture %d taken" % (i + 1)) time.sleep(1) offset = (0,0) @@ -35,6 +36,6 @@ def threedee_me(left, right, offset): left = images[i] right = images[i+1] output = threedee_me(left, right, offset) - print output.save(temp = True) + print(output.save(temp = True)) output.show() time.sleep(2) diff --git a/SimpleCV/examples/manipulation/tvexample.py b/SimpleCV/examples/manipulation/tvexample.py index 9525ef0aa..5e306d457 100644 --- a/SimpleCV/examples/manipulation/tvexample.py +++ b/SimpleCV/examples/manipulation/tvexample.py @@ -1,7 +1,8 @@ ''' This program super imposes the camera onto the television in the picture ''' -print __doc__ +from __future__ import print_function +print(__doc__) from SimpleCV import Camera, Image, Display diff --git a/SimpleCV/examples/tracking/camshift.py b/SimpleCV/examples/tracking/camshift.py index 1376639a2..67a410158 100644 --- a/SimpleCV/examples/tracking/camshift.py +++ b/SimpleCV/examples/tracking/camshift.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * # Example for CAMShift Tracker def foo(image): @@ -21,9 +22,9 @@ def camshift(): fs1.showPixelVelocityRT() img1.show() except KeyboardInterrupt: - print "Total number of frames tracked", - print fs1.trackLength() - print fs1.processTrack(foo) + print("Total number of frames tracked", end=' ') + print(fs1.trackLength()) + print(fs1.processTrack(foo)) break def getBBFromUser(cam, d): @@ -46,7 +47,7 @@ def getBBFromUser(cam, d): time.sleep(0.05) except KeyboardInterrupt: break - print p1,p2 + print(p1,p2) if not p1 or not p2: return None @@ -54,7 +55,7 @@ def getBBFromUser(cam, d): xmin = np.min((p1[0],p2[0])) ymax = np.max((p1[1],p2[1])) ymin = np.min((p1[1],p2[1])) - print xmin,ymin,xmax,ymax + print(xmin,ymin,xmax,ymax) return (xmin,ymin,xmax-xmin,ymax-ymin) camshift() diff --git a/SimpleCV/examples/tracking/lk.py b/SimpleCV/examples/tracking/lk.py index cc3d09d07..d0e31416e 100644 --- a/SimpleCV/examples/tracking/lk.py +++ b/SimpleCV/examples/tracking/lk.py @@ -1,6 +1,7 @@ """ Example of Lucas Kanade Tracker """ +from __future__ import print_function from SimpleCV import * @@ -15,7 +16,7 @@ def lktest(): img1 = cam.getImage() fs1 = img1.track("lk",fs1,img,bb1, maxCorners = 5000, qualityLevel = 0.08, winSize = (15, 15)) fs1.drawBB(color=Color.RED) - print fs1[-1].getBB() + print(fs1[-1].getBB()) img1.show() except KeyboardInterrupt: break diff --git a/SimpleCV/examples/tracking/mftrack.py b/SimpleCV/examples/tracking/mftrack.py index cd64ae04d..508b0f92d 100644 --- a/SimpleCV/examples/tracking/mftrack.py +++ b/SimpleCV/examples/tracking/mftrack.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * # Example for Media Flow Tracker. def foo(image): @@ -14,7 +15,7 @@ def mftest(): try: img1 = cam.getImage() fs1 = img1.track("mftrack",fs1,img,bb1, numM=10, numN=10, winsize=10) - print fs1[-1].shift, "shift" + print(fs1[-1].shift, "shift") fs1.drawBB(color=(255,0,0)) fs1.drawPath() img1.show() @@ -41,7 +42,7 @@ def getBBFromUser(cam, d): time.sleep(0.05) except KeyboardInterrupt: break - print p1,p2 + print(p1,p2) if not p1 or not p2: return None @@ -49,7 +50,7 @@ def getBBFromUser(cam, d): xmin = np.min((p1[0],p2[0])) ymax = np.max((p1[1],p2[1])) ymin = np.min((p1[1],p2[1])) - print xmin,ymin,xmax,ymax + print(xmin,ymin,xmax,ymax) return (xmin,ymin,xmax-xmin,ymax-ymin) mftest() diff --git a/SimpleCV/examples/tracking/surftest.py b/SimpleCV/examples/tracking/surftest.py index e585adb3c..469bb0032 100644 --- a/SimpleCV/examples/tracking/surftest.py +++ b/SimpleCV/examples/tracking/surftest.py @@ -1,6 +1,7 @@ """ Example of SURFTracker """ +from __future__ import print_function from SimpleCV import * @@ -16,7 +17,7 @@ def surftest(): fs1 = img1.track("surf",fs1,img,bb1, eps_val=0.8, dist=200, nframes=100) fs1.drawBB(color=Color.RED) fs1[-1].drawTrackerPoints() - print fs1[-1].getBB() + print(fs1[-1].getBB()) img1.show() except KeyboardInterrupt: break diff --git a/SimpleCV/examples/util/CaptureEncodeUpload.py b/SimpleCV/examples/util/CaptureEncodeUpload.py index cef27a7d9..6370e2013 100644 --- a/SimpleCV/examples/util/CaptureEncodeUpload.py +++ b/SimpleCV/examples/util/CaptureEncodeUpload.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import Camera, VideoStream, Color, Display from subprocess import call # to run command line programs """ @@ -52,6 +53,6 @@ call('ffmpeg'+params,shell=True) # construct the command line arguments for google command line params = "{0} --title \"{1}\" --tags \"{2}\" --category \"Education\" --summary \"{3}\" --access \"{4}\" ".format(outname,title,tags,summary,access) -print params +print(params) # call the command line call('google youtube post '+params,shell=True) diff --git a/SimpleCV/examples/web-based/cloudanimator/cloudanimator.py b/SimpleCV/examples/web-based/cloudanimator/cloudanimator.py index 7569d06da..ca220b363 100644 --- a/SimpleCV/examples/web-based/cloudanimator/cloudanimator.py +++ b/SimpleCV/examples/web-based/cloudanimator/cloudanimator.py @@ -5,6 +5,7 @@ # # Using jpegcam as flash webcam library: # http://code.google.com/p/jpegcam/ +from __future__ import print_function import os, tempfile, webbrowser, urllib, cherrypy, socket from SimpleCV import * from images2gif import writeGif @@ -26,7 +27,7 @@ def index(self): def update(self): #update the animation - print "update animation" + print("update animation") update.exposed = True @@ -62,7 +63,7 @@ def reset(self): self.giffile = filepath self.gifname = tmpname self.imageset = [] - print "reset animation" + print("reset animation") reset.exposed = True diff --git a/SimpleCV/examples/web-based/cloudanimator/images2gif.py b/SimpleCV/examples/web-based/cloudanimator/images2gif.py index 5c503edbd..e0ce1a4db 100644 --- a/SimpleCV/examples/web-based/cloudanimator/images2gif.py +++ b/SimpleCV/examples/web-based/cloudanimator/images2gif.py @@ -11,6 +11,7 @@ - based on gif file structure as provided by wikipedia """ +from __future__ import print_function try: import PIL @@ -201,7 +202,7 @@ def writeGif(filename, images, duration=0.1, loops=0, dither=1): # write try: n = _writeGifToFile(fp, images2, durations, loops) - print n, 'frames written' + print(n, 'frames written') finally: fp.close() diff --git a/SimpleCV/examples/web-based/cloudcam/cloudcam.py b/SimpleCV/examples/web-based/cloudcam/cloudcam.py index ebd6394a6..bf1c8c41b 100644 --- a/SimpleCV/examples/web-based/cloudcam/cloudcam.py +++ b/SimpleCV/examples/web-based/cloudcam/cloudcam.py @@ -5,6 +5,7 @@ # # Using jpegcam as flash webcam library: # http://code.google.com/p/jpegcam/ +from __future__ import print_function import os, tempfile, webbrowser, urllib, cherrypy, socket from SimpleCV import * @@ -27,8 +28,8 @@ def upload(self): outfile.close() # close the temporary file self.process(filepath) #Use SimpleCV to process the image - print "url:" + cherrypy.url() - print "socket:" + socket.gethostbyname(socket.gethostname()) + print("url:" + cherrypy.url()) + print("socket:" + socket.gethostbyname(socket.gethostname())) #~ return "http://localhost:8000/" + tmpname #return the image path via ajax request return tmpname diff --git a/SimpleCV/examples/web-based/webdisplay/flask-server.py b/SimpleCV/examples/web-based/webdisplay/flask-server.py index 1aee7e0cf..0a5e541f1 100644 --- a/SimpleCV/examples/web-based/webdisplay/flask-server.py +++ b/SimpleCV/examples/web-based/webdisplay/flask-server.py @@ -12,8 +12,9 @@ visit http://localhost:5000 ''' +from __future__ import print_function -print __doc__ +print(__doc__) from flask import Flask, jsonify, render_template, request @@ -46,8 +47,8 @@ def snapshot(): loc = 'static/' + tf.name.split('/')[-1] tf.close() img.save(loc) - print "location",loc - print "json", json.dumps(loc) + print("location",loc) + print("json", json.dumps(loc)) return json.dumps(loc) if __name__ == '__main__': diff --git a/SimpleCV/tests/ShapeContext/test_c.py b/SimpleCV/tests/ShapeContext/test_c.py index d98287664..0edc51101 100644 --- a/SimpleCV/tests/ShapeContext/test_c.py +++ b/SimpleCV/tests/ShapeContext/test_c.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * color = Color() @@ -29,15 +30,15 @@ fname = "SanityCheckExample"+str(i)+".png" i = i+ 1 result.save(fname) - print "------------------------------" - print metric + print("------------------------------") + print(metric) confuse.append(metric) -print confuse +print(confuse) confuse = np.array(confuse) -print confuse.reshape(4,4) +print(confuse.reshape(4,4)) time.sleep(10) diff --git a/SimpleCV/tests/ShapeContext/test_multi.py b/SimpleCV/tests/ShapeContext/test_multi.py index 61f962526..ced029a7d 100644 --- a/SimpleCV/tests/ShapeContext/test_multi.py +++ b/SimpleCV/tests/ShapeContext/test_multi.py @@ -1,3 +1,4 @@ +from __future__ import print_function from SimpleCV import * import string import pickle @@ -17,7 +18,7 @@ for i in iset: names.append(i.filename) -print names +print(names) names = names[0:subset] scc = None @@ -29,20 +30,20 @@ scc = ShapeContextClassifier(iset,names) #this needs to be pickled. pickle.dump(scc, open( fname, "wb" ) ) -print "--------------------------" -print "--------------------------" -print "Performing Analysis!" -print "--------------------------" -print "--------------------------" +print("--------------------------") +print("--------------------------") +print("Performing Analysis!") +print("--------------------------") +print("--------------------------") classifications = [] i = 0 for test in testset: - print "--------------------------" + print("--------------------------") best, value, result = scc.classify(test) - print "Total points in result " + str(len(scc.ptMap[best])) - print "Testing: " + test.filename - print "Best Result: " + best + print("Total points in result " + str(len(scc.ptMap[best]))) + print("Testing: " + test.filename) + print("Best Result: " + best) words = string.split(best,'/') words2 = string.split(test.filename,'/') test = test.resize(h=400) @@ -61,5 +62,5 @@ i = i + 1 matchImg.save(fname) classifications.append((test.filename,result)) - print result + print(result) pickle.dump(classifications, open( "classifications.pkl", "wb" ) ) diff --git a/SimpleCV/tests/YCrCbtests.py b/SimpleCV/tests/YCrCbtests.py index b4738dad8..fc960e6b5 100644 --- a/SimpleCV/tests/YCrCbtests.py +++ b/SimpleCV/tests/YCrCbtests.py @@ -1,56 +1,57 @@ +from __future__ import print_function from SimpleCV import * img = Image('lenna') img1 = img.toYCrCb() if (img1.isYCrCb()): - print "Converted to YCrCb\n" + print("Converted to YCrCb\n") img1 = img.toBGR() img2 = img1.toYCrCb() if (img2.isYCrCb()): - print "Converted BGR to YCrCb\n" + print("Converted BGR to YCrCb\n") img1 = img.toHLS() img2 = img1.toYCrCb() if (img2.isYCrCb()): - print "Converted HLS to YCrCb\n" + print("Converted HLS to YCrCb\n") img1 = img.toHSV() img2 = img1.toYCrCb() if (img2.isYCrCb()): - print "Converted HSV to YCrCb\n" + print("Converted HSV to YCrCb\n") img1 = img.toXYZ() img2 = img1.toYCrCb() if (img2.isYCrCb()): - print "Converted XYZ to YCrCb\n" + print("Converted XYZ to YCrCb\n") img1 = img.toYCrCb() img2 = img1.toRGB() if (img2.isYCrCb()): - print "Converted from YCrCb to RGB\n" + print("Converted from YCrCb to RGB\n") img1 = img.toYCrCb() img2 = img1.toBGR() if (img2.isRGB()): - print "Converted from YCrCb to RGB\n" + print("Converted from YCrCb to RGB\n") img1 = img.toYCrCb() img2 = img1.toHLS() if (img2.isHLS()): - print "Converted from YCrCb to HLS\n" + print("Converted from YCrCb to HLS\n") img1 = img.toYCrCb() img2 = img1.toHSV() if (img2.isHSV()): - print "Converted from YCrCb to HSV\n" + print("Converted from YCrCb to HSV\n") img1 = img.toYCrCb() img2 = img1.toXYZ() if (img2.isXYZ()): - print "Converted from YCrCb to XYZ\n" + print("Converted from YCrCb to XYZ\n") img1 = img.toGray() img2 = img1.toGray() if (img2.isGray()): - print "Converted from Gray to Gray\n" + print("Converted from Gray to Gray\n") diff --git a/SimpleCV/tests/test_cameras.py b/SimpleCV/tests/test_cameras.py index 7e7440b53..f76d741fa 100644 --- a/SimpleCV/tests/test_cameras.py +++ b/SimpleCV/tests/test_cameras.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import os, sys from SimpleCV import * from nose.tools import with_setup @@ -14,7 +15,7 @@ def test_virtual_camera_constructor(): props = mycam.getAllProperties() for i in props.keys(): - print str(i) + ": " + str(props[i]) + "\n" + print(str(i) + ": " + str(props[i]) + "\n") pass diff --git a/SimpleCV/tests/test_display.py b/SimpleCV/tests/test_display.py index d28648775..d5deb3d53 100644 --- a/SimpleCV/tests/test_display.py +++ b/SimpleCV/tests/test_display.py @@ -1,3 +1,4 @@ +from __future__ import print_function # /usr/bin/python # To run this test you need python nose tools installed # Run test just use: @@ -77,7 +78,7 @@ def imgDiffs(test_imgs,name_stem,tolerance,path): diff = (lhs-rhs) val = np.average(diff.getNumpy()) if( val > tolerance ): - print val + print(val) return True return False @@ -920,7 +921,8 @@ def test_applyBinaryMask(): def test_applyPixelFunc(): img = Image(logo) - def myFunc((r,g,b)): + def myFunc(xxx_todo_changeme): + (r,g,b) = xxx_todo_changeme return( (b,g,r) ) img = img.applyPixelFunction(myFunc) @@ -1284,7 +1286,7 @@ def test_keypoint_match(): fs0 = match0.findKeypointMatch(template)#test zero fs1 = match1.findKeypointMatch(template,quality=300.00,minDist=0.5,minMatch=0.2) fs3 = match3.findKeypointMatch(template,quality=300.00,minDist=0.5,minMatch=0.2) - print "This should fail" + print("This should fail") fs2 = match2.findKeypointMatch(template,quality=500.00,minDist=0.2,minMatch=0.1) if( fs0 is not None and fs1 is not None and fs2 is None and fs3 is not None): fs0.draw() @@ -1619,7 +1621,7 @@ def test_minrect_blobs(): results = [] for i in range(-10,10): ang = float(i*18.00) - print ang + print(ang) t = img.rotate(ang) b = t.findBlobs(threshval=128) b[-1].drawMinRect(color=Color.RED,width=5) diff --git a/SimpleCV/tests/test_optional.py b/SimpleCV/tests/test_optional.py index 3c0af7ff2..0d9398832 100644 --- a/SimpleCV/tests/test_optional.py +++ b/SimpleCV/tests/test_optional.py @@ -1,3 +1,4 @@ +from __future__ import print_function # /usr/bin/python # To run this test you need python nose tools installed # Run test just use: @@ -88,7 +89,7 @@ def test_detection_ocr(): img = Image(ocrimage) foundtext = img.readText() - print foundtext + print(foundtext) if(len(foundtext) <= 1): assert False else: diff --git a/SimpleCV/tests/test_stereovision.py b/SimpleCV/tests/test_stereovision.py index 11c2201b0..2ef57e747 100644 --- a/SimpleCV/tests/test_stereovision.py +++ b/SimpleCV/tests/test_stereovision.py @@ -1,3 +1,4 @@ +from __future__ import print_function # /usr/bin/python # To run this test you need python nose tools installed # Run test just use: @@ -51,7 +52,7 @@ def imgDiffs(test_imgs,name_stem,tolerance,path): diff = (lhs-rhs) val = np.average(diff.getNumpy()) if( val > tolerance ): - print val + print(val) return True return False diff --git a/SimpleCV/tests/test_vimba.py b/SimpleCV/tests/test_vimba.py index 56c85fb46..098dfdd45 100644 --- a/SimpleCV/tests/test_vimba.py +++ b/SimpleCV/tests/test_vimba.py @@ -1,3 +1,4 @@ +from __future__ import print_function import numpy as np import cv2 import time @@ -5,58 +6,58 @@ def printPrettyHeader(msg): - print "*"*80 + "\n* %s *\n" % msg + "*"*80 + print("*"*80 + "\n* %s *\n" % msg + "*"*80) def _getProperty(c): printPrettyHeader("Test getProperty") prop = "ExposureMode" - print "%s=%s" % (prop, c.getProperty(prop)) + print("%s=%s" % (prop, c.getProperty(prop))) def _getAllProperties(c): printPrettyHeader("Test getAllProperties") allprops = c.getAllProperties() for k in sorted(allprops.iterkeys()) : - print "%s=%s" % (k,allprops[k]) + print("%s=%s" % (k,allprops[k])) def _setProperty(c): printPrettyHeader("Test setProperty (toggle AcquisitionMode)") prop = "AcquisitionMode" val = c.getProperty(prop) - print "BEFORE: %s=%s" % (prop, val) + print("BEFORE: %s=%s" % (prop, val)) newval = "Continuous" if val == "SingleFrame" else "SingleFrame" - print "newval=%s" % newval + print("newval=%s" % newval) c.setProperty(prop, "Continuous") time.sleep(0.2) val = c.getProperty(prop) - print "AFTER: %s=%s" % (prop, val) + print("AFTER: %s=%s" % (prop, val)) def _setupASyncMode(c): printPrettyHeader("Test setupASyncMode (toggle TriggerSource)") prop1 = 'AcquisitionMode' prop2 = 'TriggerSource' - print 'BEFORE: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2)) + print('BEFORE: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2))) c.setupASyncMode() - print 'AFTER: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2)) + print('AFTER: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2))) def _setupSyncMode(c): printPrettyHeader("Test setupSyncMode (toggle TriggerSource)") prop1 = 'AcquisitionMode' prop2 = 'TriggerSource' - print 'BEFORE: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2)) + print('BEFORE: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2))) c.setupSyncMode() - print 'AFTER: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2)) + print('AFTER: %s=%s, %s=%s' % (prop1, c.getProperty(prop1), prop2, c.getProperty(prop2))) def _getImage(c): printPrettyHeader("Test getImage") img = c.getImage() img.save("test_getImage_scv.png") - print "test_getImage_scv.png saved" + print("test_getImage_scv.png saved") def _runCommand(c): printPrettyHeader("Test runCommand") @@ -75,14 +76,14 @@ def _runCommand(c): rgb = cv2.cvtColor(moreUsefulImgData, cv2.COLOR_BAYER_RG2RGB) vimbacam.endCapture() cv2.imwrite('test_runCommand.png', rgb) - print "test_runCommand.png saved" + print("test_runCommand.png saved") def _listAllCameras(c): printPrettyHeader("Test listAllCameras") l = c.listAllCameras() for i in l: - print 'Camera Id=%s' % i.cameraIdString + print('Camera Id=%s' % i.cameraIdString) def test_all(): c = VimbaCamera() diff --git a/SimpleCV/tests/test_vimba_async.py b/SimpleCV/tests/test_vimba_async.py index 40afc027f..8574d9244 100644 --- a/SimpleCV/tests/test_vimba_async.py +++ b/SimpleCV/tests/test_vimba_async.py @@ -1,3 +1,4 @@ +from __future__ import print_function import numpy as np import cv2 import time @@ -6,7 +7,7 @@ from pymba import Vimba def printPrettyHeader(msg): - print "*"*80 + "\n* %s *\n" % msg + "*"*80 + print("*"*80 + "\n* %s *\n" % msg + "*"*80) def _takeShots(cam, numPics, filename): start = time.time() @@ -16,7 +17,7 @@ def _takeShots(cam, numPics, filename): img.save("%s_%d.png" % (filename, i)) end = time.time() elapsed = end - start - print "Took %f seconds" % elapsed + print("Took %f seconds" % elapsed) ''' def test_AVT_threaded_getImage(): diff --git a/SimpleCV/tests/test_vimba_manyshots.py b/SimpleCV/tests/test_vimba_manyshots.py index 9661750a0..5d6e7c514 100644 --- a/SimpleCV/tests/test_vimba_manyshots.py +++ b/SimpleCV/tests/test_vimba_manyshots.py @@ -1,3 +1,4 @@ +from __future__ import print_function import numpy as np import cv2 import time @@ -8,7 +9,7 @@ #time.sleep(0.2) def printPrettyHeader(msg): - print "*"*80 + "\n* %s *\n" % msg + "*"*80 + print("*"*80 + "\n* %s *\n" % msg + "*"*80) def _takeShots(cam, numPics, filename): start = time.time() @@ -18,17 +19,17 @@ def _takeShots(cam, numPics, filename): img.save("%s_%d.png" % (filename, i)) end = time.time() elapsed = end - start - print "Took %f seconds" % elapsed + print("Took %f seconds" % elapsed) def _takeManyVimbaShots(idx): c = VimbaCamera() - print "_takeManyVimbaShots %d" % idx + print("_takeManyVimbaShots %d" % idx) _takeShots(c, 10, "cam_vimba%d" % idx) def _takeAVTManyShots(idx): c = AVTCamera() - print "_takeAVTManyShots %d" % idx + print("_takeAVTManyShots %d" % idx) _takeShots(c, 10, "cam_avtnative%d" % idx) diff --git a/SimpleCV/tests/tests.py b/SimpleCV/tests/tests.py index b90455238..abd80c7ab 100644 --- a/SimpleCV/tests/tests.py +++ b/SimpleCV/tests/tests.py @@ -1,3 +1,4 @@ +from __future__ import print_function # /usr/bin/python # To run this test you need python nose tools installed # Run test just use: @@ -71,7 +72,7 @@ def imgDiffs(test_imgs,name_stem,tolerance,path): diff = (lhs-rhs) val = np.average(diff.getNumpy()) if( val > tolerance ): - print val + print(val) return True return False @@ -986,7 +987,7 @@ def test_image_crop(): failed = False for img in tests: if( img is None or img.width != 40 and img.height != 40 ): - print "FAILED CROP TEST " + str(i) + " " + str(img) + print("FAILED CROP TEST " + str(i) + " " + str(img)) failed = True i = i + 1 @@ -1388,7 +1389,7 @@ def test_detection_ocr(): img = Image(ocrimage) foundtext = img.readText() - print foundtext + print(foundtext) if(len(foundtext) <= 1): assert False else: @@ -1532,7 +1533,8 @@ def test_applyBinaryMask(): def test_applyPixelFunc(): img = Image(logo) - def myFunc((r,g,b)): + def myFunc(xxx_todo_changeme): + (r,g,b) = xxx_todo_changeme return( (b,g,r) ) img = img.applyPixelFunction(myFunc) @@ -1811,12 +1813,12 @@ def test_findKeypoints(): flavors = ['SURF','STAR','FAST','MSER','ORB','BRISK','FREAK','SIFT','Dense'] for flavor in flavors: try: - print "trying to find " + flavor + " keypoints." + print("trying to find " + flavor + " keypoints.") kp = img.findKeypoints(flavor=flavor) except: continue if( kp is not None ): - print "Found: " + str(len(kp)) + print("Found: " + str(len(kp))) for k in kp: k.getObject() k.descriptor() @@ -1836,7 +1838,7 @@ def test_findKeypoints(): k.crop() kp.draw() else: - print "Found None." + print("Found None.") results = [img] name_stem = "test_findKeypoints" #~ perform_diff(results,name_stem) @@ -1949,7 +1951,7 @@ def test_keypoint_match(): fs0 = match0.findKeypointMatch(template)#test zero fs1 = match1.findKeypointMatch(template,quality=300.00,minDist=0.5,minMatch=0.2) fs3 = match3.findKeypointMatch(template,quality=300.00,minDist=0.5,minMatch=0.2) - print "This should fail" + print("This should fail") fs2 = match2.findKeypointMatch(template,quality=500.00,minDist=0.2,minMatch=0.1) if( fs0 is not None and fs1 is not None and fs2 is None and fs3 is not None): fs0.draw() @@ -2188,15 +2190,15 @@ def test_detection_spatial_relationships(): feats = [blobFS,lineFS,cornFS,tempFS,moveFS] for f in feats: - print str(len(f)) + print(str(len(f))) for f in feats: for g in feats: sample = f[0] sample2 = f[1] - print type(f[0]) - print type(g[0]) + print(type(f[0])) + print(type(g[0])) g.above(sample) g.below(sample) @@ -2243,8 +2245,8 @@ def test_get_raw_dft(): raw1[0].height != img.height or raw3[0].height != img.height or raw3[0].width != img.width or - raw1[0].depth != 64L or - raw3[0].depth != 64L or + raw1[0].depth != 64 or + raw3[0].depth != 64 or raw3[0].channels != 2 or raw3[0].channels != 2 ): assert False @@ -2725,7 +2727,7 @@ def test_minrect_blobs(): results = [] for i in range(-10,10): ang = float(i*18.00) - print ang + print(ang) t = img.rotate(ang) b = t.findBlobs(threshval=128) b[-1].drawMinRect(color=Color.RED,width=5) @@ -2978,7 +2980,7 @@ def test_findKeypoints_all(): img = Image(testimage2) methods = ["ORB", "SIFT", "SURF","FAST", "STAR", "MSER", "Dense"] for i in methods : - print i + print(i) try: kp = img.findKeypoints(flavor = i) except: @@ -3446,7 +3448,7 @@ def subtest(data,effect): i = 0 for d in data: e = effect(d) - print (i,e) + print((i,e)) i = i + 1 if( first != e ): broke = True @@ -3926,7 +3928,7 @@ def test_smartRotate(): st2 = img.rotate(27,fixed = False).resize(500,500) diff = np.average((st1-st2).getNumpy()) if (diff > 1.7): - print diff + print(diff) assert False else: assert True diff --git a/SimpleCV/tests/vcamera_tests.py b/SimpleCV/tests/vcamera_tests.py index 8895cef01..31b8e7cfe 100644 --- a/SimpleCV/tests/vcamera_tests.py +++ b/SimpleCV/tests/vcamera_tests.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import os, sys from SimpleCV import * from nose.tools import with_setup @@ -35,7 +36,7 @@ def test_camera_constructor(): props = mycam.getAllProperties() for i in props.keys(): - print str(i) + ": " + str(props[i]) + "\n" + print(str(i) + ": " + str(props[i]) + "\n") pass diff --git a/SimpleCV/tools/Calibrate.py b/SimpleCV/tools/Calibrate.py index 96eb6f431..5f4147f94 100644 --- a/SimpleCV/tools/Calibrate.py +++ b/SimpleCV/tools/Calibrate.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import webbrowser, sys, time, random from SimpleCV import Camera, Image, JpegStreamer, Color from SimpleCV.Display import Display @@ -86,7 +87,7 @@ def verticalTilt(cb): #radio between the 0, 1 and 2,3 point pairs return distance_ratio def introMessage(): - print """ + print(""" This tool will help you calibrate your camera to help remove the effects of lens distortion and give you more accurate measurement. You will need: @@ -97,7 +98,7 @@ def introMessage(): To begin, please put your chessboard close to the camera so the long side is horizontal and it fill most of the screen. Keep it parallel to the camera so it appears within the rectangle. - """ + """) def findLargeFlat(cb, i, calibration_set, dims): drawline(i, (10, 10), (i.width - 10, 10)) diff --git a/scripts/install/mac/findmods.py b/scripts/install/mac/findmods.py index e2bded277..606f73182 100644 --- a/scripts/install/mac/findmods.py +++ b/scripts/install/mac/findmods.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function from SimpleCV import * import re from types import NoneType @@ -27,4 +28,4 @@ for egg in easy_installed_pkgs.keys(): - print easy_installed_path + "/" + egg + print(easy_installed_path + "/" + egg) diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_async.py b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_async.py index 45f41fa5f..1a7e0ff17 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_async.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_async.py @@ -1,33 +1,34 @@ -#!/usr/bin/env python -import freenect -import cv -import frame_convert - -cv.NamedWindow('Depth') -cv.NamedWindow('RGB') -keep_running = True - - -def display_depth(dev, data, timestamp): - global keep_running - cv.ShowImage('Depth', frame_convert.pretty_depth_cv(data)) - if cv.WaitKey(10) == 27: - keep_running = False - - -def display_rgb(dev, data, timestamp): - global keep_running - cv.ShowImage('RGB', frame_convert.video_cv(data)) - if cv.WaitKey(10) == 27: - keep_running = False - - -def body(*args): - if not keep_running: - raise freenect.Kill - - -print('Press ESC in window to stop') -freenect.runloop(depth=display_depth, - video=display_rgb, - body=body) +#!/usr/bin/env python +from __future__ import print_function +import freenect +import cv +import frame_convert + +cv.NamedWindow('Depth') +cv.NamedWindow('RGB') +keep_running = True + + +def display_depth(dev, data, timestamp): + global keep_running + cv.ShowImage('Depth', frame_convert.pretty_depth_cv(data)) + if cv.WaitKey(10) == 27: + keep_running = False + + +def display_rgb(dev, data, timestamp): + global keep_running + cv.ShowImage('RGB', frame_convert.video_cv(data)) + if cv.WaitKey(10) == 27: + keep_running = False + + +def body(*args): + if not keep_running: + raise freenect.Kill + + +print('Press ESC in window to stop') +freenect.runloop(depth=display_depth, + video=display_rgb, + body=body) diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync.py b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync.py index a684c5e72..120720f6a 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync.py @@ -1,23 +1,24 @@ -#!/usr/bin/env python -import freenect -import cv -import frame_convert - -cv.NamedWindow('Depth') -cv.NamedWindow('Video') -print('Press ESC in window to stop') - - -def get_depth(): - return frame_convert.pretty_depth_cv(freenect.sync_get_depth()[0]) - - -def get_video(): - return frame_convert.video_cv(freenect.sync_get_video()[0]) - - -while 1: - cv.ShowImage('Depth', get_depth()) - cv.ShowImage('Video', get_video()) - if cv.WaitKey(10) == 27: - break +#!/usr/bin/env python +from __future__ import print_function +import freenect +import cv +import frame_convert + +cv.NamedWindow('Depth') +cv.NamedWindow('Video') +print('Press ESC in window to stop') + + +def get_depth(): + return frame_convert.pretty_depth_cv(freenect.sync_get_depth()[0]) + + +def get_video(): + return frame_convert.video_cv(freenect.sync_get_video()[0]) + + +while 1: + cv.ShowImage('Depth', get_depth()) + cv.ShowImage('Video', get_video()) + if cv.WaitKey(10) == 27: + break diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync_multi.py b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync_multi.py index 51de85d4e..3480d6ea5 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync_multi.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_sync_multi.py @@ -1,39 +1,40 @@ -#!/usr/bin/env python -"""This goes through each kinect on your system, grabs one frame and -displays it. Uncomment the commented line to shut down after each frame -if your system can't handle it (will get very low FPS but it should work). -This will keep trying indeces until it finds one that doesn't work, then it -starts from 0. -""" -import freenect -import cv -import frame_convert - -cv.NamedWindow('Depth') -cv.NamedWindow('Video') -ind = 0 -print('%s\nPress ESC to stop' % __doc__) - - -def get_depth(ind): - return frame_convert.pretty_depth_cv(freenect.sync_get_depth(ind)[0]) - - -def get_video(ind): - return frame_convert.video_cv(freenect.sync_get_video(ind)[0]) - - -while 1: - print(ind) - try: - depth = get_depth(ind) - video = get_video(ind) - except TypeError: - ind = 0 - continue - ind += 1 - cv.ShowImage('Depth', depth) - cv.ShowImage('Video', video) - if cv.WaitKey(10) == 27: - break - #freenect.sync_stop() # NOTE: Uncomment if your machine can't handle it +#!/usr/bin/env python +"""This goes through each kinect on your system, grabs one frame and +displays it. Uncomment the commented line to shut down after each frame +if your system can't handle it (will get very low FPS but it should work). +This will keep trying indeces until it finds one that doesn't work, then it +starts from 0. +""" +from __future__ import print_function +import freenect +import cv +import frame_convert + +cv.NamedWindow('Depth') +cv.NamedWindow('Video') +ind = 0 +print('%s\nPress ESC to stop' % __doc__) + + +def get_depth(ind): + return frame_convert.pretty_depth_cv(freenect.sync_get_depth(ind)[0]) + + +def get_video(ind): + return frame_convert.video_cv(freenect.sync_get_video(ind)[0]) + + +while 1: + print(ind) + try: + depth = get_depth(ind) + video = get_video(ind) + except TypeError: + ind = 0 + continue + ind += 1 + cv.ShowImage('Depth', depth) + cv.ShowImage('Video', video) + if cv.WaitKey(10) == 27: + break + #freenect.sync_stop() # NOTE: Uncomment if your machine can't handle it diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_thresh_sweep.py b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_thresh_sweep.py index ec85246b2..fdea1b629 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_thresh_sweep.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_thresh_sweep.py @@ -1,32 +1,33 @@ -#!/usr/bin/env python -"""Sweeps throught the depth image showing 100 range at a time""" -import freenect -import cv -import numpy as np -import time - -cv.NamedWindow('Depth') - - -def disp_thresh(lower, upper): - depth, timestamp = freenect.sync_get_depth() - depth = 255 * np.logical_and(depth > lower, depth < upper) - depth = depth.astype(np.uint8) - image = cv.CreateImageHeader((depth.shape[1], depth.shape[0]), - cv.IPL_DEPTH_8U, - 1) - cv.SetData(image, depth.tostring(), - depth.dtype.itemsize * depth.shape[1]) - cv.ShowImage('Depth', image) - cv.WaitKey(10) - - -lower = 0 -upper = 100 -max_upper = 2048 -while upper < max_upper: - print('%d < depth < %d' % (lower, upper)) - disp_thresh(lower, upper) - time.sleep(.1) - lower += 20 - upper += 20 +#!/usr/bin/env python +"""Sweeps throught the depth image showing 100 range at a time""" +from __future__ import print_function +import freenect +import cv +import numpy as np +import time + +cv.NamedWindow('Depth') + + +def disp_thresh(lower, upper): + depth, timestamp = freenect.sync_get_depth() + depth = 255 * np.logical_and(depth > lower, depth < upper) + depth = depth.astype(np.uint8) + image = cv.CreateImageHeader((depth.shape[1], depth.shape[0]), + cv.IPL_DEPTH_8U, + 1) + cv.SetData(image, depth.tostring(), + depth.dtype.itemsize * depth.shape[1]) + cv.ShowImage('Depth', image) + cv.WaitKey(10) + + +lower = 0 +upper = 100 +max_upper = 2048 +while upper < max_upper: + print('%d < depth < %d' % (lower, upper)) + disp_thresh(lower, upper) + time.sleep(.1) + lower += 20 + upper += 20 diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_threshold.py b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_threshold.py index d3f6e8266..f7d9a275c 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_cv_threshold.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_cv_threshold.py @@ -1,54 +1,55 @@ -#!/usr/bin/env python -import freenect -import cv -import frame_convert -import numpy as np - - -threshold = 100 -current_depth = 0 - - -def change_threshold(value): - global threshold - threshold = value - - -def change_depth(value): - global current_depth - current_depth = value - - -def show_depth(): - global threshold - global current_depth - - depth, timestamp = freenect.sync_get_depth() - depth = 255 * np.logical_and(depth >= current_depth - threshold, - depth <= current_depth + threshold) - depth = depth.astype(np.uint8) - image = cv.CreateImageHeader((depth.shape[1], depth.shape[0]), - cv.IPL_DEPTH_8U, - 1) - cv.SetData(image, depth.tostring(), - depth.dtype.itemsize * depth.shape[1]) - cv.ShowImage('Depth', image) - - -def show_video(): - cv.ShowImage('Video', frame_convert.video_cv(freenect.sync_get_video()[0])) - - -cv.NamedWindow('Depth') -cv.NamedWindow('Video') -cv.CreateTrackbar('threshold', 'Depth', threshold, 500, change_threshold) -cv.CreateTrackbar('depth', 'Depth', current_depth, 2048, change_depth) - -print('Press ESC in window to stop') - - -while 1: - show_depth() - show_video() - if cv.WaitKey(10) == 27: - break +#!/usr/bin/env python +from __future__ import print_function +import freenect +import cv +import frame_convert +import numpy as np + + +threshold = 100 +current_depth = 0 + + +def change_threshold(value): + global threshold + threshold = value + + +def change_depth(value): + global current_depth + current_depth = value + + +def show_depth(): + global threshold + global current_depth + + depth, timestamp = freenect.sync_get_depth() + depth = 255 * np.logical_and(depth >= current_depth - threshold, + depth <= current_depth + threshold) + depth = depth.astype(np.uint8) + image = cv.CreateImageHeader((depth.shape[1], depth.shape[0]), + cv.IPL_DEPTH_8U, + 1) + cv.SetData(image, depth.tostring(), + depth.dtype.itemsize * depth.shape[1]) + cv.ShowImage('Depth', image) + + +def show_video(): + cv.ShowImage('Video', frame_convert.video_cv(freenect.sync_get_video()[0])) + + +cv.NamedWindow('Depth') +cv.NamedWindow('Video') +cv.CreateTrackbar('threshold', 'Depth', threshold, 500, change_threshold) +cv.CreateTrackbar('depth', 'Depth', current_depth, 2048, change_depth) + +print('Press ESC in window to stop') + + +while 1: + show_depth() + show_video() + if cv.WaitKey(10) == 27: + break diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_mp_async.py b/scripts/install/win/OpenKinect/freenect-examples/demo_mp_async.py index 069d787f5..bce38e618 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_mp_async.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_mp_async.py @@ -1,49 +1,50 @@ -#!/usr/bin/env python -import freenect -import matplotlib.pyplot as mp -import signal -import frame_convert - -mp.ion() -image_rgb = None -image_depth = None -keep_running = True - - -def display_depth(dev, data, timestamp): - global image_depth - data = frame_convert.pretty_depth(data) - mp.gray() - mp.figure(1) - if image_depth: - image_depth.set_data(data) - else: - image_depth = mp.imshow(data, interpolation='nearest', animated=True) - mp.draw() - - -def display_rgb(dev, data, timestamp): - global image_rgb - mp.figure(2) - if image_rgb: - image_rgb.set_data(data) - else: - image_rgb = mp.imshow(data, interpolation='nearest', animated=True) - mp.draw() - - -def body(*args): - if not keep_running: - raise freenect.Kill - - -def handler(signum, frame): - global keep_running - keep_running = False - - -print('Press Ctrl-C in terminal to stop') -signal.signal(signal.SIGINT, handler) -freenect.runloop(depth=display_depth, - video=display_rgb, - body=body) +#!/usr/bin/env python +from __future__ import print_function +import freenect +import matplotlib.pyplot as mp +import signal +import frame_convert + +mp.ion() +image_rgb = None +image_depth = None +keep_running = True + + +def display_depth(dev, data, timestamp): + global image_depth + data = frame_convert.pretty_depth(data) + mp.gray() + mp.figure(1) + if image_depth: + image_depth.set_data(data) + else: + image_depth = mp.imshow(data, interpolation='nearest', animated=True) + mp.draw() + + +def display_rgb(dev, data, timestamp): + global image_rgb + mp.figure(2) + if image_rgb: + image_rgb.set_data(data) + else: + image_rgb = mp.imshow(data, interpolation='nearest', animated=True) + mp.draw() + + +def body(*args): + if not keep_running: + raise freenect.Kill + + +def handler(signum, frame): + global keep_running + keep_running = False + + +print('Press Ctrl-C in terminal to stop') +signal.signal(signal.SIGINT, handler) +freenect.runloop(depth=display_depth, + video=display_rgb, + body=body) diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_mp_sync.py b/scripts/install/win/OpenKinect/freenect-examples/demo_mp_sync.py index 393f34521..a0db7a455 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_mp_sync.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_mp_sync.py @@ -1,39 +1,40 @@ -#!/usr/bin/env python -import freenect -import matplotlib.pyplot as mp -import frame_convert -import signal - -keep_running = True - - -def get_depth(): - return frame_convert.pretty_depth(freenect.sync_get_depth()[0]) - - -def get_video(): - return freenect.sync_get_video()[0] - - -def handler(signum, frame): - """Sets up the kill handler, catches SIGINT""" - global keep_running - keep_running = False - - -mp.ion() -mp.gray() -mp.figure(1) -image_depth = mp.imshow(get_depth(), interpolation='nearest', animated=True) -mp.figure(2) -image_rgb = mp.imshow(get_video(), interpolation='nearest', animated=True) -print('Press Ctrl-C in terminal to stop') -signal.signal(signal.SIGINT, handler) - -while keep_running: - mp.figure(1) - image_depth.set_data(get_depth()) - mp.figure(2) - image_rgb.set_data(get_video()) - mp.draw() - mp.waitforbuttonpress(0.01) +#!/usr/bin/env python +from __future__ import print_function +import freenect +import matplotlib.pyplot as mp +import frame_convert +import signal + +keep_running = True + + +def get_depth(): + return frame_convert.pretty_depth(freenect.sync_get_depth()[0]) + + +def get_video(): + return freenect.sync_get_video()[0] + + +def handler(signum, frame): + """Sets up the kill handler, catches SIGINT""" + global keep_running + keep_running = False + + +mp.ion() +mp.gray() +mp.figure(1) +image_depth = mp.imshow(get_depth(), interpolation='nearest', animated=True) +mp.figure(2) +image_rgb = mp.imshow(get_video(), interpolation='nearest', animated=True) +print('Press Ctrl-C in terminal to stop') +signal.signal(signal.SIGINT, handler) + +while keep_running: + mp.figure(1) + image_depth.set_data(get_depth()) + mp.figure(2) + image_rgb.set_data(get_video()) + mp.draw() + mp.waitforbuttonpress(0.01) diff --git a/scripts/install/win/OpenKinect/freenect-examples/demo_tilt.py b/scripts/install/win/OpenKinect/freenect-examples/demo_tilt.py index ede190436..9f6e67d3b 100644 --- a/scripts/install/win/OpenKinect/freenect-examples/demo_tilt.py +++ b/scripts/install/win/OpenKinect/freenect-examples/demo_tilt.py @@ -1,31 +1,32 @@ -#!/usr/bin/env python -import freenect -import time -import random -import signal - -keep_running = True -last_time = 0 - - -def body(dev, ctx): - global last_time - if not keep_running: - raise freenect.Kill - if time.time() - last_time < 3: - return - last_time = time.time() - led = random.randint(0, 6) - tilt = random.randint(0, 30) - freenect.set_led(dev, led) - freenect.set_tilt_degs(dev, tilt) - print('led[%d] tilt[%d] accel[%s]' % (led, tilt, freenect.get_accel(dev))) - - -def handler(signum, frame): - """Sets up the kill handler, catches SIGINT""" - global keep_running - keep_running = False -print('Press Ctrl-C in terminal to stop') -signal.signal(signal.SIGINT, handler) -freenect.runloop(body=body) +#!/usr/bin/env python +from __future__ import print_function +import freenect +import time +import random +import signal + +keep_running = True +last_time = 0 + + +def body(dev, ctx): + global last_time + if not keep_running: + raise freenect.Kill + if time.time() - last_time < 3: + return + last_time = time.time() + led = random.randint(0, 6) + tilt = random.randint(0, 30) + freenect.set_led(dev, led) + freenect.set_tilt_degs(dev, tilt) + print('led[%d] tilt[%d] accel[%s]' % (led, tilt, freenect.get_accel(dev))) + + +def handler(signum, frame): + """Sets up the kill handler, catches SIGINT""" + global keep_running + keep_running = False +print('Press Ctrl-C in terminal to stop') +signal.signal(signal.SIGINT, handler) +freenect.runloop(body=body) diff --git a/scripts/mkvirt.py b/scripts/mkvirt.py index 6b392f877..2e6d38f87 100644 --- a/scripts/mkvirt.py +++ b/scripts/mkvirt.py @@ -1,10 +1,11 @@ +from __future__ import print_function import os import virtualenv, textwrap here = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(here) -print "Creating SimpleCV Bootstrap Install Script: simplecv-bootstrap.py" +print("Creating SimpleCV Bootstrap Install Script: simplecv-bootstrap.py") output = virtualenv.create_bootstrap_script(textwrap.dedent(""" import os, subprocess From 904196f5267cc3502ad07dc11c032949206352c6 Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Wed, 12 Aug 2015 21:34:55 -0700 Subject: [PATCH 2/3] Fix inconsistent indentation (py3 SyntaxError). Using autopep --select=E101,E121 --- SimpleCV/Camera.py | 407 +++++----- SimpleCV/Color.py | 6 +- SimpleCV/DFT.py | 10 +- SimpleCV/Display.py | 4 +- SimpleCV/Features/Blob.py | 2 +- SimpleCV/Features/Detection.py | 158 ++-- SimpleCV/Features/Features.py | 16 +- SimpleCV/Features/HaarCascade.py | 4 +- SimpleCV/Features/PlayingCards/cards.py | 44 +- SimpleCV/ImageClass.py | 696 +++++++++--------- SimpleCV/LineScan.py | 21 +- SimpleCV/MachineLearning/KNNClassifier.py | 6 +- .../MachineLearning/NaiveBayesClassifier.py | 6 +- SimpleCV/MachineLearning/SVMClassifier.py | 6 +- .../MachineLearning/TemporalColorTracker.py | 22 +- .../TestTemporalColorTracker.py | 2 +- SimpleCV/MachineLearning/TreeClassifier.py | 8 +- .../MachineLearning/query_imgs/flickrapi2.py | 13 +- SimpleCV/Segmentation/MOGSegmentation.py | 19 +- SimpleCV/Tracking/CAMShiftTracker.py | 4 +- SimpleCV/Tracking/LKTracker.py | 6 +- SimpleCV/Tracking/MFTracker.py | 164 ++--- SimpleCV/Tracking/SURFTracker.py | 10 +- SimpleCV/Tracking/TrackSet.py | 2 +- SimpleCV/Tracking/__init__.py | 2 +- SimpleCV/examples/detection/EdgeSnap.py | 10 +- .../examples/detection/MOGSegmentation.py | 12 +- SimpleCV/examples/display/qt-example.py | 2 - .../examples/manipulation/ImageMotionBlur.py | 4 +- SimpleCV/tests/test_display.py | 2 +- SimpleCV/tests/test_vimba.py | 3 +- SimpleCV/tests/tests.py | 4 +- SimpleCV/tests/vcamera_tests.py | 4 +- SimpleCV/tools/Calibrate.py | 36 +- scripts/simplecv | 4 +- 35 files changed, 852 insertions(+), 867 deletions(-) diff --git a/SimpleCV/Camera.py b/SimpleCV/Camera.py index 4890a54b4..ccb974e50 100644 --- a/SimpleCV/Camera.py +++ b/SimpleCV/Camera.py @@ -706,10 +706,10 @@ def __init__(self, s, st, start=1): self.source.load(s) else: warnings.warn('Virtual Camera is unable to figure out the contents of your ImageSet, it must be a directory, list of directories, or an ImageSet object') - + elif (self.sourcetype == 'video'): - + self.capture = cv.CaptureFromFile(self.source) cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, self.start-1) @@ -2098,7 +2098,7 @@ def get3DImage(self, Q, method="BM", state=None): sbm.fullDP = False; disparity = sbm.compute(imgLeft.getGrayNumpyCv2(), imgRight.getGrayNumpyCv2()) - + else: warnings.warn("Unknown method. Returning None") return None @@ -2167,7 +2167,7 @@ def get3DImageFromDisparity(self, disparity, Q): retVal = Image(Image3D_normalize) self.Image3D = Image3D return retVal - + class StereoCamera : """ @@ -2187,16 +2187,16 @@ def __init__(self): def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gridsize=0.027, WinSize = (352,288)): """ - + **SUMMARY** - + Stereo Calibration is a way in which you obtain the parameters that will allow you to calculate 3D information of the scene. Once both the camera's are initialized. Press [Space] once chessboard is identified in both the camera's. Press [esc] key to exit the calibration process. **PARAMETERS** - + * camLeft - Left camera index. * camRight - Right camera index. * nboards - Number of samples or multiple views of the chessboard in different positions and orientations with your stereo camera. @@ -2205,7 +2205,7 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri * WinSize - This is the window resolution. **RETURNS** - + A tuple of the form (CM1, CM2, D1, D2, R, T, E, F) on success CM1 - Camera Matrix for left camera, CM2 - Camera Matrix for right camera, @@ -2217,14 +2217,14 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri F - Fundamental matrix **EXAMPLE** - + >>> StereoCam = StereoCamera() >>> calibration = StereoCam.StereoCalibration(1,2,nboards=40) **Note** - + Press space to capture the images. - + """ count = 0 n1="Left" @@ -2326,9 +2326,9 @@ def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gri def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): """ - + **SUMMARY** - + saveCalibration is a method to save the StereoCalibration parameters such as CM1, CM2, D1, D2, R, T, E, F of stereo pair. This method returns True on success and saves the calibration in the following format. StereoCM1.txt @@ -2339,9 +2339,9 @@ def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): StereoT.txt StereoE.txt StereoF.txt - + **PARAMETERS** - + calibration - is a tuple os the form (CM1, CM2, D1, D2, R, T, E, F) CM1 -> Camera Matrix for left camera, CM2 -> Camera Matrix for right camera, @@ -2354,11 +2354,11 @@ def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): **RETURNS** - + return True on success and saves the calibration files. **EXAMPLE** - + >>> StereoCam = StereoCamera() >>> calibration = StereoCam.StereoCalibration(1,2,nboards=40) >>> StereoCam.saveCalibration(calibration,fname="Stereo1") @@ -2382,19 +2382,19 @@ def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): def loadCalibration(self,fname="Stereo",dir="."): """ - + **SUMMARY** - + loadCalibration is a method to load the StereoCalibration parameters such as CM1, CM2, D1, D2, R, T, E, F of stereo pair. This method loads from calibration files and return calibration on success else return false. - + **PARAMETERS** - + fname - is the prefix of the calibration files. dir - is the directory in which files are present. - + **RETURNS** - + a tuple of the form (CM1, CM2, D1, D2, R, T, E, F) on success. CM1 - Camera Matrix for left camera CM2 - Camera Matrix for right camera @@ -2405,12 +2405,12 @@ def loadCalibration(self,fname="Stereo",dir="."): E - Essential matrix F - Fundamental matrix else returns false - + **EXAMPLE** - + >>> StereoCam = StereoCamera() >>> loadedCalibration = StereoCam.loadCalibration(fname="Stereo1") - + """ filenames = (fname+"CM1.txt", fname+"CM2.txt", fname+"D1.txt", fname+"D2.txt", fname+"R.txt", fname+"T.txt", fname+"E.txt", fname+"F.txt") try : @@ -2430,13 +2430,13 @@ def loadCalibration(self,fname="Stereo",dir="."): def stereoRectify(self,calib=None,WinSize=(352,288)): """ - + **SUMMARY** - + Computes rectification transforms for each head of a calibrated stereo camera. - + **PARAMETERS** - + calibration - is a tuple os the form (CM1, CM2, D1, D2, R, T, E, F) CM1 - Camera Matrix for left camera, CM2 - Camera Matrix for right camera, @@ -2446,22 +2446,22 @@ def stereoRectify(self,calib=None,WinSize=(352,288)): T - Translation vector between the left and the right coordinate systems of the cameras, E - Essential matrix, F - Fundamental matrix - + **RETURNS** - + On success returns a a tuple of the format -> (R1, R2, P1, P2, Q, roi) R1 - Rectification transform (rotation matrix) for the left camera. R2 - Rectification transform (rotation matrix) for the right camera. P1 - Projection matrix in the new (rectified) coordinate systems for the left camera. P2 - Projection matrix in the new (rectified) coordinate systems for the right camera. Q - disparity-to-depth mapping matrix. - + **EXAMPLE** - + >>> StereoCam = StereoCamera() >>> calibration = StereoCam.loadCalibration(fname="Stereo1") >>> rectification = StereoCam.stereoRectify(calibration) - + """ (CM1, CM2, D1, D2, R, T, E, F) = calib R1 = cv.CreateMat(3, 3, cv.CV_64F) @@ -2469,9 +2469,9 @@ def stereoRectify(self,calib=None,WinSize=(352,288)): P1 = cv.CreateMat(3, 4, cv.CV_64F) P2 = cv.CreateMat(3, 4, cv.CV_64F) Q = cv.CreateMat(4, 4, cv.CV_64F) - + print("Running stereo rectification...") - + (leftroi, rightroi) = cv.StereoRectify(CM1, CM2, D1, D2, WinSize, R, T, R1, R2, P1, P2, Q) roi = [] roi.append(max(leftroi[0], rightroi[0])) @@ -2528,7 +2528,7 @@ def get3DImage(self, leftIndex, rightIndex, Q, method="BM", state=None): This method returns the 3D depth image using reprojectImageTo3D method. **PARAMETERS** - + * *leftIndex* - Index of left camera * *rightIndex* - Index of right camera * *Q* - reprojection Matrix (disparity to depth matrix) @@ -2549,7 +2549,7 @@ def get3DImage(self, leftIndex, rightIndex, Q, method="BM", state=None): fullDP - Bool (only SGBM) uniquenessRatio - int textureThreshold - int (only BM) - + **RETURNS** @@ -2630,32 +2630,32 @@ def __init__(self, camera): self.lock = threading.Lock() self.name = 'Thread-Camera-ID-' + str(self.camera.uniqueid) - + def run(self): counter = 0 timestamp = time.time() - + while self.run: - self.lock.acquire() - self.camera.runCommand("AcquisitionStart") - frame = self.camera._getFrame(1000) - - if frame: - img = Image(pil.fromstring(self.camera.imgformat, - (self.camera.width, self.camera.height), - frame.ImageBuffer[:int(frame.ImageBufferSize)])) - self.camera._buffer.appendleft(img) - - self.camera.runCommand("AcquisitionStop") - self.lock.release() - counter += 1 - time.sleep(0.01) + self.lock.acquire() + self.camera.runCommand("AcquisitionStart") + frame = self.camera._getFrame(1000) + + if frame: + img = Image(pil.fromstring(self.camera.imgformat, + (self.camera.width, self.camera.height), + frame.ImageBuffer[:int(frame.ImageBufferSize)])) + self.camera._buffer.appendleft(img) + + self.camera.runCommand("AcquisitionStop") + self.lock.release() + counter += 1 + time.sleep(0.01) + + if time.time() - timestamp >= 1: + self.camera.framerate = counter + counter = 0 + timestamp = time.time() - if time.time() - timestamp >= 1: - self.camera.framerate = counter - counter = 0 - timestamp = time.time() - def stop(self): @@ -2663,7 +2663,7 @@ def stop(self): def stopped(self): return self._stop.isSet() - + AVTCameraErrors = [ @@ -2690,10 +2690,10 @@ def stopped(self): ("ePvErrForbidden", "Attribute write forbidden at this time"), ("ePvErrUnavailable", "Attribute is not available at this time"), ("ePvErrFirewall", "A firewall is blocking the traffic (Windows only)"), - ] + ] def pverr(errcode): - if errcode: - raise Exception(": ".join(AVTCameraErrors[errcode])) + if errcode: + raise Exception(": ".join(AVTCameraErrors[errcode])) class AVTCamera(FrameSource): @@ -2722,7 +2722,7 @@ class AVTCamera(FrameSource): >>> img.show() """ - + _buffer = None # Buffer to store images _buffersize = 10 # Number of images to keep in the rolling image buffer for threads _lastimage = None # Last image loaded into memory @@ -2945,9 +2945,9 @@ def __init__(self, buffersize): self.frame = None def __del__(self): - #This function should disconnect from the AVT Camera - pverr(self.dll.PvCameraClose(self.handle)) - + #This function should disconnect from the AVT Camera + pverr(self.dll.PvCameraClose(self.handle)) + def __init__(self, camera_id = -1, properties = {}, threaded = False): #~ super(AVTCamera, self).__init__() import platform @@ -2980,10 +2980,10 @@ def __init__(self, camera_id = -1, properties = {}, threaded = False): self.handle = ct.c_uint() init_count = 0 while self.dll.PvCameraOpen(camera_id,0,ct.byref(self.handle)) != 0: #wait until camera is availble - if init_count > 4: # Try to connect 5 times before giving up - raise Exception('Could not connect to camera, please verify with SampleViewer you can connect') - init_count += 1 - time.sleep(1) # sleep and retry to connect to camera in a second + if init_count > 4: # Try to connect 5 times before giving up + raise Exception('Could not connect to camera, please verify with SampleViewer you can connect') + init_count += 1 + time.sleep(1) # sleep and retry to connect to camera in a second pverr(self.dll.PvCaptureStart(self.handle)) self.uniqueid = camera_id @@ -3013,11 +3013,11 @@ def __init__(self, camera_id = -1, properties = {}, threaded = False): if threaded: - self._thread = AVTCameraThread(self) - self._thread.daemon = True - self._buffer = deque(maxlen=self._buffersize) - self._thread.start() - self.threaded = True + self._thread = AVTCameraThread(self) + self._thread.daemon = True + self._buffer = deque(maxlen=self._buffersize) + self._thread.start() + self.threaded = True self.frame = None self._refreshFrameStats() @@ -3216,21 +3216,21 @@ def getImage(self, timeout = 5000): self.frame = None return img elif self.threaded: - self._thread.lock.acquire() - try: - img = self._buffer.pop() - self._lastimage = img - except IndexError: - img = self._lastimage - self._thread.lock.release() + self._thread.lock.acquire() + try: + img = self._buffer.pop() + self._lastimage = img + except IndexError: + img = self._lastimage + self._thread.lock.release() else: - self.runCommand("AcquisitionStart") - frame = self._getFrame(timeout) - img = Image(pil.fromstring(self.imgformat, - (self.width, self.height), - frame.ImageBuffer[:int(frame.ImageBufferSize)])) - self.runCommand("AcquisitionStop") + self.runCommand("AcquisitionStart") + frame = self._getFrame(timeout) + img = Image(pil.fromstring(self.imgformat, + (self.width, self.height), + frame.ImageBuffer[:int(frame.ImageBufferSize)])) + self.runCommand("AcquisitionStop") return img @@ -3263,20 +3263,20 @@ def _getFrame(self, timeout = 5000): #return the AVTFrame object from the camera, timeout in ms #need to multiply by bitdepth try: - frame = self.AVTFrame(self.buffersize) - pverr( self.dll.PvCaptureQueueFrame(self.handle, ct.byref(frame), None) ) - st = time.time() - try: - pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(frame), timeout) ) - except Exception as e: - print("Exception waiting for frame:", e) - print("Time taken:",time.time() - st) - raise(e) - + frame = self.AVTFrame(self.buffersize) + pverr( self.dll.PvCaptureQueueFrame(self.handle, ct.byref(frame), None) ) + st = time.time() + try: + pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(frame), timeout) ) + except Exception as e: + print("Exception waiting for frame:", e) + print("Time taken:",time.time() - st) + raise(e) + except Exception as e: print("Exception aquiring frame:", e) raise(e) - + return frame def acquire(self): @@ -3294,7 +3294,7 @@ class GigECamera(Camera): """ GigE Camera driver via Aravis """ - + def __init__(self, camera_id = None, properties = {}, threaded = False): try: from gi.repository import Aravis @@ -3302,41 +3302,41 @@ def __init__(self, camera_id = None, properties = {}, threaded = False): print("GigE is supported by the Aravis library, download and build from https://github.com/sightmachine/aravis") print("Note that you need to set GI_TYPELIB_PATH=$GI_TYPELIB_PATH:(PATH_TO_ARAVIS)/src for the GObject Introspection") sys.exit() - + self._cam = Aravis.Camera.new (None) - + self._pixel_mode = "RGB" if properties.get("mode", False): self._pixel_mode = properties.pop("mode") - - + + if self._pixel_mode == "gray": self._cam.set_pixel_format (Aravis.PIXEL_FORMAT_MONO_8) else: self._cam.set_pixel_format (Aravis.PIXEL_FORMAT_BAYER_BG_8) #we'll use bayer (basler cams) #TODO, deal with other pixel formats - + if properties.get("roi", False): roi = properties['roi'] self._cam.set_region(*roi) #TODO, check sensor size - + if properties.get("width", False): #TODO, set internal function to scale results of getimage pass - + if properties.get("framerate", False): self._cam.set_frame_rate(properties['framerate']) - + self._stream = self._cam.create_stream (None, None) - + payload = self._cam.get_payload() self._stream.push_buffer(Aravis.Buffer.new_allocate (payload)) [x,y,width,height] = self._cam.get_region () self._height, self._width = height, width - + def getImage(self): - + camera = self._cam camera.start_acquisition() buff = self._stream.pop_buffer() @@ -3346,99 +3346,99 @@ def getImage(self): self._stream.push_buffer(buff) camera.stop_acquisition() #TODO, we should handle software triggering (separate capture and get image events) - + return Image(rgb) def getPropertyList(self): - l = [ - 'available_pixel_formats', - 'available_pixel_formats_as_display_names', - 'available_pixel_formats_as_strings', - 'binning', - 'device_id', - 'exposure_time', - 'exposure_time_bounds', - 'frame_rate', - 'frame_rate_bounds', - 'gain', - 'gain_bounds', - 'height_bounds', - 'model_name', - 'payload', - 'pixel_format', - 'pixel_format_as_string', - 'region', - 'sensor_size', - 'trigger_source', - 'vendor_name', - 'width_bounds' - ] - return l - - + l = [ + 'available_pixel_formats', + 'available_pixel_formats_as_display_names', + 'available_pixel_formats_as_strings', + 'binning', + 'device_id', + 'exposure_time', + 'exposure_time_bounds', + 'frame_rate', + 'frame_rate_bounds', + 'gain', + 'gain_bounds', + 'height_bounds', + 'model_name', + 'payload', + 'pixel_format', + 'pixel_format_as_string', + 'region', + 'sensor_size', + 'trigger_source', + 'vendor_name', + 'width_bounds' + ] + return l + + def getProperty(self, name = None): - ''' - This function get's the properties availble to the camera - - Usage: - > camera.getProperty('region') - > (0, 0, 128, 128) - - Available Properties: - see function camera.getPropertyList() - ''' - if name == None: - print("You need to provide a property, available properties are:") - print("") - for p in self.getPropertyList(): - print(p) - return + ''' + This function get's the properties availble to the camera + + Usage: + > camera.getProperty('region') + > (0, 0, 128, 128) + + Available Properties: + see function camera.getPropertyList() + ''' + if name == None: + print("You need to provide a property, available properties are:") + print("") + for p in self.getPropertyList(): + print(p) + return + + stringval = "get_{}".format(name) + try: + return getattr(self._cam, stringval)() + except: + print('Property {} does not appear to exist'.format(name)) + return None - stringval = "get_{}".format(name) - try: - return getattr(self._cam, stringval)() - except: - print('Property {} does not appear to exist'.format(name)) - return None - def setProperty(self, name = None, *args): - ''' - This function sets the property available to the camera + ''' + This function sets the property available to the camera - Usage: - > camera.setProperty('region',(256,256)) + Usage: + > camera.setProperty('region',(256,256)) - Available Properties: - see function camera.getPropertyList() + Available Properties: + see function camera.getPropertyList() - ''' + ''' - if name == None: - print("You need to provide a property, available properties are:") - print("") - for p in self.getPropertyList(): - print(p) - return + if name == None: + print("You need to provide a property, available properties are:") + print("") + for p in self.getPropertyList(): + print(p) + return + + if len(args) <= 0: + print("You must provide a value to set") + return + + stringval = "set_{}".format(name) + try: + return getattr(self._cam, stringval)(*args) + except: + print('Property {} does not appear to exist or value is not in correct format'.format(name)) + return None - if len(args) <= 0: - print("You must provide a value to set") - return - - stringval = "set_{}".format(name) - try: - return getattr(self._cam, stringval)(*args) - except: - print('Property {} does not appear to exist or value is not in correct format'.format(name)) - return None - def getAllProperties(self): - ''' - This function just prints out all the properties available to the camera - ''' - - for p in self.getPropertyList(): - print("{}: {}".format(p,self.getProperty(p))) + ''' + This function just prints out all the properties available to the camera + ''' + + for p in self.getPropertyList(): + print("{}: {}".format(p,self.getProperty(p))) class VimbaCameraThread(threading.Thread): camera = None @@ -3456,11 +3456,11 @@ def __init__(self, camera): self.lock = threading.Lock() self.name = 'Thread-Camera-ID-' + str(self.camera.uniqueid) - + def run(self): counter = 0 timestamp = time.time() - + while self.run: self.lock.acquire() @@ -3550,7 +3550,7 @@ def __init__(self, camera_id = -1, properties = {}, threaded = False): self._vimba = None self._setupVimba() - + camlist = self.listAllCameras() self._camTable = {} self._frame = None @@ -3613,12 +3613,12 @@ def __init__(self, camera_id = -1, properties = {}, threaded = False): self.setProperty(p, properties[p]) if threaded: - self._thread = VimbaCameraThread(self) - self._thread.daemon = True - self._buffer = deque(maxlen=self._buffersize) - self._thread.start() - self.threaded = True - + self._thread = VimbaCameraThread(self) + self._thread.daemon = True + self._buffer = deque(maxlen=self._buffersize) + self._thread.start() + self.threaded = True + self._refreshFrameStats() def restart(self): @@ -3714,7 +3714,7 @@ def getAllProperties(self): # Ignore features not yet implemented pass return ar - + def setProperty(self, name, value, skip_buffer_size_check=False): """ @@ -3823,4 +3823,3 @@ def _captureFrame(self, timeout = 5000): except Exception as e: print("Exception acquiring frame: %s: %s" % (e, traceback.format_exc())) raise(e) - diff --git a/SimpleCV/Color.py b/SimpleCV/Color.py index 748d1a743..fe63fe8b6 100644 --- a/SimpleCV/Color.py +++ b/SimpleCV/Color.py @@ -306,7 +306,7 @@ def getLightness(self,rgb): >>> c = Color.getLightness((22,35,230)) **NOTES** - + Lightness Method: value = (max(R,G,B)+min(R,G,B))/2 """ @@ -332,7 +332,7 @@ def getLuminosity(self,rgb): >>> c = Color.getLuminosity((22,35,230)) **NOTES** - + Luminosity Method: value = 0.21*R + 0.71*G + 0.07*B """ @@ -347,7 +347,7 @@ class ColorCurve: least 4 point pairs. Either of these must map in a 255x255 space. The curve can then be used in the applyRGBCurve, applyHSVCurve, and applyInstensityCurve functions. - + Note: The points should be in strictly increasing order of their first elements (X-coordinates) diff --git a/SimpleCV/DFT.py b/SimpleCV/DFT.py index 1b9811faf..44fcf1f41 100644 --- a/SimpleCV/DFT.py +++ b/SimpleCV/DFT.py @@ -29,13 +29,13 @@ class DFT: * *_yCutoffLow* - Lower vertical cut off frequency for lowpassfilter * *_xCutoffHigh* - Upper horizontal cut off frequency for highpassfilter * *_yCutoffHigh* - Upper vertical cut off frequency for highassfilter - + **EXAMPLE** >>> gauss = DFT.createGaussianFilter(dia=40, size=(512,512)) - + >>> dft = DFT() >>> butterworth = dft.createButterworthFilter(dia=300, order=2, size=(300, 300)) @@ -298,7 +298,7 @@ def createLowpassFilter(self, xCutoff, yCutoff=None, size=(64, 64)): >>> flt = DFT.createLowpassFilter(xCutoff=[75, 113, 124], yCutoff=[35, 45, 90], size=(320, 280)) - + >>> img = Image('lenna') >>> flt.applyFilter(img).show() """ @@ -384,7 +384,7 @@ def createHighpassFilter(self, xCutoff, yCutoff=None, size=(64, 64)): >>> flt = DFT.createHighpassFilter(xCutoff=[75, 113, 124], yCutoff=[35, 45, 90], size=(320, 280)) - + >>> img = Image('lenna') >>> flt.applyFilter(img).show() """ @@ -472,7 +472,7 @@ def createBandpassFilter(self, xCutoffLow, xCutoffHigh, yCutoffLow=None, yCutoffLow=[70, 110, 112], yCutoffHigh=[180, 220, 220], size=(320, 280)) - + >>> img = Image('lenna') >>> flt.applyFilter(img).show() """ diff --git a/SimpleCV/Display.py b/SimpleCV/Display.py index 785ff3e04..8689e01a5 100644 --- a/SimpleCV/Display.py +++ b/SimpleCV/Display.py @@ -578,7 +578,7 @@ def _setButtonState(self, state, button): def checkEvents(self,returnStrings=False): """ - + **SUMMARY** CheckEvents checks the pygame event queue and sets the internal display @@ -591,7 +591,7 @@ def checkEvents(self,returnStrings=False): **PARAMETERS** returnStrings - pygame returns an enumerated int by default, when this is set to true we return a list of strings. - + **RETURNS** A list of key down events. Parse them with pg.K_ diff --git a/SimpleCV/Features/Blob.py b/SimpleCV/Features/Blob.py index 4c1666d69..b5db2e1d6 100644 --- a/SimpleCV/Features/Blob.py +++ b/SimpleCV/Features/Blob.py @@ -1101,7 +1101,7 @@ def match(self, otherblob): otherM = otherSigns * otherLogs return np.sum(abs((1/ myM - 1/ otherM))) - + def getMaskedImage(self): """ Get the blob size image with the masked blob diff --git a/SimpleCV/Features/Detection.py b/SimpleCV/Features/Detection.py index e9963075f..8b028d3ad 100644 --- a/SimpleCV/Features/Detection.py +++ b/SimpleCV/Features/Detection.py @@ -416,7 +416,7 @@ def angle(self): def cropToImageEdges(self): """ **SUMMARY** - + Returns the line with endpoints on edges of image. If some endpoints lies inside image then those points remain the same without extension to the edges. @@ -437,7 +437,7 @@ def cropToImageEdges(self): x2, y2 = pt2 w, h = self.image.width-1, self.image.height-1 slope = self.slope - + ep = [] if slope == float('inf'): if 0 <= x1 <= w and 0 <= x2 <= w: @@ -455,11 +455,11 @@ def cropToImageEdges(self): x = (slope*x1 + h - y1)/slope # bottom edge y = h if 0 <= x <= w: ep.append((int(round(x)), h)) - + y = -slope*x1 + y1 # left edge x = 0 if 0 <= y <= h: ep.append( (0, (int(round(y)))) ) - + y = slope*(w - x1) + y1 # right edge x = w if 0 <= y <= h: ep.append( (w, (int(round(y)))) ) @@ -478,9 +478,9 @@ def cropToImageEdges(self): else: logger.warning("Line does not cross the image") return None - + return Line(self.image, (pt1, pt2)) - + def getVector(self): # this should be a lazy property if( self.vector is None): @@ -497,7 +497,7 @@ def cross(self,other): def getYIntercept(self): """ **SUMMARY** - + Returns the y intercept based on the lines equation. Note that this point is potentially not contained in the image itself **RETURNS** @@ -520,7 +520,7 @@ def getYIntercept(self): def extendToImageEdges(self): """ **SUMMARY** - + Returns the line with endpoints on edges of image. **RETURNS** @@ -540,11 +540,11 @@ def extendToImageEdges(self): x2, y2 = pt2 w, h = self.image.width-1, self.image.height-1 slope = self.slope - + if not 0 <= x1 <= w or not 0 <= x2 <= w or not 0 <= y1 <= w or not 0 <= y2 <= w: logger.warning("At first the line should be cropped") return None - + ep = [] if slope == float('inf'): if 0 <= x1 <= w and 0 <= x2 <= w: @@ -560,18 +560,18 @@ def extendToImageEdges(self): x = (slope*x1 + h - y1)/slope # bottom edge y = h if 0 <= x <= w: ep.append((int(round(x)), h)) - + y = -slope*x1 + y1 # left edge x = 0 if 0 <= y <= h: ep.append( (0, (int(round(y)))) ) - + y = slope*(w - x1) + y1 # right edge x = w if 0 <= y <= h: ep.append( (w, (int(round(y)))) ) ep = list(set(ep)) # remove duplicates of points if line cross image at corners ep.sort() - + return Line(self.image, ep) @@ -682,7 +682,7 @@ def area(self): Returns the area defined by the quandrangle formed by the boundary points - + **RETURNS** An integer area value. @@ -1844,7 +1844,7 @@ def __init__(self,x,y=None,w=None,h=None,image=None ): * *y* - this is usually a second point or set of y values. * *w* - a width * *h* - a height. - + **RETURNS** Nothing. @@ -1870,13 +1870,13 @@ def __init__(self,x,y=None,w=None,h=None,image=None ): h = None else: self.image = image - + if( image is None and isinstance(x,(Feature,FeatureSet))): if( isinstance(x,Feature) ): self.image = x.image if( isinstance(x,FeatureSet) and len(x) > 0 ): self.image = x[0].image - + if(isinstance(x,Feature)): self.subFeatures = FeatureSet([x]) elif(isinstance(x,(list,tuple)) and len(x) > 0 and isinstance(x,Feature)): @@ -1887,7 +1887,7 @@ def __init__(self,x,y=None,w=None,h=None,image=None ): logger.warning("Could not create an ROI from your data.") return self._rebase(result) - + def resize(self,w,h=None,percentage=True): """ @@ -1896,7 +1896,7 @@ def resize(self,w,h=None,percentage=True): Contract/Expand the roi. By default use a percentage, otherwise use pixels. This is all done relative to the center of the roi - + **PARAMETERS** * *w* - the percent to grow shrink the region is the only parameter, otherwise @@ -1905,7 +1905,7 @@ def resize(self,w,h=None,percentage=True): * *percentage* - If true use percentages (e.g. 2 doubles the size), otherwise use pixel values. * *h* - a height. - + **RETURNS** Nothing. @@ -1945,14 +1945,14 @@ def overlaps(self,otherROI): def translate(self,x=0,y=0): """ **SUMMARY** - + Move the roi. - + **PARAMETERS** * *x* - Move the ROI horizontally. * *y* - Move the ROI vertically - + **RETURNS** Nothing. @@ -1966,18 +1966,18 @@ def translate(self,x=0,y=0): """ if( x == 0 and y == 0 ): return - + if(y == 0 and isinstance(x,(tuple,list))): y = x[1] x = x[0] - + if( isinstance(x,(float,int)) and isinstance(y,(float,int))): self._rebase([self.xtl+x,self.ytl+y,self.w,self.h]) def toXYWH(self): """ **SUMMARY** - + Get the ROI as a list of the top left corner's x and y position and the roi's width and height in pixels. @@ -1993,11 +1993,11 @@ def toXYWH(self): """ return [self.xtl,self.ytl,self.w,self.h] - + def toTLAndBR(self): """ **SUMMARY** - + Get the ROI as a list of tuples of the ROI's top left corner and bottom right corner. @@ -2010,7 +2010,7 @@ def toTLAndBR(self): >>> roi = ROI(10,10,100,100,img) >>> roi.translate(30,30) >>> print roi.toTLAndBR() - + """ return [(self.xtl,self.ytl),(self.xtl+self.w,self.ytl+self.h)] @@ -2018,10 +2018,10 @@ def toTLAndBR(self): def toPoints(self): """ **SUMMARY** - + Get the ROI as a list of four points that make up the bounding rectangle. - - + + **RETURNS** A list of the form [(x,y),(x,y),(x,y),(x,y)] @@ -2037,16 +2037,16 @@ def toPoints(self): br = (self.xtl+self.w,self.ytl+self.h) bl = (self.xtl,self.ytl+self.h) return [tl,tr,br,bl] - + def toUnitXYWH(self): """ **SUMMARY** - + Get the ROI as a list, the values are top left x, to left y, width and height. These values are scaled to unit values with respect to the source image.. - - + + **RETURNS** A list of the form [x,y,w,h] @@ -2067,13 +2067,13 @@ def toUnitXYWH(self): nx = x/srcw if( y != 0 ): ny = y/srch - + return [nx,ny,w/srcw,h/srch] - + def toUnitTLAndBR(self): """ **SUMMARY** - + Get the ROI as a list of tuples of the ROI's top left corner and bottom right corner. These coordinates are in unit length values with respect to the source image. @@ -2087,9 +2087,9 @@ def toUnitTLAndBR(self): >>> roi = ROI(10,10,100,100,img) >>> roi.translate(30,30) >>> print roi.toUnitTLAndBR() - + """ - + if(self.image is None): return None srcw = float(self.image.width) @@ -2103,18 +2103,18 @@ def toUnitTLAndBR(self): nx = x/srcw if( y != 0 ): ny = y/srch - + return [(nx,ny),(nx+nw,ny+nh)] def toUnitPoints(self): """ **SUMMARY** - + Get the ROI as a list of four points that make up the bounding rectangle. Each point is represented in unit coordinates with respect to the souce image. - + **RETURNS** A list of the form [(x,y),(x,y),(x,y),(x,y)] @@ -2139,15 +2139,15 @@ def toUnitPoints(self): y = y/srch retVal.append((x,y)) return retVal - + def CoordTransformX(self,x,intype="ROI",output="SRC"): """ **SUMMARY** - + Transform a single or a set of x values from one reference frame to another. Options are: - + SRC - the coordinates of the source image. ROI - the coordinates of the ROI ROI_UNIT - unit coordinates in the frame of reference of the ROI @@ -2187,11 +2187,11 @@ def CoordTransformX(self,x,intype="ROI",output="SRC"): def CoordTransformY(self,y,intype="ROI",output="SRC"): """ **SUMMARY** - + Transform a single or a set of y values from one reference frame to another. Options are: - + SRC - the coordinates of the source image. ROI - the coordinates of the ROI ROI_UNIT - unit coordinates in the frame of reference of the ROI @@ -2229,15 +2229,15 @@ def CoordTransformY(self,y,intype="ROI",output="SRC"): return y return self._transform(y,self.image.height,self.h,self.ytl,intype,output) - + def CoordTransformPts(self,pts,intype="ROI",output="SRC"): """ **SUMMARY** - + Transform a set of (x,y) values from one reference frame to another. Options are: - + SRC - the coordinates of the source image. ROI - the coordinates of the ROI ROI_UNIT - unit coordinates in the frame of reference of the ROI @@ -2272,14 +2272,14 @@ def CoordTransformPts(self,pts,intype="ROI",output="SRC"): output = output.upper() x = [pt[0] for pt in pts] y = [pt[1] for pt in pts] - + if( intype == output ): return pts - + x = self._transform(x,self.image.width,self.w,self.xtl,intype,output) y = self._transform(y,self.image.height,self.h,self.ytl,intype,output) return zip(x,y) - + def _transform(self,x,imgsz,roisz,offset,intype,output): xtemp = [] @@ -2309,10 +2309,10 @@ def _transform(self,x,imgsz,roisz,offset,intype,output): else: logger.warning("Bad Parameter to CoordTransformX") return None - + return retVal - + def splitX(self,x,unitVals=False,srcVals=False): """ @@ -2330,23 +2330,23 @@ def splitX(self,x,unitVals=False,srcVals=False): * *x*-The split point. Can be a single point or a list of points. the type is determined by the flags. * *unitVals* - Use unit vals for the split point. E.g. 0.5 means split at 50% of the ROI. * *srcVals* - Use x values relative to the source image rather than relative to the ROI. - - + + **RETURNS** - + Returns a feature set of ROIs split from the source ROI. **EXAMPLE** >>> roi = ROI(0,0,100,100,img) >>> splits = roi.splitX(50) # create two ROIs - + """ retVal = FeatureSet() if(unitVals and srcVals): logger.warning("Not sure how you would like to split the feature") return None - + if(not isinstance(x,(list,tuple))): x = [x] @@ -2359,7 +2359,7 @@ def splitX(self,x,unitVals=False,srcVals=False): if( xt < self.xtl or xt > self.xtl+self.w ): logger.warning("Invalid split point.") return None - + x.insert(0,self.xtl) x.append(self.xtl+self.w) for i in xrange(0,len(x)-1): @@ -2385,22 +2385,22 @@ def splitY(self,y,unitVals=False,srcVals=False): * *y*-The split point. Can be a single point or a list of points. the type is determined by the flags. * *unitVals* - Use unit vals for the split point. E.g. 0.5 means split at 50% of the ROI. * *srcVals* - Use x values relative to the source image rather than relative to the ROI. - + **RETURNS** - + Returns a feature set of ROIs split from the source ROI. **EXAMPLE** >>> roi = ROI(0,0,100,100,img) >>> splits = roi.splitY(50) # create two ROIs - + """ retVal = FeatureSet() if(unitVals and srcVals): logger.warning("Not sure how you would like to split the feature") return None - + if(not isinstance(y,(list,tuple))): y = [y] @@ -2413,7 +2413,7 @@ def splitY(self,y,unitVals=False,srcVals=False): if( yt < self.ytl or yt > self.ytl+self.h ): logger.warning("Invalid split point.") return None - + y.insert(0,self.ytl) y.append(self.ytl+self.h) for i in xrange(0,len(y)-1): @@ -2427,7 +2427,7 @@ def splitY(self,y,unitVals=False,srcVals=False): def merge(self, regions): """ **SUMMARY** - + Combine another region, or regions with this ROI. Everything must be in the source image coordinates. Regions can be a ROIs, [ROI], features, FeatureSets, or anything that can be cajoled into a region. @@ -2435,7 +2435,7 @@ def merge(self, regions): **PARAMETERS** * *regions* - A region or list of regions. Regions are just about anything that has position. - + **RETURNS** @@ -2448,7 +2448,7 @@ def merge(self, regions): >>> print roi.toXYWH() >>> roi.merge(blob[2]) >>> print roi.toXYWH() - + """ result = self._standardize(regions) if( result is not None ): @@ -2474,12 +2474,12 @@ def merge(self, regions): elif(isinstance(regions[0],Feature)): for r in regions: self.subFeatures.append(r) - + def rebase(self, x,y=None,w=None,h=None): """ Completely alter roi using whatever source coordinates you wish. - + """ if(isinstance(x,Feature)): self.subFeatures.append(x) @@ -2536,7 +2536,7 @@ def show(self, color = Color.GREEN, width=2): """ self.draw(color,width) self.image.show() - + def meanColor(self): """ **SUMMARY** @@ -2558,7 +2558,7 @@ def meanColor(self): """ x,y,w,h = self.toXYWH() return self.image.crop(x,y,w,h).meanColor() - + def _rebase(self,roi): x,y,w,h = roi self._mMaxX = None @@ -2607,7 +2607,7 @@ def _standardize(self,x,y=None,w=None,h=None): y = ymin w = xmax-xmin h = ymax-ymin - + elif(isinstance(x, Feature)): theFeature = x x = theFeature.points[0][0] @@ -2639,7 +2639,7 @@ def _standardize(self,x,y=None,w=None,h=None): else: logger.warning("x should be in the form ((x,y),(x1,y1),(x2,y2),(x3,y3))") return None - + # x,y of the form [x1,x2,x3,x4,x5....] and y similar elif(isinstance(x, (tuple,list)) and isinstance(y, (tuple,list)) and @@ -2697,7 +2697,7 @@ def _standardize(self,x,y=None,w=None,h=None): h = np.abs(y[1]-x[1]) x = xt y = yt - + else: logger.warning("if x and y are tuple it should be in the form (x1,y1) and (x2,y2)") return None @@ -2715,7 +2715,7 @@ def _standardize(self,x,y=None,w=None,h=None): h = np.clip(h,0,self.image.height-y) return [x,y,w,h] - + def crop(self): retVal = None if(self.image is not None): diff --git a/SimpleCV/Features/Features.py b/SimpleCV/Features/Features.py index 842a992f4..0ff6deb8c 100644 --- a/SimpleCV/Features/Features.py +++ b/SimpleCV/Features/Features.py @@ -69,11 +69,11 @@ def draw(self, color = Color.GREEN,width=1, autocolor = False, alpha=-1): Call the draw() method on each feature in the FeatureSet. **PARAMETERS** - + * *color* - The color to draw the object. Either an BGR tuple or a member of the :py:class:`Color` class. * *width* - The width to draw the feature in pixels. A value of -1 usually indicates a filled region. * *autocolor* - If true a color is randomly selected for each feature. - + **RETURNS** @@ -1066,18 +1066,18 @@ def aspectRatios(self): def cluster(self,method="kmeans",properties=None,k=3): """ - + **SUMMARY** This function clusters the blobs in the featureSet based on the properties. Properties can be "color", "shape" or "position" of blobs. Clustering is done using K-Means or Hierarchical clustering(Ward) algorithm. **PARAMETERS** - + * *properties* - It should be a list with any combination of "color", "shape", "position". properties = ["color","position"]. properties = ["position","shape"]. properties = ["shape"] * *method* - if method is "kmeans", it will cluster using K-Means algorithm, if the method is "hierarchical", no need to spicify the number of clusters * *k* - The number of clusters(kmeans). - + **RETURNS** @@ -1091,7 +1091,7 @@ def cluster(self,method="kmeans",properties=None,k=3): >>> for i in clusters: >>> i.draw(color=Color.getRandom(),width=5) >>> img.show() - + """ try : from sklearn.cluster import KMeans, Ward @@ -1119,10 +1119,10 @@ def cluster(self,method="kmeans",properties=None,k=3): X.append(featureVector) if method == "kmeans": - + # Ignore minor version numbers. sklearn_version = re.search(r'\d+\.\d+', __version__).group() - + if (float(sklearn_version) > 0.11): k_means = KMeans(init='random', n_clusters=k, n_init=10).fit(X) else: diff --git a/SimpleCV/Features/HaarCascade.py b/SimpleCV/Features/HaarCascade.py index 98f845b29..80600b573 100644 --- a/SimpleCV/Features/HaarCascade.py +++ b/SimpleCV/Features/HaarCascade.py @@ -31,7 +31,7 @@ def __init__(self, fname=None, name=None): logger.warning("Could not find Haar Cascade file " + fname) logger.warning("Try running the function img.listHaarFeatures() to see what is available") return None - + self._mCascade = cv.Load(self._fhandle) if self._fhandle in HaarCascade._cache: @@ -54,7 +54,7 @@ def load(self, fname=None, name = None): logger.warning("Could not find Haar Cascade file " + fname) logger.warning("Try running the function img.listHaarFeatures() to see what is available") return None - + self._mCascade = cv.Load(self._fhandle) if self._fhandle in HaarCascade._cache: diff --git a/SimpleCV/Features/PlayingCards/cards.py b/SimpleCV/Features/PlayingCards/cards.py index bf9fde820..a6b47f9cf 100644 --- a/SimpleCV/Features/PlayingCards/cards.py +++ b/SimpleCV/Features/PlayingCards/cards.py @@ -19,32 +19,32 @@ # utility functions def cmp_cards(a, b): return cmp(ORDER_LOOKUP[a], ORDER_LOOKUP[b]) - + def cmp_tuples(a, b): n1 = len(a) n2 = len(b) if n1 != n2: return cmp(n1, n2) return cmp(a, b) - + def suit(card): return card[1] - + def suit_int(card): return SUIT_LOOKUP[card[1]] - + def rank(card): return card[0] - + def rank_int(card): return RANK_LOOKUP[card[0]] - + def card_int(card): s = 1 << suit_int(card) r = rank_int(card) c = (s << 4) | r return c - + # test functions def is_straight(cards): previous = rank_int(cards[0]) - 1 @@ -55,48 +55,48 @@ def is_straight(cards): return False previous = r return True - + def is_flush(cards): s = suit(cards[0]) return all(suit(card) == s for card in cards) - + def same_rank(cards): r = rank(cards[0]) return all(rank(card) == r for card in cards) - + def split_ranks(cards, indexes): for index in indexes: a, b = cards[:index], cards[index:] if same_rank(a) and same_rank(b): return True return False - + def is_full_house(cards): return split_ranks(cards, (2, 3)) - + def is_four(cards): return split_ranks(cards, (1, 4)) - + def is_pat(cards): return is_straight(cards) or is_flush(cards) or is_full_house(cards) or is_four(cards) - + def is_straight_flush(cards): return is_straight(cards) and is_flush(cards) - + def rank_count(cards): result = {} for card in cards: r = rank_int(card) result[r] = result.get(r, 0) + 1 return result - + def is_three(cards, counts=None): counts = counts or rank_count(cards) for rank, count in counts.iteritems(): if count == 3: return True return False - + def is_two_pair(cards, counts=None): pairs = 0 counts = counts or rank_count(cards) @@ -104,27 +104,27 @@ def is_two_pair(cards, counts=None): if count == 2: pairs += 1 return pairs == 2 - + def is_pair(cards, counts=None): counts = counts or rank_count(cards) for rank, count in counts.iteritems(): if count == 2: return True return False - + def get_ranks(counts): values = [(count, rank) for rank, count in counts.iteritems()] values.sort(reverse=True) values = [n[1] for n in values] return values - + def get_straight_rank(cards): top = rank_int(cards[-1]) bottom = rank_int(cards[0]) if top == 12 and bottom == 0: return 3 return top - + def evaluate_hand(cards): flush = is_flush(cards) straight = is_straight(cards) @@ -151,4 +151,4 @@ def evaluate_hand(cards): else: value = 1 ranks.insert(0, value) - return tuple(ranks) + return tuple(ranks) diff --git a/SimpleCV/ImageClass.py b/SimpleCV/ImageClass.py index 571f57c5e..854a5793c 100644 --- a/SimpleCV/ImageClass.py +++ b/SimpleCV/ImageClass.py @@ -230,67 +230,67 @@ def download(self, tag=None, number=10, size='thumb'): def upload(self,dest,api_key=None,api_secret=None, verbose = True): """ - + **SUMMARY** - + Uploads all the images to imgur or flickr or dropbox. In verbose mode URL values are printed. - - + + **PARAMETERS** - + * *api_key* - a string of the API key. * *api_secret* - (required only for flickr and dropbox ) a string of the API secret. * *verbose* - If verbose is true all values are printed to the screen - - + + **RETURNS** - + if uploading is successful - + - Imgur return the original image URL on success and None if it fails. - Flick returns True on success, else returns False. - dropbox returns True on success. - + **EXAMPLE** - + TO upload image to imgur:: - + >>> imgset = ImageSet("/home/user/Desktop") >>> result = imgset.upload( 'imgur',"MY_API_KEY1234567890" ) >>> print "Uploaded To: " + result[0] - + To upload image to flickr:: - + >>> imgset.upload('flickr','api_key','api_secret') >>> imgset.upload('flickr') #Once the api keys and secret keys are cached. To upload image to dropbox:: - + >>> imgset.upload('dropbox','api_key','api_secret') >>> imgset.upload('dropbox') #Once the api keys and secret keys are cached. **NOTES** - + .. Warning:: This method requires two packages to be installed -PyCurl -flickr api. -dropbox - - + + .. Warning:: You must supply your own API key. Find more about API keys: - + - http://imgur.com/register/api_anon - http://www.flickr.com/services/api/misc.api_keys.html - https://www.dropbox.com/developers/start/setup#python - - + + """ try : for i in self: @@ -419,7 +419,7 @@ def _write_gif(self, filename, duration=0.1, loops=0, dither=1): def save(self, destination=None, dt=0.2, verbose = False, displaytype=None): """ - + **SUMMARY** This is a quick way to save all the images in a data set. @@ -436,8 +436,8 @@ def save(self, destination=None, dt=0.2, verbose = False, displaytype=None): * *dt* - time between frames, for creating gif files. * *verbose* - print the path of the saved files to the console. * *displaytype* - the method use for saving or displaying images. - - + + valid values are: * 'notebook' - display to the ipython notebook. @@ -947,7 +947,7 @@ def __init__(self, source = None, camera = None, colorSpace = ColorSpace.UNKNOWN im = StringIO(img_file.read()) source = pil.open(im).convert("RGB") - + #Check if loaded from base64 URI if isinstance(source, basestring) and (source.lower().startswith("data:image/png;base64,")): img = source[22:].decode("base64") @@ -974,7 +974,7 @@ def __init__(self, source = None, camera = None, colorSpace = ColorSpace.UNKNOWN choice = random.choice(['LyleJune1973.png','lenna.png']) imgpth = os.path.join(LAUNCH_PATH, 'sampleimages',choice) source = imgpth - + elif sample: imgpth = os.path.join(LAUNCH_PATH, 'sampleimages', source) source = imgpth @@ -1041,11 +1041,11 @@ def __init__(self, source = None, camera = None, colorSpace = ColorSpace.UNKNOWN if source == '': raise IOError("No filename provided to Image constructor") - + elif webp or source.split('.')[-1] == 'webp': try: if source.__class__.__name__ == 'StringIO': - source.seek(0) # set the stringIO to the begining + source.seek(0) # set the stringIO to the begining self._pil = pil.open(source) self._bitmap = cv.CreateImageHeader(self._pil.size, cv.IPL_DEPTH_8U, 3) except: @@ -2227,7 +2227,7 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa .. attention:: We need examples for all save methods as they are unintuitve. - + """ #TODO, we use the term mode here when we mean format #TODO, if any params are passed, use PIL @@ -2270,9 +2270,9 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa if self._colorSpace != ColorSpace.BGR and self._colorSpace != ColorSpace.GRAY: saveimg = saveimg.toBGR() - + if not isinstance(filehandle_or_filename, basestring): - + fh = filehandle_or_filename if (not PIL_ENABLED): @@ -2321,14 +2321,14 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa mode = "jpeg" try: - saveimg.getPIL().save(fh, mode, **params) # The latest version of PIL / PILLOW supports webp, try this first, if not gracefully fallback - self.filehandle = fh #set the filename for future save operations - self.filename = "" - return 1 + saveimg.getPIL().save(fh, mode, **params) # The latest version of PIL / PILLOW supports webp, try this first, if not gracefully fallback + self.filehandle = fh #set the filename for future save operations + self.filename = "" + return 1 except Exception as e: - if mode.lower() != 'webp': - raise e - + if mode.lower() != 'webp': + raise e + if verbose: print(self.filename) @@ -2341,7 +2341,7 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa filename = tempfile.mkstemp(suffix=".png")[-1] else: filename = filehandle_or_filename - + #allow saving in webp format if mode == 'webp' or re.search('\.webp$', filename): try: @@ -2367,11 +2367,11 @@ def save(self, filehandle_or_filename="", mode="", verbose=False, temp=False, pa IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH * 3 ) result = webmEncode.EncodeRGB(image) - + if filehandle_or_filename.__class__.__name__ == 'StringIO': - filehandle_or_filename.write(result.data) + filehandle_or_filename.write(result.data) else: - file(filename.format("RGB"), "wb").write(result.data) + file(filename.format("RGB"), "wb").write(result.data) return 1 #if the user is passing kwargs use the PIL save method. if( params ): #usually this is just the compression rate for the image @@ -2423,63 +2423,63 @@ def copy(self): def upload(self,dest,api_key=None,api_secret=None, verbose = True): """ **SUMMARY** - + Uploads image to imgur or flickr or dropbox. In verbose mode URL values are printed. **PARAMETERS** - + * *api_key* - a string of the API key. * *api_secret* (required only for flickr and dropbox ) - a string of the API secret. * *verbose* - If verbose is true all values are printed to the screen - + **RETURNS** - + if uploading is successful - + - Imgur return the original image URL on success and None if it fails. - Flick returns True on success, else returns False. - dropbox returns True on success. - + **EXAMPLE** - + TO upload image to imgur:: - + >>> img = Image("lenna") >>> result = img.upload( 'imgur',"MY_API_KEY1234567890" ) >>> print "Uploaded To: " + result[0] - + To upload image to flickr:: - + >>> img.upload('flickr','api_key','api_secret') >>> img.invert().upload('flickr') #Once the api keys and secret keys are cached. - + To upload image to dropbox:: - + >>> img.upload('dropbox','api_key','api_secret') >>> img.invert().upload('dropbox') #Once the api keys and secret keys are cached. - + **NOTES** - + .. Warning:: This method requires two packages to be installed - + - PyCurl - flickr api. - dropbox - + .. Warning:: You must supply your own API key. See here: - + - http://imgur.com/register/api_anon - http://www.flickr.com/services/api/misc.api_keys.html - https://www.dropbox.com/developers/start/setup#python - + """ if ( dest=='imgur' ) : try: @@ -2791,11 +2791,11 @@ def medianFilter(self, window='',grayscale=False): see : http://en.wikipedia.org/wiki/Median_filter **Parameters** - + * *window* - should be in the form a tuple (win_x,win_y). Where win_x should be equal to win_y. By default it is set to 3x3, i.e window = (3x3). - + **Note** - + win_x and win_y should be greater than zero, a odd number and equal. For OpenCV versions <= 2.3.0 @@ -2803,7 +2803,7 @@ def medianFilter(self, window='',grayscale=False): For OpenCV versions >= 2.3.0 cv2.medianBlur function is called. - + """ try: import cv2 @@ -3181,13 +3181,13 @@ def stretch(self, thresh_low = 0, thresh_high = 255): return None def gammaCorrect(self, gamma = 1): - + """ **DESCRIPTION** Transforms an image according to Gamma Correction also known as Power Law Transform. - + **PARAMETERS** * *gamma* - A non-negative real number. @@ -3202,7 +3202,7 @@ def gammaCorrect(self, gamma = 1): >>> img.show() >>> img.gammaCorrect(1.5).show() >>> img.gammaCorrect(0.7).show() - + """ if gamma < 0: return "Gamma should be a non-negative real number" @@ -3325,19 +3325,19 @@ def meanColor(self, colorSpace = None): >>> colors = img.meanColor('Gray') # returns float of mean intensity. >>> colors = img.meanColor('YCrCb') # returns tuple in (Y,Cr,Cb) format. >>> colors = img.meanColor('HLS') # returns tuple in (H,L,S) format. - - + + """ - + if colorSpace == None: - return tuple(cv.Avg(self.getBitmap())[0:3]) - + return tuple(cv.Avg(self.getBitmap())[0:3]) + elif colorSpace == 'BGR': return tuple(cv.Avg(self.toBGR().getBitmap())[0:3]) - + elif colorSpace == 'RGB': return tuple(cv.Avg(self.toRGB().getBitmap())[0:3]) - + elif colorSpace == 'HSV': return tuple(cv.Avg(self.toHSV().getBitmap())[0:3]) @@ -3356,8 +3356,8 @@ def meanColor(self, colorSpace = None): else: logger.warning("Image.meanColor: There is no supported conversion to the specified colorspace. Use one of these as argument: 'BGR' , 'RGB' , 'HSV' , 'Gray' , 'XYZ' , 'YCrCb' , 'HLS' .") return None - - + + def findCorners(self, maxnum = 50, minquality = 0.04, mindistance = 1.0): """ @@ -3423,7 +3423,7 @@ def findCorners(self, maxnum = 50, minquality = 0.04, mindistance = 1.0): def findBlobs(self, threshval = -1, minsize=10, maxsize=0, threshblocksize=0, threshconstant=5,appx_level=3): """ - + **SUMMARY** Find blobs will look for continuous @@ -3557,8 +3557,8 @@ def getSkintoneMask(self, dilate_iter=0): **PARAMETERS** * *dilate_iter* - the number of times to run the dilation operation. - - + + **RETURNS** Returns a binary mask. @@ -4971,7 +4971,7 @@ def findLines(self, threshold=80, minlinelength=30, maxlinegap=10, cannyth1=50, """ em = self._getEdgeMap(cannyth1, cannyth2) - + linesFS = FeatureSet() if useStandard: lines = cv.HoughLines2(em, cv.CreateMemStorage(), cv.CV_HOUGH_STANDARD, 1.0, cv.CV_PI/180.0, threshold, minlinelength, maxlinegap) @@ -4982,7 +4982,7 @@ def findLines(self, threshold=80, minlinelength=30, maxlinegap=10, cannyth1=50, x,y = np.where(em.getGrayNumpy() > 128) # Put points in dictionary for fast checkout if point is white pts = dict((p, 1) for p in zip(x, y)) - + w, h = self.width-1, self.height-1 for rho, theta in lines[:nLines]: ep = [] @@ -5016,7 +5016,7 @@ def findLines(self, threshold=80, minlinelength=30, maxlinegap=10, cannyth1=50, ep = list(set(ep)) # remove duplicates if line crosses the image at corners ep.sort() brl = self.bresenham_line(ep[0], ep[1]) - + # Follow the points on Bresenham's line. Look for white points. # If the distance between two adjacent white points (dist) is less than or # equal maxpixelgap then consider them the same line. If dist is bigger @@ -5048,7 +5048,7 @@ def findLines(self, threshold=80, minlinelength=30, maxlinegap=10, cannyth1=50, last_p = p # last white point else: dist += 1 - + for l in ls: linesFS.append(Line(self, l)) linesFS = linesFS[:nLines] @@ -5059,7 +5059,7 @@ def findLines(self, threshold=80, minlinelength=30, maxlinegap=10, cannyth1=50, for l in lines[:nLines]: linesFS.append(Line(self, l)) - + return linesFS @@ -5484,7 +5484,7 @@ def transformPerspective(self, rotMatrix): rotMatrix = npArray2cvMat(rotMatrix) cv.WarpPerspective(self.getBitmap(), retVal, rotMatrix) return Image(retVal, colorSpace=self._colorSpace) - + def getPixel(self, x, y): """ **SUMMARY** @@ -5741,9 +5741,9 @@ def getHorzScanlineGray(self, row): def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): """ - + **SUMMARY** - + Consider you want to crop a image with the following dimension:: (x,y) @@ -5753,7 +5753,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): | | +--------------+ w (x1,y1) - + Crop attempts to use the x and y position variables and the w and h width and height variables to crop the image. When centered is false, x and y @@ -5781,7 +5781,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): * *centered* - Boolean - if True we treat the crop region as being the center coordinate and a width and height. If false we treat it as the top left corner of the crop region. * *smart* - Will make sure you don't try and crop outside the image size, so if your image is 100x100 and you tried a crop like img.crop(50,50,100,100), it will autoscale the crop to the max width. - + **RETURNS** @@ -5805,19 +5805,19 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): """ if smart: - if x > self.width: - x = self.width - elif x < 0: - x = 0 - elif y > self.height: - y = self.height - elif y < 0: - y = 0 - elif (x + w) > self.width: - w = self.width - x - elif (y + h) > self.height: - h = self.height - y - + if x > self.width: + x = self.width + elif x < 0: + x = 0 + elif y > self.height: + y = self.height + elif y < 0: + y = 0 + elif (x + w) > self.width: + w = self.width - x + elif (y + h) > self.height: + h = self.height - y + if(isinstance(x,np.ndarray)): x = x.tolist() if(isinstance(y,np.ndarray)): @@ -5833,7 +5833,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): elif(isinstance(x, (tuple,list)) and len(x) == 4 and isinstance(x[0],(int, long, float)) and y == None and w == None and h == None): - x,y,w,h = x + x,y,w,h = x # x of the form [(x,y),(x1,y1),(x2,y2),(x3,y3)] # x of the form [[x,y],[x1,y1],[x2,y2],[x3,y3]] # x of the form ([x,y],[x1,y1],[x2,y2],[x3,y3]) @@ -5855,7 +5855,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): else: logger.warning("x should be in the form ((x,y),(x1,y1),(x2,y2),(x3,y3))") return None - + # x,y of the form [x1,x2,x3,x4,x5....] and y similar elif(isinstance(x, (tuple,list)) and isinstance(y, (tuple,list)) and @@ -5913,7 +5913,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): h = np.abs(y[1]-x[1]) x = xt y = yt - + else: logger.warning("if x and y are tuple it should be in the form (x1,y1) and (x2,y2)") return None @@ -5946,7 +5946,7 @@ def crop(self, x , y = None, w = None, h = None, centered=False, smart=False): retVal = np.zeros((bottomROI[3],bottomROI[2],3),dtype='uint8') retVal= self.getNumpyCv2()[bottomROI[1]:bottomROI[1] + bottomROI[3],bottomROI[0]:bottomROI[0] + bottomROI[2],:] - + img = Image(retVal, colorSpace=self._colorSpace,cv2image = True) #Buffering the top left point (x, y) in a image. @@ -6731,7 +6731,7 @@ def adaptiveScale(self, resolution,fit=True): targetx = (resolution[0]-targetw)/2 targety = 0 img = img.scale(targetw,targeth) - + else: # we're going to crop instead if(self.width <= resolution[0] and self.height <= resolution[1] ): # center a too small image #we're too small just center the thing @@ -6770,7 +6770,7 @@ def adaptiveScale(self, resolution,fit=True): x = (self.width-resolution[0])/2 y = 0 img = img.crop(x,y,targetw,targeth) - + retVal[targety:targety + targeth,targetx:targetx + targetw,:] = img.getNumpyCv2() retVal = Image(retVal,cv2image = True) return(retVal) @@ -7096,8 +7096,8 @@ def embiggen(self, size=None, color=Color.BLACK, pos=None): """ if not isinstance(size, tuple) and size > 1: - size = (self.width * size, self.height * size) - + size = (self.width * size, self.height * size) + if( size == None or size[0] < self.width or size[1] < self.height ): logger.warning("image.embiggenCanvas: the size provided is invalid") @@ -7555,7 +7555,7 @@ def findTemplate(self, template_image = None, threshold = 5, method = "SQR_DIFF_ * CCORR - Cross correlation * CCORR_NORM - Normalize cross correlation * *grayscale* - Boolean - If false, template Match is found using BGR image. - + **EXAMPLE** >>> image = Image("/path/to/img.png") @@ -7657,7 +7657,7 @@ def findTemplateOnce(self, template_image = None, threshold = 0.2, method = "SQR This method returns the single best match if and only if that match less than the threshold (greater than in the case of some methods). - + **PARAMETERS** * *template_image* - The template image. @@ -7671,7 +7671,7 @@ def findTemplateOnce(self, template_image = None, threshold = 0.2, method = "SQR * CCORR - Cross correlation * CCORR_NORM - Normalize cross correlation * *grayscale* - Boolean - If false, template Match is found using BGR image. - + **EXAMPLE** >>> image = Image("/path/to/img.png") @@ -8421,9 +8421,9 @@ def findKeypointMatch(self,template,quality=500.00,minDist=0.2,minMatch=0.4): except: warnings.warn("Can't Match Keypoints without OpenCV >= 2.3.0") return - + if template == None: - return None + return None fs = FeatureSet() skp,sd = self._getRawKeypoints(quality) tkp,td = template._getRawKeypoints(quality) @@ -8449,7 +8449,7 @@ def findKeypointMatch(self,template,quality=500.00,minDist=0.2,minMatch=0.4): if( result[i] ): lhs.append((tkp[i].pt[1], tkp[i].pt[0])) rhs.append((skp[idx[i]].pt[0], skp[idx[i]].pt[1])) - + rhs_pt = np.array(rhs) lhs_pt = np.array(lhs) if( len(rhs_pt) < 16 or len(lhs_pt) < 16 ): @@ -8458,16 +8458,16 @@ def findKeypointMatch(self,template,quality=500.00,minDist=0.2,minMatch=0.4): (homography,mask) = cv2.findHomography(lhs_pt,rhs_pt,cv2.RANSAC, ransacReprojThreshold=1.0 ) w = template.width h = template.height - + pts = np.array([[0,0],[0,h],[w,h],[w,0]], dtype="float32") - + pPts = cv2.perspectiveTransform(np.array([pts]), homography) - + pt0i = (pPts[0][0][1], pPts[0][0][0]) pt1i = (pPts[0][1][1], pPts[0][1][0]) pt2i = (pPts[0][2][1], pPts[0][2][0]) pt3i = (pPts[0][3][1], pPts[0][3][0]) - + #construct the feature set and return it. fs = FeatureSet() fs.append(KeypointMatch(self,template,(pt0i,pt1i,pt2i,pt3i),homography)) @@ -9690,7 +9690,7 @@ def floodFillToMask(self, points,tolerance=None,color=Color.WHITE,lower=None,upp color = color.tolist() elif( isinstance(color,dict) ): color = (color['R'],color['G'],color['B']) - + if( isinstance(points,tuple) ): points = np.array(points) @@ -11271,7 +11271,7 @@ def edgeIntersections(self, pt0, pt1, width=1, canny1=0, canny2=100): def fitContour(self, initial_curve, window=(11,11), params=(0.1,0.1,0.1),doAppx=True,appx_level=1): """ - + **SUMMARY** This method tries to fit a list of points to lines in the image. The list of points @@ -11300,7 +11300,7 @@ def fitContour(self, initial_curve, window=(11,11), params=(0.1,0.1,0.1),doAppx= * Continuity * Curvature * Image (Gradient) - + Each Weighted by Specified Parameter: Total Energy = Alpha*Continuity + Beta*Curvature + Gamma*Image @@ -11354,113 +11354,113 @@ def fitContour(self, initial_curve, window=(11,11), params=(0.1,0.1,0.1),doAppx= return retVal def fitEdge(self,guess,window=10,threshold=128, measurements=5, darktolight=True, lighttodark=True,departurethreshold=1): - """ - **SUMMARY** - - Fit edge in a binary/gray image using an initial guess and the least squares method. - The functions returns a single line - - **PARAMETERS** - - * *guess* - A tuples of the form ((x0,y0),(x1,y1)) which is an approximate guess - * *window* - A window around the guess to search. - * *threshold* - the threshold above which we count a pixel as a line - * *measurements* -the number of line projections to use for fitting the line - TODO: Constrict a line to black to white or white to black - Right vs. Left orientation. - - **RETURNS** - - A a line object - **EXAMPLE** - """ - searchLines = FeatureSet() - fitPoints = FeatureSet() - x1 = guess[0][0] - x2 = guess[1][0] - y1 = guess[0][1] - y2 = guess[1][1] - dx = float((x2-x1))/(measurements-1) - dy = float((y2-y1))/(measurements-1) - s = np.zeros((measurements,2)) - lpstartx = np.zeros(measurements) - lpstarty = np.zeros(measurements) - lpendx = np.zeros(measurements) - lpendy = np.zeros(measurements) - linefitpts = np.zeros((measurements,2)) - - #obtain equation for initial guess line - if( x1==x2): #vertical line must be handled as special case since slope isn't defined - m=0 - mo = 0 - b = x1 - for i in xrange(0, measurements): - s[i][0] = x1 - s[i][1] = y1 + i * dy - lpstartx[i] = s[i][0] + window - lpstarty[i] = s[i][1] - lpendx[i] = s[i][0] - window - lpendy[i] = s[i][1] - Cur_line = Line(self,((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i]))) - ((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i])) = Cur_line.cropToImageEdges().end_points - - searchLines.append(Cur_line) - tmp = self.getThresholdCrossing((int(lpstartx[i]),int(lpstarty[i])),(int(lpendx[i]),int(lpendy[i])),threshold=threshold,lighttodark=lighttodark, darktolight=darktolight, departurethreshold=departurethreshold) - fitPoints.append(Circle(self,tmp[0],tmp[1],3)) - linefitpts[i] = tmp - - else: - m = float((y2-y1))/(x2-x1) - b = y1 - m*x1 - mo = -1/m #slope of orthogonal line segments - - #obtain points for measurement along the initial guess line - for i in xrange(0, measurements): - s[i][0] = x1 + i * dx - s[i][1] = y1 + i * dy - fx = (math.sqrt(math.pow(window,2))/(1+mo))/2 - fy = fx * mo - lpstartx[i] = s[i][0] + fx - lpstarty[i] = s[i][1] + fy - lpendx[i] = s[i][0] - fx - lpendy[i] = s[i][1] - fy - Cur_line = Line(self,((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i]))) - ((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i])) = Cur_line.cropToImageEdges().end_points - searchLines.append(Cur_line) - tmp = self.getThresholdCrossing((int(lpstartx[i]),int(lpstarty[i])),(int(lpendx[i]),int(lpendy[i])),threshold=threshold,lighttodark=lighttodark, darktolight=darktolight,departurethreshold=departurethreshold) - fitPoints.append((tmp[0],tmp[1])) - linefitpts[i] = tmp - - badpts = [] - for j in range(len(linefitpts)): - if (linefitpts[j,0] == -1) or (linefitpts[j,1] == -1): - badpts.append(j) - for pt in badpts: - linefitpts = np.delete(linefitpts,pt,axis=0) - - x = linefitpts[:,0] - y = linefitpts[:,1] - ymin = np.min(y) - ymax = np.max(y) - xmax = np.max(x) - xmin = np.min(x) - - if( (xmax-xmin) > (ymax-ymin) ): - # do the least squares - A = np.vstack([x,np.ones(len(x))]).T - m,c = nla.lstsq(A,y)[0] - y0 = int(m*xmin+c) - y1 = int(m*xmax+c) - finalLine = Line(self,((xmin,y0),(xmax,y1))) - else: - # do the least squares - A = np.vstack([y,np.ones(len(y))]).T - m,c = nla.lstsq(A,x)[0] - x0 = int(ymin*m+c) - x1 = int(ymax*m+c) - finalLine = Line(self,((x0,ymin),(x1,ymax))) - - return finalLine, searchLines, fitPoints + """ + **SUMMARY** + + Fit edge in a binary/gray image using an initial guess and the least squares method. + The functions returns a single line + + **PARAMETERS** + + * *guess* - A tuples of the form ((x0,y0),(x1,y1)) which is an approximate guess + * *window* - A window around the guess to search. + * *threshold* - the threshold above which we count a pixel as a line + * *measurements* -the number of line projections to use for fitting the line + TODO: Constrict a line to black to white or white to black + Right vs. Left orientation. + + **RETURNS** + + A a line object + **EXAMPLE** + """ + searchLines = FeatureSet() + fitPoints = FeatureSet() + x1 = guess[0][0] + x2 = guess[1][0] + y1 = guess[0][1] + y2 = guess[1][1] + dx = float((x2-x1))/(measurements-1) + dy = float((y2-y1))/(measurements-1) + s = np.zeros((measurements,2)) + lpstartx = np.zeros(measurements) + lpstarty = np.zeros(measurements) + lpendx = np.zeros(measurements) + lpendy = np.zeros(measurements) + linefitpts = np.zeros((measurements,2)) + + #obtain equation for initial guess line + if( x1==x2): #vertical line must be handled as special case since slope isn't defined + m=0 + mo = 0 + b = x1 + for i in xrange(0, measurements): + s[i][0] = x1 + s[i][1] = y1 + i * dy + lpstartx[i] = s[i][0] + window + lpstarty[i] = s[i][1] + lpendx[i] = s[i][0] - window + lpendy[i] = s[i][1] + Cur_line = Line(self,((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i]))) + ((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i])) = Cur_line.cropToImageEdges().end_points + + searchLines.append(Cur_line) + tmp = self.getThresholdCrossing((int(lpstartx[i]),int(lpstarty[i])),(int(lpendx[i]),int(lpendy[i])),threshold=threshold,lighttodark=lighttodark, darktolight=darktolight, departurethreshold=departurethreshold) + fitPoints.append(Circle(self,tmp[0],tmp[1],3)) + linefitpts[i] = tmp + + else: + m = float((y2-y1))/(x2-x1) + b = y1 - m*x1 + mo = -1/m #slope of orthogonal line segments + + #obtain points for measurement along the initial guess line + for i in xrange(0, measurements): + s[i][0] = x1 + i * dx + s[i][1] = y1 + i * dy + fx = (math.sqrt(math.pow(window,2))/(1+mo))/2 + fy = fx * mo + lpstartx[i] = s[i][0] + fx + lpstarty[i] = s[i][1] + fy + lpendx[i] = s[i][0] - fx + lpendy[i] = s[i][1] - fy + Cur_line = Line(self,((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i]))) + ((lpstartx[i],lpstarty[i]),(lpendx[i],lpendy[i])) = Cur_line.cropToImageEdges().end_points + searchLines.append(Cur_line) + tmp = self.getThresholdCrossing((int(lpstartx[i]),int(lpstarty[i])),(int(lpendx[i]),int(lpendy[i])),threshold=threshold,lighttodark=lighttodark, darktolight=darktolight,departurethreshold=departurethreshold) + fitPoints.append((tmp[0],tmp[1])) + linefitpts[i] = tmp + + badpts = [] + for j in range(len(linefitpts)): + if (linefitpts[j,0] == -1) or (linefitpts[j,1] == -1): + badpts.append(j) + for pt in badpts: + linefitpts = np.delete(linefitpts,pt,axis=0) + + x = linefitpts[:,0] + y = linefitpts[:,1] + ymin = np.min(y) + ymax = np.max(y) + xmax = np.max(x) + xmin = np.min(x) + + if( (xmax-xmin) > (ymax-ymin) ): + # do the least squares + A = np.vstack([x,np.ones(len(x))]).T + m,c = nla.lstsq(A,y)[0] + y0 = int(m*xmin+c) + y1 = int(m*xmax+c) + finalLine = Line(self,((xmin,y0),(xmax,y1))) + else: + # do the least squares + A = np.vstack([y,np.ones(len(y))]).T + m,c = nla.lstsq(A,x)[0] + x0 = int(ymin*m+c) + x1 = int(ymax*m+c) + finalLine = Line(self,((x0,ymin),(x1,ymax))) + + return finalLine, searchLines, fitPoints def getThresholdCrossing(self, pt1, pt2, threshold=128, darktolight=True, lighttodark=True, departurethreshold=1): """ @@ -11537,7 +11537,7 @@ def getThresholdCrossing(self, pt1, pt2, threshold=128, darktolight=True, lightt retVal = (-1,-1) #print 'Edgepoint not found.' return retVal - + def getDiagonalScanlineGrey(self, pt1, pt2): """ @@ -11558,7 +11558,7 @@ def getDiagonalScanlineGrey(self, pt1, pt2): >>> img = Image("lenna") >>> sl = img.getDiagonalScanlineGrey((100,200),(300,400)) - + **SEE ALSO** @@ -11572,7 +11572,7 @@ def getDiagonalScanlineGrey(self, pt1, pt2): #self = self._getGrayscaleBitmap() width = round(math.sqrt(math.pow(pt2[0]-pt1[0],2) + math.pow(pt2[1]-pt1[1],2))) retVal = np.zeros(width) - + for x in range(0, retVal.size): xind = pt1[0] + int(round((pt2[0]-pt1[0])*x/retVal.size)) yind = pt1[1] + int(round((pt2[1]-pt1[1])*x/retVal.size)) @@ -11840,7 +11840,7 @@ def sobel(self, xorder=1, yorder=1, doGray=True, aperture=5, aperature=None): def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): """ - + **DESCRIPTION** Tracking the object surrounded by the bounding box in the given @@ -11852,7 +11852,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): * *ts* - TrackSet - SimpleCV.Features.TrackSet. * *img* - Image - Image to be tracked or list - List of Images to be tracked. * *bb* - tuple - Bounding Box tuple (x, y, w, h) - + **Optional Parameters** @@ -11953,11 +11953,11 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): numM - Number of points to be tracked in the bounding box in height direction. default: 10 - + numN - Number of points to be tracked in the bounding box in width direction. default: 10 - + margin - Margin around the bounding box. default: 5 @@ -11974,7 +11974,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): - LK - SURF - MFTrack - + **RETURNS** @@ -11985,7 +11985,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): **HOW TO** >>> ts = img.track("camshift", img=img1, bb=bb) - + Here TrackSet is returned. All the necessary attributes will be included in the trackset. After getting the trackset you need not provide the bounding box or image. You provide TrackSet as parameter to track(). @@ -12009,7 +12009,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): img = cam.getImage() ts = img.track("camshift",ts,img0,bb) - + now here in first loop iteration since ts is empty, img0 and bb will be considered. New tracking object will be created and added in ts (TrackSet) After first iteration, ts is not empty and hence the previous @@ -12027,21 +12027,21 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): Using Optional Parameters: for CAMShift - + >>> ts = [] >>> ts = img.track("camshift", ts, img1, bb, lower=(40, 100, 100), upper=(100, 250, 250)) You can provide some/all/None of the optional parameters listed for CAMShift. for LK - + >>> ts = [] >>> ts = img.track("lk", ts, img1, bb, maxCorners=4000, qualityLevel=0.5, minDistance=3) You can provide some/all/None of the optional parameters listed for LK. for SURF - + >>> ts = [] >>> ts = img.track("surf", ts, img1, bb, eps_val=0.7, min_samples=8, distance=200) @@ -12075,7 +12075,7 @@ def track(self, method="CAMShift", ts=None, img=None, bb=None, **kwargs): k-means. Median Flow Tracker: - + Media Flow Tracker is the base tracker that is used in OpenTLD. It is based on Optical Flow. It calculates optical flow of the points in the bounding box from frame 1 to frame 2 and from frame 2 to frame 1 and using back track error, removes @@ -12260,7 +12260,7 @@ def rotateRight(self): # same as 270 >>>> img.rotateRight().show() """ - + return self.rotate270() @@ -12287,7 +12287,7 @@ def rotate180(self): def verticalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=False): """ - + **DESCRIPTION** This method generates histogram of the number of grayscale pixels @@ -12297,12 +12297,12 @@ def verticalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=False is helpful for doing basic morphological analysis. **PARAMETERS** - + * *bins* - The number of bins to use. * *threshold* - The grayscale threshold. We count pixels greater than this value. * *normalize* - If normalize is true we normalize the bin countsto sum to one. Otherwise we return the number of pixels. * *forPlot* - If this is true we return the bin indicies, the bin counts, and the bin widths as a tuple. We can use these values in pyplot.bar to quickly plot the histogram. - + **RETURNS** @@ -12311,16 +12311,16 @@ def verticalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=False contains a list of bin labels, the bin counts, and the bin widths. This tuple can be used to plot the histogram using matplotlib.pyplot.bar function. - - + + **EXAMPLE** - + >>> import matplotlib.pyplot as plt >>> img = Image('lenna') >>> plt.bar(*img.verticalHistogram(threshold=128,bins=10,normalize=False,forPlot=True),color='y') >>> plt.show() - - + + **NOTES** See: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html @@ -12345,7 +12345,7 @@ def verticalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=False def horizontalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=False): """ - + **DESCRIPTION** This method generates histogram of the number of grayscale pixels @@ -12355,13 +12355,13 @@ def horizontalHistogram(self, bins=10, threshold=128,normalize=False,forPlot=Fal is helpful for doing basic morphological analysis. **PARAMETERS** - + * *bins* - The number of bins to use. * *threshold* - The grayscale threshold. We count pixels greater than this value. * *normalize* - If normalize is true we normalize the bin counts to sum to one. Otherwise we return the number of pixels. * *forPlot* - If this is true we return the bin indicies, the bin counts, and the bin widths as a tuple. We can use these values in pyplot.bar to quickly plot the histogram. - - + + **RETURNS** The default settings return the raw bin counts moving from top to @@ -12408,14 +12408,14 @@ def getLineScan(self,x=None,y=None,pt1=None,pt2=None,channel = -1): than can be manipulated further. **PARAMETERS** - + * *x* - Take a vertical line scan at the column x. * *y* - Take a horizontal line scan at the row y. * *pt1* - Take a line scan between two points on the line the line scan values always go in the +x direction * *pt2* - Second parameter for a non-vertical or horizontal line scan. * *channel* - To select a channel. eg: selecting a channel RED,GREEN or BLUE. If set to -1 it operates with gray scale values - - + + **RETURNS** A SimpleCV.LineScan object or None if the method fails. @@ -12502,15 +12502,15 @@ def setLineScan(self, linescan,x=None,y=None,pt1=None,pt2=None,channel = -1): This function helps you put back the linescan in the image. **PARAMETERS** - + * *linescan* - LineScan object * *x* - put line scan at the column x. * *y* - put line scan at the row y. * *pt1* - put line scan between two points on the line the line scan values always go in the +x direction * *pt2* - Second parameter for a non-vertical or horizontal line scan. * *channel* - To select a channel. eg: selecting a channel RED,GREEN or BLUE. If set to -1 it operates with gray scale values - - + + **RETURNS** A SimpleCV.Image @@ -12524,7 +12524,7 @@ def setLineScan(self, linescan,x=None,y=None,pt1=None,pt2=None,channel = -1): >>> newimg = img.putLineScan(a, x=50) >>> newimg.show() # This will show you a black line in column 50. - + """ #retVal = self.toGray() if channel == -1: @@ -12602,7 +12602,7 @@ def setLineScan(self, linescan,x=None,y=None,pt1=None,pt2=None,channel = -1): def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel = None): """ - + **SUMMARY** This function easily lets you replace the linescan in the image. @@ -12613,7 +12613,7 @@ def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel LineScan from. **PARAMETERS** - + * *linescan* - LineScan object * *x* - put line scan at the column x. * *y* - put line scan at the row y. @@ -12621,7 +12621,7 @@ def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel * *pt2* - Second parameter for a non-vertical or horizontal line scan. * *channel* - To select a channel. eg: selecting a channel RED,GREEN or BLUE. If set to -1 it operates with gray scale values - + **RETURNS** A SimpleCV.Image @@ -12635,12 +12635,12 @@ def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel >>> newimg = img.replaceLineScan(a) >>> newimg.show() # This will show you a black line in column 10. - + """ - + if x is None and y is None and pt1 is None and pt2 is None and channel is None: - + if linescan.channel == -1: img = np.copy(self.getGrayNumpy()) else: @@ -12674,7 +12674,7 @@ def replaceLineScan(self, linescan, x=None, y=None, pt1=None, pt2=None, channel for pt in pts: img[pt[0],pt[1]]=ls[idx] idx = idx+1 - + if linescan.channel == -1: retVal = Image(img) else: @@ -13473,7 +13473,7 @@ def findBlobsFromWatershed(self,mask=None,erode=2,dilate=2,useMyMask=False,inver Color.WATERSHED_FG - The watershed foreground color Color.WATERSHED_BG - The watershed background color Color.WATERSHED_UNSURE - The watershed not sure if fg or bg color. - + """ newmask = self.watershed(mask,erode,dilate,useMyMask) if( invert ): @@ -13491,12 +13491,12 @@ def maxValue(self,locations=False): * *locations* - If true return the location of pixels that have this value. - + **RETURNS** The maximum value and optionally the list of points as a list of (x,y) tuples. - + **EXAMPLE** >>> img = Image("lenna") @@ -13513,7 +13513,7 @@ def maxValue(self,locations=False): else: val = np.max(self.getGrayNumpy()) return int(val) - + def minValue(self,locations=False): """ **SUMMARY** @@ -13525,12 +13525,12 @@ def minValue(self,locations=False): * *locations* - If true return the location of pixels that have this value. - + **RETURNS** The minimum value and optionally the list of points as a list of (x,y) tuples. - + **EXAMPLE** >>> img = Image("lenna") @@ -13548,7 +13548,7 @@ def minValue(self,locations=False): val = np.min(self.getGrayNumpy()) return int(val) - + def findKeypointClusters(self, num_of_clusters = 5, order='dsc', flavor='surf'): ''' This function is meant to try and find interesting areas of an @@ -13566,30 +13566,30 @@ def findKeypointClusters(self, num_of_clusters = 5, order='dsc', flavor='surf'): **EXAMPLE** - + >>> img = Image('simplecv') >>> clusters = img.findKeypointClusters() >>> clusters.draw() >>> img.show() **RETURNS** - + FeatureSet ''' if flavor.lower() == 'corner': - keypoints = self.findCorners() #fallback to corners + keypoints = self.findCorners() #fallback to corners else: - keypoints = self.findKeypoints(flavor=flavor.upper()) #find the keypoints + keypoints = self.findKeypoints(flavor=flavor.upper()) #find the keypoints if keypoints == None or keypoints <= 0: - return None - + return None + xypoints = np.array([(f.x,f.y) for f in keypoints]) xycentroids, xylabels = scv.kmeans2(xypoints, num_of_clusters) # find the clusters of keypoints xycounts = np.array([]) - + for i in range(num_of_clusters ): #count the frequency of occurences for sorting xycounts = np.append(xycounts, len(np.where(xylabels == i)[-1])) - + merged = np.msort(np.hstack((np.vstack(xycounts), xycentroids))) #sort based on occurence clusters = [c[1:] for c in merged] # strip out just the values ascending if order.lower() == 'dsc': @@ -13599,7 +13599,7 @@ def findKeypointClusters(self, num_of_clusters = 5, order='dsc', flavor='surf'): for x,y in clusters: #map the values to a feature set f = Corner(self, x, y) fs.append(f) - + return fs def getFREAKDescriptor(self, flavor="SURF"): @@ -13649,7 +13649,7 @@ def getFREAKDescriptor(self, flavor="SURF"): if int(cv2.__version__.replace('.','0'))<20402: warnings.warn("OpenCV version >= 2.4.2 requierd") return None - + flavors = ["SIFT", "SURF", "BRISK", "ORB", "STAR", "MSER", "FAST", "Dense"] if flavor not in flavors: warnings.warn("Unkown Keypoints detector. Returning None.") @@ -13670,9 +13670,9 @@ def getGrayHistogramCounts(self, bins = 255, limit=-1): This function returns a list of tuples of greyscale pixel counts by frequency. This would be useful in determining the dominate pixels (peaks) of the greyscale image. - + **PARAMETERS** - + * *bins* - The number of bins for the hisogram, defaults to 255 (greyscale) * *limit* - The number of counts to return, default is all @@ -13788,7 +13788,7 @@ def grayPeaks(self, bins = 255, delta = 0, lookahead = 15): #set algorithm to only find maxima now mn = -np.Inf mx = -np.Inf - + retVal = [] for intensity, pixelcount in maxtab: retVal.append((intensity, pixelcount / float(self.width * self.height))) @@ -13822,14 +13822,14 @@ def tvDenoising(self, gray=False, weight=50, eps=0.0002, max_iter=200, resize=1) mostly to speed up the filter. **NOTE** - + This function requires Scikit-image library to be installed! To install scikit-image library run:: - + sudo pip install -U scikit-image Read More: http://scikit-image.org/ - + """ try: @@ -13837,9 +13837,9 @@ def tvDenoising(self, gray=False, weight=50, eps=0.0002, max_iter=200, resize=1) except ImportError: logger.warn('Scikit-image Library not installed!') return None - + img = self.copy() - + if resize <= 0: print('Enter a valid resize value') return None @@ -13865,7 +13865,7 @@ def tvDenoising(self, gray=False, weight=50, eps=0.0002, max_iter=200, resize=1) return retVal.resize(int(retVal.width/resize),int(retVal.width/resize)) else: return retVal - + def motionBlur(self,intensity=15, direction='NW'): """ **SUMMARY** @@ -13894,11 +13894,11 @@ def motionBlur(self,intensity=15, direction='NW'): >>> i = Image ('lenna') >>> mb = i.motionBlur() >>> mb.show() - + """ mid = int(intensity/2) tmp = np.identity(intensity) - + if intensity == 0: warnings.warn("0 intensity means no blurring") return self @@ -13931,10 +13931,10 @@ def motionBlur(self,intensity=15, direction='NW'): else: warnings.warn("Please enter a proper direction") return None - + retval=self.convolve(kernel=kernel/div) return retval - + def recognizeFace(self, recognizer=None): """ **SUMMARY** @@ -14099,7 +14099,7 @@ def prewitt(self): **NOTES** Read more at: http://en.wikipedia.org/wiki/Prewitt_operator - + """ img = self.copy() grayimg = img.grayscale() @@ -14132,7 +14132,7 @@ def edgeSnap(self,pointList,step = 1): **RETURNS** * FeatureSet * - A FeatureSet of Lines - + **EXAMPLE** >>> image = Image("logo").edges() @@ -14143,7 +14143,7 @@ def edgeSnap(self,pointList,step = 1): imgArray = self.getGrayNumpy() c1 = np.count_nonzero(imgArray ) c2 = np.count_nonzero(imgArray - 255) - + #checking that all values are 0 and 255 if( c1 + c2 != imgArray.size): raise ValueError("Image must be binary") @@ -14157,7 +14157,7 @@ def edgeSnap(self,pointList,step = 1): for point in pointList[1:None]: finalList += self._edgeSnap2(last,point,step) last = point - + last = finalList[0] for point in finalList: featureSet.append(Line(self,(last,point))) @@ -14185,7 +14185,7 @@ def _edgeSnap2(self,start,end,step): **RETURNS** * List * - A list of tuples , each tuple contains (x,y) values - + """ @@ -14204,14 +14204,14 @@ def _edgeSnap2(self,start,end,step): #List of Edge Points. finalList = [] i = 0 - + #Closest any point has ever come to the end point overallMinDist = None while i < len(line) : - + x,y = line[i] - + #Get the matrix of points fromx around current point. region = edgeMap[x-box:x+box,y-box:y+box] @@ -14223,7 +14223,7 @@ def _edgeSnap2(self,start,end,step): #Index of all Edge points indexList = np.argwhere(region>0) if (indexList.size > 0): - + #Center the coordinates around the point indexList -= box minDist = None @@ -14256,9 +14256,9 @@ def _edgeSnap2(self,start,end,step): #Add the point to list and redefine the line line =[(x+dx,y+dy)] + self.bresenham_line((x+dx, y+dy), end) finalList += [(x+dx,y+dy)] - + i = 0 - + i += step finalList += [end] return finalList @@ -14279,7 +14279,7 @@ def motionBlur(self,intensity=15, angle = 0): * *angle* - Angle in degrees at which motion blur will occur. Positive is Clockwise and negative is Anti-Clockwise. 0 blurs from left to right - + **RETURNS** @@ -14289,28 +14289,28 @@ def motionBlur(self,intensity=15, angle = 0): >>> img = Image ('lenna') >>> blur = img.motionBlur(40,45) >>> blur.show() - + """ - + intensity = int(intensity) if(intensity <= 1): logger.warning('power less than 1 will result in no change') return self - + kernel = np.zeros((intensity,intensity)) - + rad = math.radians(angle) x1,y1 = intensity/2,intensity/2 - + x2 = int(x1-(intensity-1)/2*math.sin(rad)) y2 = int(y1 -(intensity-1)/2*math.cos(rad)) - + line = self.bresenham_line((x1,y1),(x2,y2)) - + x = [p[0] for p in line] y = [p[1] for p in line] - + kernel[x,y] = 1 kernel = kernel/len(line) return self.convolve(kernel = kernel) @@ -14323,7 +14323,7 @@ def getLightness(self): Lightness method. **Parameters** - + None **RETURNS** @@ -14334,7 +14334,7 @@ def getLightness(self): >>> img = Image ('lenna') >>> out = img.getLightness() >>> out.show() - + **NOTES** Algorithm used: value = (MAX(R,G,B) + MIN(R,G,B))/2 @@ -14358,7 +14358,7 @@ def getLuminosity(self): Luminosity method. **Parameters** - + None **RETURNS** @@ -14369,7 +14369,7 @@ def getLuminosity(self): >>> img = Image ('lenna') >>> out = img.getLuminosity() >>> out.show() - + **NOTES** Algorithm used: value = 0.21 R + 0.71 G + 0.07 B @@ -14393,7 +14393,7 @@ def getAverage(self): the R,G,B values. **Parameters** - + None **RETURNS** @@ -14404,7 +14404,7 @@ def getAverage(self): >>> img = Image ('lenna') >>> out = img.getAverage() >>> out.show() - + **NOTES** Algorithm used: value = (R+G+B)/3 @@ -14419,7 +14419,7 @@ def getAverage(self): return None return Image(retVal,cv2image=True) - + def smartRotate(self,bins=18,point = [-1,-1],auto = True,threshold=80,minLength=30,maxGap=10,t1=150,t2=200,fixed = True): """ **SUMMARY** @@ -14428,31 +14428,31 @@ def smartRotate(self,bins=18,point = [-1,-1],auto = True,threshold=80,minLength= approximately parellel to horizontal or vertical edges. **Parameters** - - + + * *bins* - The number of bins the lines will be grouped into. - + * *point* - the point about which to rotate, refer :py:meth:`rotate` - + * *auto* - If true point will be computed to the mean of centers of all the lines in the selected bin. If auto is True, value of point is ignored - + * *threshold* - which determines the minimum "strength" of the line refer :py:meth:`findLines` for details. - + * *minLength* - how many pixels long the line must be to be returned, refer :py:meth:`findLines` for details. - + * *maxGap* - how much gap is allowed between line segments to consider them the same line .refer to :py:meth:`findLines` for details. - + * *t1* - thresholds used in the edge detection step, refer to :py:meth:`_getEdgeMap` for details. - + * *t2* - thresholds used in the edge detection step, refer to :py:meth:`_getEdgeMap` for details. - + * *fixed* - if fixed is true,keep the original image dimensions, otherwise scale the image to fit the rotation , refer to :py:meth:`rotate` @@ -14467,14 +14467,14 @@ def smartRotate(self,bins=18,point = [-1,-1],auto = True,threshold=80,minLength= """ lines = self.findLines(threshold, minLength, maxGap, t1,t2) - + if(len(lines) == 0): logger.warning("No lines found in the image") return self # Initialize empty bins binn = [[] for i in range(bins)] - + #Convert angle to bin number conv = lambda x:int(x+90)/bins @@ -14484,10 +14484,10 @@ def smartRotate(self,bins=18,point = [-1,-1],auto = True,threshold=80,minLength= #computing histogram, value of each column is total length of all lines #in the bin hist = [ sum([line.length() for line in lines]) for lines in binn] - + #The maximum histogram index = np.argmax(np.array(hist)) - + #Good ol weighted mean, for the selected bin avg = sum([line.angle()*line.length() for line in binn[index]])/sum([line.length() for line in binn[index] ]) @@ -14598,7 +14598,7 @@ def getNormalizedHueHistogram(self,roi=None): ImageClass.backProjectHueHistogram() ImageClass.findBlobsFromHueHistogram() - + """ try: import cv2 @@ -14655,14 +14655,14 @@ def backProjectHueHistogram(self,model,smooth=True,fullColor=False,threshold=Non **SEE ALSO** ImageClass.getNormalizedHueHistogram() ImageClass.findBlobsFromHueHistogram() - + """ try: import cv2 except ImportError: warnings.warn("OpenCV >= 2.3 required to use this.") return None - + if( model is None ): warnings.warn('Backproject requires a model') return None @@ -14689,7 +14689,7 @@ def backProjectHueHistogram(self,model,smooth=True,fullColor=False,threshold=Non warnings.warn('Backproject model does not appear to be valid') return None - + def findBlobsFromHueHistogram(self,model,threshold=1,smooth=True,minsize=10,maxsize=None): """ **SUMMARY** @@ -14726,10 +14726,10 @@ def findBlobsFromHueHistogram(self,model,threshold=1,smooth=True,minsize=10,maxs >>>> blobs.show() **SEE ALSO** - + ImageClass.getNormalizedHueHistogram() ImageClass.backProjectHueHistogram() - + """ newMask = self.backProjectHueHistogram(model,smooth,fullColor=False,threshold=threshold) return self.findBlobsFromMask(newMask,minsize=minsize,maxsize=maxsize) diff --git a/SimpleCV/LineScan.py b/SimpleCV/LineScan.py index 242eec29d..c3241e4d0 100644 --- a/SimpleCV/LineScan.py +++ b/SimpleCV/LineScan.py @@ -64,7 +64,7 @@ def __init__(self, args, **kwargs): if key == "channel": if kwargs[key] is not None: self.channel = kwargs[key] - + if(self.pointLoc is None): self.pointLoc = zip(range(0,len(self)),range(0,len(self))) @@ -89,7 +89,7 @@ def __getslice__(self, i, j): return self.__getitem__(slice(i,j)) def __sub__(self,other): - + if len(self) == len(other): retVal = LineScan(map(operator.sub,self,other)) else: @@ -99,7 +99,7 @@ def __sub__(self,other): return retVal def __add__(self,other): - + if len(self) == len(other): retVal = LineScan(map(operator.add,self,other)) else: @@ -248,7 +248,7 @@ def scale(self,value_range=(0,1)): >>>> plt.plot(sl) >>>> plt.plot(sl.scale(value_range(0,255))) >>>> plt.show() - + **SEE ALSO** """ @@ -1085,7 +1085,7 @@ def medianFilter(self, kernel_size=5): if kernel_size % 2 == 0: kernel_size-=1 print("Kernel Size should be odd. New kernel size =" , (kernel_size)) - + medfilt_array = medfilt(np.asarray(self[:]), kernel_size) retVal = LineScan(medfilt_array.astype("uint8").tolist(), image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2, x=self.col, y=self.row) retVal._update(self) @@ -1146,7 +1146,7 @@ def runningAverage(self, diameter=3, algo="uniform"): >>> plt.plot(ra) >>> plt.plot(rag) >>> plt.show() - + """ if diameter%2 == 0: @@ -1190,7 +1190,7 @@ def findPeaks(self, window = 30, delta = 3): >>> print peaks >>> peaks10 = ls.findPeaks(window=10) >>> print peaks10 - + """ maximum = -np.Inf @@ -1235,7 +1235,7 @@ def findValleys(self,window = 30, delta = 3 ): >>> print valleys >>> valleys10 = ls.findValleys(window=10) >>> print valleys10 - + """ minimum = np.Inf width = int(window/2.0) @@ -1251,7 +1251,7 @@ def findValleys(self,window = 30, delta = 3 ): peaks.append((minpos, minimum)) minimum = np.Inf return peaks - + def fitSpline(self,degree=2): """ @@ -1278,7 +1278,7 @@ def fitSpline(self,degree=2): >>> plt.show() >>> plt.plot(spline) >>> plt.show() - + **NOTES** Implementation taken from http://www.scipy.org/Cookbook/Interpolation @@ -1297,4 +1297,3 @@ def fitSpline(self,degree=2): cj = sps.cspline1d(y) retVal = sps.cspline1d_eval(cj,newx,dx=dx,x0=x[0]) return retVal - diff --git a/SimpleCV/MachineLearning/KNNClassifier.py b/SimpleCV/MachineLearning/KNNClassifier.py index f257325af..7bbb1daec 100644 --- a/SimpleCV/MachineLearning/KNNClassifier.py +++ b/SimpleCV/MachineLearning/KNNClassifier.py @@ -188,11 +188,11 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): featureVector.extend(feats) else: badFeat = True - + if(badFeat): badFeat = False continue - + featureVector.extend([className]) self.mDataSetRaw.append(featureVector) text = 'Training: ' + className @@ -423,7 +423,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): self._WriteText(disp,img,text, Color.RED) count = count + 1 del img - + return([dataset,count,correct]) def _WriteText(self, disp, img, txt,color): diff --git a/SimpleCV/MachineLearning/NaiveBayesClassifier.py b/SimpleCV/MachineLearning/NaiveBayesClassifier.py index 5d3e33a60..db63c9f52 100644 --- a/SimpleCV/MachineLearning/NaiveBayesClassifier.py +++ b/SimpleCV/MachineLearning/NaiveBayesClassifier.py @@ -155,11 +155,11 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): featureVector.extend(feats) else: badFeat = True - + if(badFeat): badFeat = False continue - + featureVector.extend([className]) self.mDataSetRaw.append(featureVector) text = 'Training: ' + className @@ -387,7 +387,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): self._WriteText(disp,img,text, Color.RED) count = count + 1 del img - + return([dataset,count,correct]) def _WriteText(self, disp, img, txt,color): diff --git a/SimpleCV/MachineLearning/SVMClassifier.py b/SimpleCV/MachineLearning/SVMClassifier.py index e14ec181e..f491485e7 100644 --- a/SimpleCV/MachineLearning/SVMClassifier.py +++ b/SimpleCV/MachineLearning/SVMClassifier.py @@ -216,11 +216,11 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): featureVector.extend(feats) else: badFeat = True - + if(badFeat): badFeat = False continue - + featureVector.extend([className]) self.mDataSetRaw.append(featureVector) text = 'Training: ' + className @@ -449,7 +449,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): self._WriteText(disp,img,text, Color.RED) count = count + 1 del img - + return([dataset,count,correct]) def _WriteText(self, disp, img, txt,color): diff --git a/SimpleCV/MachineLearning/TemporalColorTracker.py b/SimpleCV/MachineLearning/TemporalColorTracker.py index 67d4f28e5..660b6b3ea 100644 --- a/SimpleCV/MachineLearning/TemporalColorTracker.py +++ b/SimpleCV/MachineLearning/TemporalColorTracker.py @@ -13,7 +13,7 @@ class TemporalColorTracker: trained it will return a count object every time the signal is detected. This class is usefull for counting periodically occuring events, for example, waves on a beach or the second hand on a clock. - + """ def __init__(self): self._rtData = LineScan([]) # the deployed data @@ -72,7 +72,7 @@ def train(self,src,roi=None, extractor=None, doCorr=False, maxFrames=1000, By default this module will look at the signal with the highest peak/valley swings. You can manually overide this behavior. * *verbose* - Print debug info after training. - + **RETURNS** Nothing, will raise an exception if no signal is found. @@ -121,7 +121,7 @@ def train(self,src,roi=None, extractor=None, doCorr=False, maxFrames=1000, print("BEST SIGNAL: {0}".format(self._bestKey)) print("BEST WINDOW: {0}".format(self._window)) print("BEST CUTOFF: {0}".format(self._cutoff)) - + def _getDataFromImg(self,img): """ Get the data from the image @@ -158,11 +158,11 @@ def _extract(self,src,maxFrames,verbose): break else: self._getDataFromImg(img) - + else: raise Exception('Not a valid training source') return None - + def _findSteadyState(self,windowSzPrct=0.05): # slide a window across each of the signals # find where the std dev of the window is minimal @@ -221,7 +221,7 @@ def _extractSignalInfo(self,forceChannel): self.vD[key] = np.abs(self._steadyState[key][0]-valleyMean) else: self.vD[key] = 0.00 - + self.doPeaks[key]=False best = self.vD[key] if( self.pD[key] > self.vD[key] ): @@ -241,7 +241,7 @@ def _extractSignalInfo(self,forceChannel): else: self._bestKey = bestKey - + def _buildSignalProfile(self): key = self._bestKey self._window = None @@ -293,7 +293,7 @@ def _doCorr(self): self.corrTemplates.append(np.array(self.data[key][lb:ub])) if( len(self.corrTemplates) < 1 ): raise Exception('Could not find a coherrent signal for correlation.') - + sig = np.copy(self.corrTemplates[0]) # little np gotcha for peak in self.corrTemplates[1:]: sig += peak @@ -302,7 +302,7 @@ def _doCorr(self): corrVals = [np.correlate(peak/np.max(peak),self._template) for peak in self.corrTemplates] print(corrVals) self.corrThresh = (np.mean(corrVals),np.std(corrVals)) - + def _getBestValue(self,img): """ Extract the data from the live signal @@ -322,7 +322,7 @@ def _getBestValue(self,img): return Color.getLightness(mc) elif( self._bestKey == 'h' ): return Color.getHueFromRGB(mc) - + def _updateBuffer(self,v): """ Keep a buffer of the running data and process it to determine if there is @@ -356,7 +356,7 @@ def _updateBuffer(self,v): else: self.count += 1 return self.count - + def recognize(self,img): """ diff --git a/SimpleCV/MachineLearning/TestTemporalColorTracker.py b/SimpleCV/MachineLearning/TestTemporalColorTracker.py index 4e04a62be..82175e0b1 100644 --- a/SimpleCV/MachineLearning/TestTemporalColorTracker.py +++ b/SimpleCV/MachineLearning/TestTemporalColorTracker.py @@ -27,7 +27,7 @@ plt.savefig('temp.png') plt.clf() plotImg = Image('temp.png') - + roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) roi.draw(width=3) img.drawText(str(result),20,20,color=Color.RED,fontsize=32) diff --git a/SimpleCV/MachineLearning/TreeClassifier.py b/SimpleCV/MachineLearning/TreeClassifier.py index a4d2030b8..1da92fb7d 100644 --- a/SimpleCV/MachineLearning/TreeClassifier.py +++ b/SimpleCV/MachineLearning/TreeClassifier.py @@ -57,7 +57,7 @@ class TreeClassifier: mforestFlavorDict = { "NTrees":100, #number of trees in our forest "NAttributes":None # number of attributes per split sqrt(features) is default - } + } mBoostedFlavorDict = { "NClassifiers":10, #number of learners } @@ -225,11 +225,11 @@ def _trainImageSet(self,imageset,className,subset,disp,verbose): featureVector.extend(feats) else: badFeat = True - + if(badFeat): badFeat = False continue - + featureVector.extend([className]) self.mDataSetRaw.append(featureVector) text = 'Training: ' + className @@ -479,7 +479,7 @@ def _testImageSet(self,imageset,className,dataset,subset,disp,verbose): self._WriteText(disp,img,text, Color.RED) count = count + 1 del img - + return([dataset,count,correct]) def _WriteText(self, disp, img, txt,color): diff --git a/SimpleCV/MachineLearning/query_imgs/flickrapi2.py b/SimpleCV/MachineLearning/query_imgs/flickrapi2.py index 2d1eacb95..921ec2d3d 100644 --- a/SimpleCV/MachineLearning/query_imgs/flickrapi2.py +++ b/SimpleCV/MachineLearning/query_imgs/flickrapi2.py @@ -145,7 +145,7 @@ def __parseXMLElement(element, thisNode): elif a.nodeType == xml.dom.Node.TEXT_NODE: thisNode.elementText += a.nodeValue - + return thisNode dom = xml.dom.minidom.parseString(xmlStr) @@ -204,7 +204,7 @@ def __sign(self, data): #------------------------------------------------------------------- def __getattr__(self, method, **arg): """Handle all the flickr API calls. - + This is Michele Campeotto's cleverness, wherein he writes a general handler for methods not defined, and assumes they are flickr methods. He then converts them to a form to be passed as @@ -252,7 +252,7 @@ def __getAuthURL(self, perms, frob): This is the URL the app will launch a browser toward if it needs a new token. - + perms -- "read", "write", or "delete" frob -- picked up from an earlier call to FlickrAPI.auth_getFrob() @@ -410,7 +410,7 @@ def __getCachedToken(self): try: f = file(self.__getCachedTokenFilename(), "r") - + data = f.read() f.close() @@ -446,7 +446,7 @@ def getToken(self, perms="read", browser="lynx"): This first attempts to find a token in the user's token cache on disk. - + If that fails (or if the token is no longer valid based on flickr.auth.checkToken) a new frob is acquired. The frob is validated by having the user log into flickr (with lynx), and @@ -458,7 +458,7 @@ def getToken(self, perms="read", browser="lynx"): browser--whatever browser should be used in the system() call """ - + # see if we have a saved token token = self.__getCachedToken() @@ -532,4 +532,3 @@ def main(argv): # run the main if we're not being imported: if __name__ == "__main__": sys.exit(main(sys.argv)) - diff --git a/SimpleCV/Segmentation/MOGSegmentation.py b/SimpleCV/Segmentation/MOGSegmentation.py index 28cc75f9e..bfc93561f 100644 --- a/SimpleCV/Segmentation/MOGSegmentation.py +++ b/SimpleCV/Segmentation/MOGSegmentation.py @@ -7,7 +7,7 @@ class MOGSegmentation(SegmentationBase): Background subtraction using mixture of gausians. For each pixel store a set of gaussian distributions and try to fit new pixels into those distributions. One of the distributions will represent the background. - + history - length of the pixel history to be stored nMixtures - number of gaussian distributions to be stored per pixel backgroundRatio - chance of a pixel being included into the background model @@ -19,7 +19,7 @@ class MOGSegmentation(SegmentationBase): mDiffImg = None mColorImg = None mReady = False - + # OpenCV default parameters history = 200 nMixtures = 5 @@ -29,7 +29,7 @@ class MOGSegmentation(SegmentationBase): bsMOG = None def __init__(self, history = 200, nMixtures = 5, backgroundRatio = 0.7, noiseSigma = 15, learningRate = 0.7): - + try: import cv2 except ImportError: @@ -38,23 +38,23 @@ def __init__(self, history = 200, nMixtures = 5, backgroundRatio = 0.7, noiseSig if not hasattr(cv2, 'BackgroundSubtractorMOG'): raise ImportError("A newer version of OpenCV is needed") return - + self.mError = False self.mReady = False self.mDiffImg = None self.mColorImg = None self.mBlobMaker = BlobMaker() - + self.history = history self.nMixtures = nMixtures self.backgroundRatio = backgroundRatio self.noiseSigma = noiseSigma self.learningRate = learningRate - + self.mBSMOG = cv2.BackgroundSubtractorMOG(history, nMixtures, backgroundRatio, noiseSigma) - - - + + + def addImage(self, img): """ @@ -133,4 +133,3 @@ def __getstate__(self): def __setstate__(self, mydict): self.__dict__ = mydict self.mBlobMaker = BlobMaker() - diff --git a/SimpleCV/Tracking/CAMShiftTracker.py b/SimpleCV/Tracking/CAMShiftTracker.py index f1fba652f..0531c9a88 100644 --- a/SimpleCV/Tracking/CAMShiftTracker.py +++ b/SimpleCV/Tracking/CAMShiftTracker.py @@ -7,7 +7,7 @@ def camshiftTracker(img, bb, ts, **kwargs): """ **DESCRIPTION** - + (Dev Zone) Tracking the object surrounded by the bounding box in the given @@ -26,7 +26,7 @@ def camshiftTracker(img, bb, ts, **kwargs): lower - Lower HSV value for inRange thresholding tuple of (H, S, V) - + upper - Upper HSV value for inRange thresholding tuple of (H, S, V) diff --git a/SimpleCV/Tracking/LKTracker.py b/SimpleCV/Tracking/LKTracker.py index a4c204844..359757668 100644 --- a/SimpleCV/Tracking/LKTracker.py +++ b/SimpleCV/Tracking/LKTracker.py @@ -8,7 +8,7 @@ def lkTracker(img, bb, ts, oldimg, **kwargs): """ **DESCRIPTION** - + (Dev Zone) Tracking the object surrounded by the bounding box in the given @@ -30,7 +30,7 @@ def lkTracker(img, bb, ts, oldimg, **kwargs): maxCorners - Maximum number of corners to return in goodFeaturesToTrack. If there are more corners than are found, the strongest of them is returned. - + qualityLevel - Parameter characterizing the minimal accepted quality of image corners. The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue or the Harris function response. @@ -38,7 +38,7 @@ def lkTracker(img, bb, ts, oldimg, **kwargs): For example, if the best corner has the quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure less than 15 are rejected. - + minDistance - Minimum possible Euclidean distance between the returned corners. blockSize - Size of an average block for computing a derivative covariation matrix over each pixel neighborhood. diff --git a/SimpleCV/Tracking/MFTracker.py b/SimpleCV/Tracking/MFTracker.py index 8bfb1a7b4..f1195db85 100644 --- a/SimpleCV/Tracking/MFTracker.py +++ b/SimpleCV/Tracking/MFTracker.py @@ -8,7 +8,7 @@ def mfTracker(img, bb, ts, oldimg, **kwargs): """ **DESCRIPTION** - + (Dev Zone) Tracking the object surrounded by the bounding box in the given @@ -28,10 +28,10 @@ def mfTracker(img, bb, ts, oldimg, **kwargs): numM - Number of points to be tracked in the bounding box in height direction. - + numN - Number of points to be tracked in the bounding box in width direction. - + margin - Margin around the bounding box. winsize_lk - Optical Flow search window size. @@ -63,7 +63,7 @@ def mfTracker(img, bb, ts, oldimg, **kwargs): READ MORE: Median Flow Tracker: - + Media Flow Tracker is the base tracker that is used in OpenTLD. It is based on Optical Flow. It calculates optical flow of the points in the bounding box from frame 1 to frame 2 and from frame 2 to frame 1 and using back track error, removes @@ -101,9 +101,9 @@ def fbtrack(imgI, imgJ, bb, numM=10, numN=10,margin=5,winsize_ncc=10, winsize_lk **SUMMARY** (Dev Zone) Forward-Backward tracking using Lucas-Kanade Tracker - + **PARAMETERS** - + imgI - Image contain Object with known BoundingBox (Numpy array) imgJ - Following image (Numpy array) bb - Bounding box represented through 2 points (x1,y1,x2,y2) @@ -111,12 +111,12 @@ def fbtrack(imgI, imgJ, bb, numM=10, numN=10,margin=5,winsize_ncc=10, winsize_lk numN - Number of points in width direction. margin - margin (in pixel) winsize_ncc - Size of quadratic area around the point which is compared. - + **RETURNS** - + newbb - Bounding box of object in track in imgJ scaleshift - relative scale change of bb - + """ nPoints = numM*numN @@ -126,14 +126,14 @@ def fbtrack(imgI, imgJ, bb, numM=10, numN=10,margin=5,winsize_ncc=10, winsize_lk fb, ncc, status, ptTracked = lktrack(imgI, imgJ, pt, nPoints, winsize_ncc, winsize_lk) nlkPoints = sum(status)[0] - + startPoints = [] targetPoints = [] fbLKCleaned = [0.0]*nlkPoints nccLKCleaned = [0.0]*nlkPoints M = 2 nRealPoints = 0 - + for i in range(nPoints): if ptTracked[M*i] is not -1: startPoints.append((pt[2 * i],pt[2*i+1])) @@ -141,10 +141,10 @@ def fbtrack(imgI, imgJ, bb, numM=10, numN=10,margin=5,winsize_ncc=10, winsize_lk fbLKCleaned[nRealPoints]=fb[i] nccLKCleaned[nRealPoints]=ncc[i] nRealPoints+=1 - + medFb = getMedian(fbLKCleaned) medNcc = getMedian(nccLKCleaned) - + nAfterFbUsage = 0 for i in range(nlkPoints): if fbLKCleaned[i] <= medFb and nccLKCleaned[i] >= medNcc: @@ -161,9 +161,9 @@ def lktrack(img1, img2, ptsI, nPtsI, winsize_ncc=10, win_size_lk=4, method=cv2.c **SUMMARY** (Dev Zone) Lucas-Kanede Tracker with pyramids - + **PARAMETERS** - + img1 - Previous image or image containing the known bounding box (Numpy array) img2 - Current image ptsI - Points to track from the first image @@ -172,41 +172,41 @@ def lktrack(img1, img2, ptsI, nPtsI, winsize_ncc=10, win_size_lk=4, method=cv2.c winsize_ncc - size of the search window at each pyramid level in LK tracker (in int) method - Paramete specifying the comparison method for normalized cross correlation (see http://opencv.itseez.com/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#cv2.matchTemplate) - + **RETURNS** - + fb - forward-backward confidence value. (corresponds to euclidean distance between). ncc - normCrossCorrelation values status - Indicates positive tracks. 1 = PosTrack 0 = NegTrack ptsJ - Calculated Points of second image - + """ template_pt = [] target_pt = [] fb_pt = [] ptsJ = [-1]*len(ptsI) - + for i in range(nPtsI): template_pt.append((ptsI[2*i],ptsI[2*i+1])) target_pt.append((ptsI[2*i],ptsI[2*i+1])) fb_pt.append((ptsI[2*i],ptsI[2*i+1])) - + template_pt = np.asarray(template_pt,dtype="float32") target_pt = np.asarray(target_pt,dtype="float32") fb_pt = np.asarray(fb_pt,dtype="float32") - + target_pt, status, track_error = cv2.calcOpticalFlowPyrLK(img1, img2, template_pt, target_pt, winSize=(win_size_lk, win_size_lk), flags = cv2.OPTFLOW_USE_INITIAL_FLOW, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) - + fb_pt, status_bt, track_error_bt = cv2.calcOpticalFlowPyrLK(img2,img1, target_pt,fb_pt, winSize = (win_size_lk,win_size_lk),flags = cv2.OPTFLOW_USE_INITIAL_FLOW, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) - + status = status & status_bt ncc = normCrossCorrelation(img1, img2, template_pt, target_pt, status, winsize_ncc, method) fb = euclideanDistance(template_pt, target_pt) - + newfb = -1*np.ones(len(fb)) newncc = -1*np.ones(len(ncc)) for i in np.argwhere(status): @@ -237,48 +237,48 @@ def getMedian(a): def calculateBBCenter(bb): """ - + **SUMMARY** (Dev Zone) Calculates the center of the given bounding box - + **PARAMETERS** - + bb - Bounding Box represented through 2 points (x1,y1,x2,y2) - + **RETURNS** - + center - A tuple of two floating points - + """ center = (0.5*(bb[0] + bb[2]),0.5*(bb[1]+bb[3])) return center - + def getFilledBBPoints(bb, numM, numN, margin): """ - + **SUMMARY** (Dev Zone) Creates numM x numN points grid on Bounding Box - + **PARAMETERS** - + bb - Bounding Box represented through 2 points (x1,y1,x2,y2) numM - Number of points in height direction. numN - Number of points in width direction. margin - margin (in pixel) - + **RETURNS** - + pt - A list of points (pt[0] - x1, pt[1] - y1, pt[2] - x2, ..) - + """ pointDim = 2 bb_local = (bb[0] + margin, bb[1] + margin, bb[2] - margin, bb[3] - margin) if numM == 1 and numN == 1 : pts = calculateBBCenter(bb_local) return pts - + elif numM > 1 and numN == 1: divM = numM - 1 divN = 2 @@ -289,9 +289,9 @@ def getFilledBBPoints(bb, numM, numN, margin): for j in range(numM): pt[i * numM * pointDim + j * pointDim + 0] = center[0] pt[i * numM * pointDim + j * pointDim + 1] = bb_local[1] + j * spaceM - + return pt - + elif numM == 1 and numN > 1: divM = 2 divN = numN - 1 @@ -303,16 +303,16 @@ def getFilledBBPoints(bb, numM, numN, margin): pt[i * numM * pointDim + j * pointDim + 0] = bb_local[0] + i * spaceN pt[i * numM * pointDim + j * pointDim + 1] = center[1] return pt - + elif numM > 1 and numN > 1: divM = numM - 1 divN = numN - 1 - + spaceN = (bb_local[2] - bb_local[0]) / divN spaceM = (bb_local[3] - bb_local[1]) / divM pt = [0.0]*((numN-1)*numM*pointDim+numM*pointDim) - + for i in range(numN): for j in range(numM): pt[i * numM * pointDim + j * pointDim + 0] = float(bb_local[0] + i * spaceN) @@ -321,71 +321,71 @@ def getFilledBBPoints(bb, numM, numN, margin): def getBBWidth(bb): """ - + **SUMMARY** (Dev Zone) Get width of the bounding box - + **PARAMETERS** - + bb - Bounding Box represented through 2 points (x1,y1,x2,y2) - + **RETURNS** - + width of the bounding box - + """ return bb[2]-bb[0]+1 - + def getBBHeight(bb): """ - + **SUMMARY** (Dev Zone) Get height of the bounding box - + **PARAMETERS** - + bb - Bounding Box represented through 2 points (x1,y1,x2,y2) - + **RETURNS** - + height of the bounding box """ return bb[3]-bb[1]+1 - + def predictBB(bb0, pt0, pt1, nPts): """ - + **SUMMARY** (Dev Zone) Calculates the new (moved and resized) Bounding box. Calculation based on all relative distance changes of all points to every point. Then the Median of the relative Values is used. - + **PARAMETERS** - + bb0 - Bounding Box represented through 2 points (x1,y1,x2,y2) pt0 - Starting Points pt1 - Target Points nPts - Total number of points (eg. len(pt0)) - + **RETURNS** - + bb1 - new bounding box shift - relative scale change of bb0 - + """ ofx = [] ofy = [] for i in range(nPts): ofx.append(pt1[i][0]-pt0[i][0]) ofy.append(pt1[i][1]-pt0[i][1]) - + dx = getMedianUnmanaged(ofx) dy = getMedianUnmanaged(ofy) ofx=ofy=0 - + lenPdist = nPts * (nPts - 1) / 2 dist0=[] for i in range(nPts): @@ -396,7 +396,7 @@ def predictBB(bb0, pt0, pt1, nPts): dist0.append(float(temp1)/temp0) else: dist0.append(1.0) - + shift = getMedianUnmanaged(dist0) if shift is None: return(bb0, 1.0) @@ -406,8 +406,8 @@ def predictBB(bb0, pt0, pt1, nPts): shift = 1 s0 = 0.5 * (shift - 1) * getBBWidth(bb0) s1 = 0.5 * (shift - 1) * getBBHeight(bb0) - - + + x1 = bb0[0] - s0 + dx y1 = bb0[1] - s1 + dy x2 = bb0[2] + s0 + dx @@ -420,35 +420,35 @@ def predictBB(bb0, pt0, pt1, nPts): y1 = bb0[1] x2 = bb0[2] y2 = bb0[3] - + bb1 = (int(x1),int(y1),int(x2),int(y2)) - + return (bb1, shift) - + def getBB(pt0,pt1): xmax = np.max((pt0[0],pt1[0])) xmin = np.min((pt0[0],pt1[0])) ymax = np.max((pt0[1],pt1[1])) ymin = np.min((pt0[1],pt1[1])) return xmin,ymin,xmax,ymax - + def getRectFromBB(bb): return bb[0],bb[1],bb[2]-bb[0],bb[3]-bb[1] - + def euclideanDistance(point1,point2): """ (Dev Zone) **SUMMARY** - + Calculates eculidean distance between two points - + **PARAMETERS** - + point1 - vector of points point2 - vector of points with same length - + **RETURNS** - + match = returns a vector of eculidean distance """ match = ((point1[:,0]-point2[:,0])**2+(point1[:,1]-point2[:,1])**2)**0.5 @@ -459,9 +459,9 @@ def normCrossCorrelation(img1, img2, pt0, pt1, status, winsize, method=cv2.cv.CV **SUMMARY** (Dev Zone) Calculates normalized cross correlation for every point. - + **PARAMETERS** - + img1 - Image 1. img2 - Image 2. pt0 - vector of points of img1 @@ -472,12 +472,12 @@ def normCrossCorrelation(img1, img2, pt0, pt1, status, winsize, method=cv2.cv.CV winsize- Size of quadratic area around the point which is compared. method - Specifies the way how image regions are compared. see cv2.matchTemplate - + **RETURNS** - + match - Output: Array will contain ncc values. 0.0 if not calculated. - + """ nPts = len(pt0) match = np.zeros(nPts) diff --git a/SimpleCV/Tracking/SURFTracker.py b/SimpleCV/Tracking/SURFTracker.py index d8657c911..b24508bf8 100644 --- a/SimpleCV/Tracking/SURFTracker.py +++ b/SimpleCV/Tracking/SURFTracker.py @@ -8,7 +8,7 @@ def surfTracker(img, bb, ts, **kwargs): """ **DESCRIPTION** - + (Dev Zone) Tracking the object surrounded by the bounding box in the given @@ -28,11 +28,11 @@ def surfTracker(img, bb, ts, **kwargs): eps_val - eps for DBSCAN The maximum distance between two samples for them to be considered as in the same neighborhood. - + min_samples - min number of samples in DBSCAN The number of samples in a neighborhood for a point to be considered as a core point. - + distance - thresholding KNN distance of each feature if KNN distance > distance, point is discarded. @@ -129,7 +129,7 @@ def surfTracker(img, bb, ts, **kwargs): skp_final = [] skp_final_labelled=[] data_cluster=[] - + for i, dis in itertools.izip(idx, dist): if dis < distance: skp_final.append(skp[i]) @@ -139,7 +139,7 @@ def surfTracker(img, bb, ts, **kwargs): n_data = np.asarray(data_cluster) D = Dis.squareform(Dis.pdist(n_data)) S = 1 - (D/np.max(D)) - + db = DBSCAN(eps=eps_val, min_samples=min_samples).fit(S) core_samples = db.core_sample_indices_ labels = db.labels_ diff --git a/SimpleCV/Tracking/TrackSet.py b/SimpleCV/Tracking/TrackSet.py index 878a43d72..74c82ec87 100644 --- a/SimpleCV/Tracking/TrackSet.py +++ b/SimpleCV/Tracking/TrackSet.py @@ -28,7 +28,7 @@ class TrackSet(FeatureSet): import cv2 except ImportError: warnings.warn("OpenCV >= 2.3.1 required.") - + def __init__(self): self.kalman = None self.predict_pt = (0,0) diff --git a/SimpleCV/Tracking/__init__.py b/SimpleCV/Tracking/__init__.py index b47a0669e..a9dc8d963 100644 --- a/SimpleCV/Tracking/__init__.py +++ b/SimpleCV/Tracking/__init__.py @@ -3,4 +3,4 @@ from SimpleCV.Tracking.LKTracker import lkTracker from SimpleCV.Tracking.SURFTracker import surfTracker from SimpleCV.Tracking.MFTracker import mfTracker -from SimpleCV.Tracking.TrackSet import TrackSet \ No newline at end of file +from SimpleCV.Tracking.TrackSet import TrackSet diff --git a/SimpleCV/examples/detection/EdgeSnap.py b/SimpleCV/examples/detection/EdgeSnap.py index 06fc05d5d..6b84c8953 100644 --- a/SimpleCV/examples/detection/EdgeSnap.py +++ b/SimpleCV/examples/detection/EdgeSnap.py @@ -36,17 +36,11 @@ points += [left] if(right != None ): - + featureSet = edgeMap.edgeSnap(points) featureSet.image = image if(featureSet): featureSet.draw(width = 4,color = Color.RED) image.save(display) - - points = [] - - - - - + points = [] diff --git a/SimpleCV/examples/detection/MOGSegmentation.py b/SimpleCV/examples/detection/MOGSegmentation.py index 840182f28..507d6218f 100644 --- a/SimpleCV/examples/detection/MOGSegmentation.py +++ b/SimpleCV/examples/detection/MOGSegmentation.py @@ -3,19 +3,19 @@ from SimpleCV.Segmentation.MOGSegmentation import MOGSegmentation mog = MOGSegmentation(history = 200, nMixtures = 5, backgroundRatio = 0.3, noiseSigma = 16, learningRate = 0.3) - + cam = Camera() - + disp = Display() - + while (disp.isNotDone()): frame = cam.getImage() - + mog.addImage(frame) - + segmentedImage = mog.getSegmentedImage() blobs = mog.getSegmentedBlobs() for blob in blobs: segmentedImage.dl().circle((blob.x, blob.y), 10, Color.RED) - + segmentedImage.save(disp) diff --git a/SimpleCV/examples/display/qt-example.py b/SimpleCV/examples/display/qt-example.py index 2e624c5dc..633a6f9f1 100644 --- a/SimpleCV/examples/display/qt-example.py +++ b/SimpleCV/examples/display/qt-example.py @@ -71,5 +71,3 @@ def show_frame(self): webcam = Webcam() webcam.show() app.exec_() - - diff --git a/SimpleCV/examples/manipulation/ImageMotionBlur.py b/SimpleCV/examples/manipulation/ImageMotionBlur.py index 3fb52ea65..0c86f73ec 100644 --- a/SimpleCV/examples/manipulation/ImageMotionBlur.py +++ b/SimpleCV/examples/manipulation/ImageMotionBlur.py @@ -40,7 +40,7 @@ angle = 0 while not display.isDone(): time.sleep(0.01) - + #detect up,down,left,right keypresses and modify power,angle if( pygame.key.get_pressed()[pygame.K_UP] != 0 ): power +=10 @@ -59,5 +59,3 @@ blur = img.motionBlur(power,angle) blur.save(display) pass - - diff --git a/SimpleCV/tests/test_display.py b/SimpleCV/tests/test_display.py index d5deb3d53..f53aa7223 100644 --- a/SimpleCV/tests/test_display.py +++ b/SimpleCV/tests/test_display.py @@ -567,7 +567,7 @@ def test_image_perspective(): assert False def test_camera_undistort(): - + fakeCamera = FrameSource() fakeCamera.loadCalibration("TestCalibration") img = Image("../sampleimages/CalibImage0.png") diff --git a/SimpleCV/tests/test_vimba.py b/SimpleCV/tests/test_vimba.py index 098dfdd45..e7aac56be 100644 --- a/SimpleCV/tests/test_vimba.py +++ b/SimpleCV/tests/test_vimba.py @@ -64,7 +64,7 @@ def _runCommand(c): vimbacam = c._camera f = vimbacam.getFrame() # creates a frame f.announceFrame() - + vimbacam.startCapture() f.queueFrameCapture() c.runCommand("AcquisitionStart") @@ -96,4 +96,3 @@ def test_all(): _getImage(c) _runCommand(c) _listAllCameras(c) - diff --git a/SimpleCV/tests/tests.py b/SimpleCV/tests/tests.py index abd80c7ab..dc1c25c20 100644 --- a/SimpleCV/tests/tests.py +++ b/SimpleCV/tests/tests.py @@ -3514,9 +3514,9 @@ def test_findKeypointClusters(): img = Image('simplecv') kpc = img.findKeypointClusters() if len(kpc) <= 0: - assert False + assert False else: - pass + pass def test_replaceLineScan(): img = Image("lenna") diff --git a/SimpleCV/tests/vcamera_tests.py b/SimpleCV/tests/vcamera_tests.py index 31b8e7cfe..1d16277a6 100644 --- a/SimpleCV/tests/vcamera_tests.py +++ b/SimpleCV/tests/vcamera_tests.py @@ -29,7 +29,7 @@ def doFullVCamCoverageTest(vcam): if( img is None or count > maxf ): run = False return True - + def test_camera_constructor(): mycam = VirtualCamera(testimage, "image") @@ -37,7 +37,7 @@ def test_camera_constructor(): for i in props.keys(): print(str(i) + ": " + str(props[i]) + "\n") - + pass def test_camera_image(): diff --git a/SimpleCV/tools/Calibrate.py b/SimpleCV/tools/Calibrate.py index 5f4147f94..a39172f33 100644 --- a/SimpleCV/tools/Calibrate.py +++ b/SimpleCV/tools/Calibrate.py @@ -249,24 +249,24 @@ def findPlane(cb, i, calibration_set, dims): result = False grid = ( - #outline the top left corner - ((min_x, min_y), (right_x, bottom_y)), - #top middle - ((mid_min_x, min_y), (mid_max_x, bottom_y)), - #top right - ((left_x, min_y), (max_x, bottom_y)), - #right side middle - ((left_x, mid_min_y), (max_x, mid_max_y)), - # center - ((mid_min_x, mid_min_y), (mid_max_x, mid_max_y)), - #left middle - ((min_x, mid_min_y), (right_x, mid_max_y)), - #left bottom corner - ((min_x, top_y), (right_x, max_y)), - #bottom middle, - ((mid_min_x, top_y), (mid_max_x, max_y)), - #right bottom - ((left_x, top_y), (max_x, max_y)) ) + #outline the top left corner + ((min_x, min_y), (right_x, bottom_y)), + #top middle + ((mid_min_x, min_y), (mid_max_x, bottom_y)), + #top right + ((left_x, min_y), (max_x, bottom_y)), + #right side middle + ((left_x, mid_min_y), (max_x, mid_max_y)), + # center + ((mid_min_x, mid_min_y), (mid_max_x, mid_max_y)), + #left middle + ((min_x, mid_min_y), (right_x, mid_max_y)), + #left bottom corner + ((min_x, top_y), (right_x, max_y)), + #bottom middle, + ((mid_min_x, top_y), (mid_max_x, max_y)), + #right bottom + ((left_x, top_y), (max_x, max_y)) ) testrect(i, cb, calibration_set, dims, grid[lcs % len(grid)]) diff --git a/scripts/simplecv b/scripts/simplecv index 119285e0f..540241191 100755 --- a/scripts/simplecv +++ b/scripts/simplecv @@ -2,6 +2,6 @@ from SimpleCV import Shell import sys if len(sys.argv) > 1: - Shell.main(sys.argv) + Shell.main(sys.argv) else: - Shell.main() + Shell.main() From 2c86eb53922c24887aa309df0ba756f0c933ee58 Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Wed, 12 Aug 2015 21:23:44 -0700 Subject: [PATCH 3/3] Update imports for py3 compat. Python 3 requires OpenCV3.0 which has removed (!) support for cv2.cv. This does not address that aspect but should make later migration easier... --- SimpleCV/Display.py | 11 ++++++---- SimpleCV/ImageClass.py | 5 +++++ SimpleCV/Stream.py | 2 +- SimpleCV/base.py | 47 ++++++++++++++++++++++++++++-------------- 4 files changed, 45 insertions(+), 20 deletions(-) diff --git a/SimpleCV/Display.py b/SimpleCV/Display.py index 8689e01a5..9fa60898a 100644 --- a/SimpleCV/Display.py +++ b/SimpleCV/Display.py @@ -1,7 +1,10 @@ from __future__ import absolute_import from SimpleCV.base import * import SimpleCV.ImageClass -import Queue +try: + import queue # Note: This is unused. +except ImportError: + import Queue as queue from .base import * @@ -151,14 +154,14 @@ def __init__(self, resolution = (640, 480), flags = 0, title = "SimpleCV", displ self.rightButtonDown = None self.rightButtonUp = None self.pressed = None - self.displaytype = displaytype + self.displaytype = displaytype # NOTE: NO PYGAME CALLS SHOULD BE MADE IN INIT AS THEY KILLL - # THE DISPLAY IN IPYTHON NOTEBOOKS + # THE DISPLAY IN IPYTHON NOTEBOOKS self.mouseRawX = 0 # Raw x and y are the actual position on the screen self.mouseRawY = 0 # versus the position on the image. self.resolution = resolution if not displaytype == 'notebook': - self.screen = pg.display.set_mode(resolution, flags) + self.screen = pg.display.set_mode(resolution, flags) if os.path.isfile(os.path.join(LAUNCH_PATH, 'sampleimages','simplecv.png')): #checks if simplecv.png exists scvLogo = SimpleCV.Image("simplecv").scale(32,32) pg.display.set_icon(scvLogo.getPGSurface()) diff --git a/SimpleCV/ImageClass.py b/SimpleCV/ImageClass.py index 854a5793c..cd7416270 100644 --- a/SimpleCV/ImageClass.py +++ b/SimpleCV/ImageClass.py @@ -21,6 +21,11 @@ import copy # for deep copy #import scipy.stats.mode as spsmode +try: + basestring +except NameError: # python3 + basestring = (str, bytes) + class ColorSpace: """ **SUMMARY** diff --git a/SimpleCV/Stream.py b/SimpleCV/Stream.py index b5cec521f..c7a85f0c5 100644 --- a/SimpleCV/Stream.py +++ b/SimpleCV/Stream.py @@ -71,7 +71,7 @@ def do_GET(self): -class JpegTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): +class JpegTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True daemon_threads = True diff --git a/SimpleCV/base.py b/SimpleCV/base.py index bff98f11f..5d0044c95 100644 --- a/SimpleCV/base.py +++ b/SimpleCV/base.py @@ -9,9 +9,15 @@ import time import socket import re -import urllib2 +try: + from urllib.request import urlopen +except: + from urllib2 import urlopen import types -import SocketServer +try: + import socketserver +except: + import SocketServer as socketserver import threading import tempfile import zipfile @@ -43,9 +49,20 @@ from copy import copy from math import * from pkg_resources import load_entry_point -from SimpleHTTPServer import SimpleHTTPRequestHandler -from types import IntType, LongType, FloatType, InstanceType -from cStringIO import StringIO +try: + from http.server import SimpleHTTPRequestHandler +except ImportError: + from SimpleHTTPServer import SimpleHTTPRequestHandler +try: + from types import IntType, LongType, FloatType, InstanceType + REAL_TYPE = (IntType, LongType, FloatType) +except ImportError: + REAL_TYPE = (int, float) + InstanceType = object +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO from numpy import int32 from numpy import uint8 from .EXIF import * @@ -163,7 +180,7 @@ def is_number(n): Returns: Type """ - return type(n) in (IntType, LongType, FloatType) + return type(n) in REAL_TYPE def is_tuple(n): """ @@ -212,7 +229,7 @@ def download_and_extract(URL): tmpdir = tempfile.mkdtemp() filename = os.path.basename(URL) path = tmpdir + "/" + filename - zdata = urllib2.urlopen(URL) + zdata = urlopen(URL) print("Saving file to disk please wait....") with open(path, "wb") as local_file: @@ -371,25 +388,25 @@ def set_logging(log_level,myfilename = None): def system(): """ - + **SUMMARY** - + Output of this function includes various informations related to system and library. - + Main purpose: - While submiting a bug, report the output of this function - Checking the current version and later upgrading the library based on the output - + **RETURNS** - + None **EXAMPLE** - + >>> import SimpleCV >>> SimpleCV.system() - - + + """ try : import platform