Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Directly 2to3 #723

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
143 changes: 73 additions & 70 deletions SimpleCV/Camera.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion SimpleCV/Color.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,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

Expand Down
6 changes: 3 additions & 3 deletions SimpleCV/ColorModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def _makeCanonical(self, data):
#create a unique set of colors. I had to look this one up

#create a dict of encoded strings
return dict.fromkeys(map(np.ndarray.tostring, uniques), 1)
return dict.fromkeys(list(map(np.ndarray.tostring, uniques)), 1)

def reset(self):
"""
Expand Down Expand Up @@ -169,7 +169,7 @@ def threshold(self, img):
b = 0

rs = np.right_shift(img.getNumpy(), self.mBits).reshape(-1, 3) #bitshift down and reshape to Nx3
mapped = np.array(map(self.mData.has_key, map(np.ndarray.tostring, rs))) #map to True/False based on the model
mapped = np.array(list(map(self.mData.has_key, list(map(np.ndarray.tostring, rs))))) #map to True/False based on the model
thresh = np.where(mapped, a, b) #replace True and False with fg and bg
return Image(thresh.reshape(img.width, img.height))

Expand Down Expand Up @@ -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):
"""
Expand Down
4 changes: 2 additions & 2 deletions SimpleCV/Display.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from SimpleCV.base import *
import SimpleCV.ImageClass
import Queue
from base import *
import queue
from .base import *


PYGAME_INITIALIZED = False
Expand Down
3 changes: 2 additions & 1 deletion SimpleCV/DrawingLayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
50 changes: 25 additions & 25 deletions SimpleCV/EXIF.py
Original file line number Diff line number Diff line change
Expand Up @@ -1179,7 +1179,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
Expand Down Expand Up @@ -1260,7 +1260,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
Expand Down Expand Up @@ -1409,8 +1409,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
Expand Down Expand Up @@ -1510,21 +1510,21 @@ 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',
dict=MAKERNOTE_NIKON_NEWER_TAGS, relative=1)
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
Expand Down Expand Up @@ -1581,7 +1581,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')
Expand Down Expand Up @@ -1632,7 +1632,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
Expand All @@ -1645,27 +1645,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

Expand Down Expand Up @@ -1706,7 +1706,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)
Expand Down Expand Up @@ -1742,25 +1742,25 @@ 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()
x=list(data.keys())
x.sort()
for i in x:
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()
12 changes: 6 additions & 6 deletions SimpleCV/Features/BOFFeatureExtractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,19 @@ def generate(self,imgdirs,numcodes=128,sz=(11,11),imgs_per_dir=50,img_layout=(8,
for i in range(nimgs):
infile = files[i]
if verbose:
print(path+" "+str(i)+" of "+str(imgs_per_dir))
print "Opening file: " + infile
print((path+" "+str(i)+" of "+str(imgs_per_dir)))
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')
Expand Down
20 changes: 7 additions & 13 deletions SimpleCV/Features/Blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def __init__(self):
def __getstate__(self):
skip = self.pickle_skip_properties
newdict = {}
for k,v in self.__dict__.items():
for k,v in list(self.__dict__.items()):
if k in skip:
continue
else:
Expand Down Expand Up @@ -510,21 +510,15 @@ def rotate(self,angle):
self.mMask = self.mMask.rotate(angle,mode,point)
self.mHullMask = self.mHullMask.rotate(angle,mode,point)

self.mContour = map(lambda x:
(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)),
self.mContour)
self.mConvexHull = map(lambda x:
(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)),
self.mConvexHull)
self.mContour = [(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)) for x in self.mContour]
self.mConvexHull = [(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)) for x in self.mConvexHull]

if( self.mHoleContour is not None):
for h in self.mHoleContour:
h = map(lambda x:
(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)),
h)
h = [(x[0]*np.cos(theta)-x[1]*np.sin(theta),
x[0]*np.sin(theta)+x[1]*np.cos(theta)) for x in h]


