Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 52 additions & 52 deletions SimpleCV/Camera.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# SimpleCV Cameras & Devices

#load system libraries
Expand Down Expand Up @@ -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:
Expand All @@ -381,7 +382,7 @@ def live(self):

i.save(d)
if d.mouseRight:
print "Closing Window"
print("Closing Window")
d.done = True


Expand Down Expand Up @@ -483,16 +484,16 @@ 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
if camera_index == -1:
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))
Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -1335,7 +1336,7 @@ def printProperties(self):
"""
for prop in self.device.optlist:
try:
print self.device[prop]
print(self.device[prop])
except:
pass

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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]))
Expand All @@ -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

Expand Down Expand Up @@ -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 :
Expand Down Expand Up @@ -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 :
Expand Down Expand Up @@ -2469,15 +2470,15 @@ 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 = []
roi.append(max(leftroi[0], rightroi[0]))
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)):
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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)


Expand All @@ -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)
Expand Down Expand Up @@ -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):
Expand All @@ -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


Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -3819,7 +3820,6 @@ 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)

3 changes: 2 additions & 1 deletion 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
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
8 changes: 6 additions & 2 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
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
Loading