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

Towards python 3 support #677

Open
wants to merge 3 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
484 changes: 242 additions & 242 deletions SimpleCV/Camera.py

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions SimpleCV/Color.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# SimpleCV Color Library
#
# This library is used to modify different color properties of images
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -305,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

"""
Expand All @@ -331,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

"""
Expand All @@ -346,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)
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/ColorModel.py
Original file line number Diff line number Diff line change
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
10 changes: 5 additions & 5 deletions SimpleCV/DFT.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down Expand Up @@ -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()
"""
Expand Down Expand Up @@ -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()
"""
Expand Down Expand Up @@ -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()
"""
Expand Down
18 changes: 11 additions & 7 deletions SimpleCV/Display.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import absolute_import
from SimpleCV.base import *
import SimpleCV.ImageClass
import Queue
from base import *
try:
import queue # Note: This is unused.
except ImportError:
import Queue as queue
from .base import *


PYGAME_INITIALIZED = False
Expand Down Expand Up @@ -150,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())
Expand Down Expand Up @@ -577,7 +581,7 @@ def _setButtonState(self, state, button):

def checkEvents(self,returnStrings=False):
"""

**SUMMARY**

CheckEvents checks the pygame event queue and sets the internal display
Expand All @@ -590,7 +594,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_<lowercase_letter>
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
49 changes: 25 additions & 24 deletions SimpleCV/EXIF.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1510,21 +1511,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 +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')
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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()
11 changes: 6 additions & 5 deletions SimpleCV/Features/BOFFeatureExtractor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from SimpleCV.base import *
from SimpleCV.ImageClass import Image
from SimpleCV.Features.FeatureExtractorBase import *
Expand Down Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion SimpleCV/Features/Blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
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