def drawAppx(self, color = Color.HOTPINK,width=-1,alpha=-1,layer=None):
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/Features/BlobMaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
16 changes: 8 additions & 8 deletions SimpleCV/Features/Detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1016,7 +1016,7 @@ def __init__(self, i, at_x, at_y, r):
points = [(at_x-r,at_y-r),(at_x+r,at_y-r),(at_x+r,at_y+r),(at_x-r,at_y+r)]
super(Circle, self).__init__(i, at_x, at_y, points)
segments = 18
rng = range(1,segments+1)
rng = list(range(1,segments+1))
self.mContour = []
for theta in rng:
rp = 2.0*math.pi*float(theta)/float(segments)
Expand Down Expand Up @@ -1256,7 +1256,7 @@ def __init__(self, i, keypoint, descriptor=None, flavor="SURF" ):
super(KeyPoint, self).__init__(i, x, y, points)

segments = 18
rng = range(1,segments+1)
rng = list(range(1,segments+1))
self.points = []
for theta in rng:
rp = 2.0*math.pi*float(theta)/float(segments)
Expand Down Expand Up @@ -2278,7 +2278,7 @@ def CoordTransformPts(self,pts,intype="ROI",output="SRC"):

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)
return list(zip(x,y))


def _transform(self,x,imgsz,roisz,offset,intype,output):
Expand Down Expand Up @@ -2362,7 +2362,7 @@ def splitX(self,x,unitVals=False,srcVals=False):

x.insert(0,self.xtl)
x.append(self.xtl+self.w)
for i in xrange(0,len(x)-1):
for i in range(0,len(x)-1):
xstart = x[i]
xstop = x[i+1]
w = xstop-xstart
Expand Down Expand Up @@ -2416,7 +2416,7 @@ def splitY(self,y,unitVals=False,srcVals=False):

y.insert(0,self.ytl)
y.append(self.ytl+self.h)
for i in xrange(0,len(y)-1):
for i in range(0,len(y)-1):
ystart = y[i]
ystop = y[i+1]
h = ystop-ystart
Expand Down Expand Up @@ -2616,7 +2616,7 @@ def _standardize(self,x,y=None,w=None,h=None):
h = theFeature.height()

# [x,y,w,h] (x,y,w,h)
elif(isinstance(x, (tuple,list)) and len(x) == 4 and isinstance(x[0],(int, long, float))
elif(isinstance(x, (tuple,list)) and len(x) == 4 and isinstance(x[0],(int, float))
and y == None and w == None and h == None):
x,y,w,h = x
# x of the form [(x,y),(x1,y1),(x2,y2),(x3,y3)]
Expand Down Expand Up @@ -2644,7 +2644,7 @@ def _standardize(self,x,y=None,w=None,h=None):
elif(isinstance(x, (tuple,list)) and
isinstance(y, (tuple,list)) and
len(x) > 4 and len(y) > 4 ):
if(isinstance(x[0],(int, long, float)) and isinstance(y[0],(int, long, float))):
if(isinstance(x[0],(int, float)) and isinstance(y[0],(int, float))):
xmax = np.max(x)
ymax = np.max(y)
xmin = np.min(x)
Expand All @@ -2660,7 +2660,7 @@ def _standardize(self,x,y=None,w=None,h=None):
# x of the form [(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)]
elif(isinstance(x, (list,tuple)) and
len(x) > 4 and len(x[0]) == 2 and y == None and w == None and h == None):
if(isinstance(x[0][0],(int, long, float))):
if(isinstance(x[0][0],(int, float))):
xs = [pt[0] for pt in x]
ys = [pt[1] for pt in x]
xmax = np.max(xs)
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/Features/FaceRecognizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
4 changes: 1 addition & 3 deletions SimpleCV/Features/FeatureExtractorBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@
from SimpleCV.Color import Color
from SimpleCV.ImageClass import Image

class FeatureExtractorBase(object):
class FeatureExtractorBase(object, metaclass=abc.ABCMeta):
"""
The featureExtractorBase class is a way of abstracting the process of collecting
descriptive features within an image. A feature is some description of the image
like the mean color, or the width of a center image, or a histogram of edge
lengths. This feature vectors can then be composed together and used within
a machine learning algorithm to descriminate between different classes of objects.
"""

__metaclass__ = abc.ABCMeta
def load(cls, fname):
"""
load segmentation settings to file.
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/Features/FeatureUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def GetParallelSets(line_fs,parallel_thresh=2):
result = result.reshape(sz,sz)
# find the lines that are less than our thresh
l1,l2=np.where(result<parallel_thresh)
idxs = zip(l1,l2)
idxs = list(zip(l1,l2))
retVal = []
# now construct the line pairs
for idx in idxs:
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/Features/Features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down