Features Package

Features Package

BOFFeatureExtractor Module

class SimpleCV.Features.BOFFeatureExtractor.BOFFeatureExtractor(patchsz=(11, 11), numcodes=128, imglayout=(8, 16), padding=0)

Bases: object

For a discussion of bag of features please see: http://en.wikipedia.org/wiki/Bag_of_words_model_in_computer_vision

Initialize the bag of features extractor. This assumes you don’t have the feature codebook pre-computed. patchsz = the dimensions of each codebook patch numcodes = the number of different patches in the codebook. imglayout = the shape of the resulting image in terms of patches padding = the pixel padding of each patch in the resulting image.

extract(img)

This method extracts a bag of features histogram for the input image using the provided codebook. The result are the bin counts for each codebook code.

extractPatches(img, sz=(11, 11))

Get patches from a single images. This is an external access method. The user will need to maintain the list of features. See the generate method as a guide to doing this by hand. Sz is the image patch size.

generate(imgdirs, numcodes=128, sz=(11, 11), imgs_per_dir=50, img_layout=(8, 16), padding=0, verbose=True)

This method builds the bag of features codebook from a list of directories with images in them. Each directory should be broken down by image class.

  • imgdirs: This list of directories.
  • patchsz: the dimensions of each codebook patch
  • numcodes: the number of different patches in the codebook.
  • imglayout: the shape of the resulting image in terms of patches
  • padding:the pixel padding of each patch in the resulting image.
  • imgs_per_dir: this method can use a specified number of images per directory
  • verbose: print output

Once the method has completed it will save the results to a local file using the file name codebook.png

WARNING:

THIS METHOD WILL TAKE FOREVER
getFieldNames()

This method gives the names of each field in the feature vector in the order in which they are returned. For example, ‘xpos’ or ‘width’

getNumFields()

This method returns the total number of fields in the feature vector.

load(datafile)

Load a codebook from file using the datafile. The datafile should point to a local image for the source patch image.

mCodebook = None
mCodebookImg = None
mLayout = (8, 16)
mNumCodes = 128
mPadding = 0
mPatchSize = (11, 11)
makeCodebook(featureStack, ncodes=128)

This method will return the centroids of the k-means analysis of a large number of images. Ncodes is the number of centroids to find.

reconstruct(img)

This is a “just for fun” method as a sanity check for the BOF codeook. The method takes in an image, extracts each codebook code, and replaces the image at the position with the code.

save(imgfname, datafname)

Save the bag of features codebook and data set to a local file.

Blob Module

class SimpleCV.Features.Blob.Blob

Bases: SimpleCV.Features.Features.Feature

SUMMARY

A blob is a typicall a cluster of pixels that form a feature or unique shape that allows it to be distinguished from the rest of the image Blobs typically are computed very quickly so they are used often to find various items in a picture based on properties. Typically these things like color, shape, size, etc. Since blobs are computed quickly they are typically used to narrow down search regions in an image, where you quickly find a blob and then that blobs region is used for more computational intensive type image processing.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].draw()
>>> img.show()

SEE ALSO findBlobs() BlobMaker findBlobsFromMask()

angle()

SUMMARY

This method returns the angle between the horizontal and the minimum enclosing rectangle of the blob. The minimum enclosing rectangle IS NOT not the bounding box. Use the bounding box for situations where you need only an approximation of the objects dimensions. The minimum enclosing rectangle is slightly harder to maninpulate but gives much better information about the blobs dimensions.

RETURNS

Returns the angle between the minimum bounding rectangle and the horizontal.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blob[-1].angle()
area()

SUMMARY

This method returns the area of the blob in terms of the number of pixels inside the contour.

RETURNS

An integer of the area of the blob in pixels.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].area()
>>> print blobs[0].area()
blobImage()

SUMMARY

This method automatically copies all of the image data around the blob and puts it in a new image. The resulting image has the size of the blob, with the blob data copied in place. Where the blob is not present the background is black.

RETURNS

Returns just the image of the blob (cropped to fit).

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].blobImage().show()
blobMask()

SUMMARY

This method returns an image of the blob’s mask. Areas where the blob are present are white while all other areas are black. The image is cropped to match the blob area.

RETURNS

Returns a SimplecV image of the blob’s mask, cropped to fit.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].blobMask().show()
centroid()

SUMMARY

Return the centroid (mass-determined center) of the blob. Note that this is differnt from the bounding box center.

RETURNS

An (x,y) tuple that is the center of mass of the blob.

EXAMPLE >>> img = Image(“lenna”) >>> blobs = img.findBlobs() >>> img.drawCircle((blobs[-1].x,blobs[-1].y),10,color=Color.RED) >>> img.drawCircle((blobs[-1].centroid()),10,color=Color.BLUE) >>> img.show()

circleDistance()

SUMMARY

Compare the hull mask to an ideal circle and count the number of pixels that deviate as a fraction of total area of the ideal circle.

RETURNS

The difference, as a percentage, between the hull of our blob and an idealized circle of our blob.

contour()

SUMMARY

This function returns the contour points as a list of x,y tuples.

RETURNS

A list of x,y tuples.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].contour()
draw(color=(0, 128, 0), width=-1, alpha=-1, layer=None)

SUMMARY

Draw the blob, in the given color, to the appropriate layer

By default, this draws the entire blob filled in, with holes. If you provide a width, an outline of the exterior and interior contours is drawn.

PARAMETERS

  • color -The color to render the blob as a color tuple.
  • alpha - The alpha value of the rendered blob 0=transparent 255=opaque.
  • width - The width of the drawn blob in pixels, if -1 then filled then the polygon is filled.
  • layer - A source layer, if layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

This method either works on the original source image, or on the drawing layer provided. The method does not modify object itself.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-2].draw(color=Color.PUCE,width=-1,alpha=128)
>>> img.show()
drawHoles(color=(0, 128, 0), alpha=-1, width=-1, layer=None)

SUMMARY

This method renders all of the holes (if any) that are present in the blob.

PARAMETERS

  • color - The color to render the blob’s holes.
  • alpha - The alpha value of the rendered blob hole.
  • width - The width of the drawn blob hole in pixels, if w=-1 then the polygon is filled.
  • layer - If layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

This method either works on the original source image, or on the drawing layer provided. The method does not modify object itself.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs(128)
>>> blobs[-1].drawHoles(color=Color.GREEN,width=3,alpha=128)
>>> img.show()
drawHull(color=(0, 128, 0), alpha=-1, width=-1, layer=None)

SUMMARY

Draw the blob’s convex hull to either the source image or to the specified layer given by layer.

PARAMETERS

  • color - The color to render the blob’s convex hull as an RGB triplet.
  • alpha - The alpha value of the rendered blob.
  • width - The width of the drawn blob in pixels, if w=-1 then the polygon is filled.
  • layer - if layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

This method either works on the original source image, or on the drawing layer provided. The method does not modify object itself.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs(128)
>>> blobs[-1].drawHoles(color=Color.GREEN,width=3,alpha=128)
>>> img.show()
drawMaskToLayer(layer=None, offset=(0, 0))

SUMMARY

Draw the actual pixels of the blob to another layer. This is handy if you want to examine just the pixels inside the contour.

PARAMETERS

  • layer - A drawing layer upon which to apply the mask.
  • offset - The offset from the top left corner where we want to place the mask.

RETURNS

This method either works on the original source image, or on the drawing layer provided. The method does not modify object itself.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs(128)
>>> dl = DrawingLayer((img.width,img.height))
>>> blobs[-1].drawMaskToLayer(layer = dl)
>>> dl.show()
drawMinRect(layer=None, color=(0, 0, 0), width=1, alpha=128)

SUMMARY

Draws the minimum bounding rectangle for the blob. The minimum bounding rectangle is the smallest rotated rectangle that can enclose the blob.

PARAMETERS

  • color - The color to render the blob’s box.
  • alpha - The alpha value of the rendered blob 0 = transparent 255 = opaque.
  • width - The width of the drawn blob in pixels
  • layer - If layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

Returns none, this operation works on the supplied layer or the source image.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> for b in blobs:
>>>      b.drawMinRect(color=Color.RED, width=-1,alpha=128)
>>> img.show()
drawOutline(color=(0, 128, 0), alpha=128, width=1, layer=None)

SUMMARY

Draw the blob contour the provided layer – if no layer is provided, draw to the source image.

PARAMETERS

  • color - The color to render the blob.
  • alpha - The alpha value of the rendered blob.
  • width - The width of the drawn blob in pixels, -1 then the polygon is filled.
  • layer - if layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

This method either works on the original source image, or on the drawing layer provided. The method does not modify object itself.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-2].drawOutline(color=Color.GREEN,width=3,alpha=128)
>>> img.show()
drawRect(layer=None, color=(0, 0, 0), width=1, alpha=128)

SUMMARY

Draws the bounding rectangle for the blob.

PARAMETERS

  • color - The color to render the blob’s box.
  • alpha - The alpha value of the rendered blob 0 = transparent 255 = opaque.
  • width - The width of the drawn blob in pixels
  • layer - if layer is not None, the blob is rendered to the layer versus the source image.

RETURNS

Returns None, this operation works on the supplied layer or the source image.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].drawRect(color=Color.RED, width=-1,alpha=128)
>>> img.show()
hull()

SUMMARY

This function returns the convex hull points as a list of x,y tuples.

RETURNS

A list of x,y tuples.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].hull()
hullImage()

SUMMARY

The convex hull of a blob is the shape that would result if you snapped a rubber band around the blob. So if you had the letter “C” as your blob the convex hull would be the letter “O.” This method returns an image where the source image around the convex hull of the blob is copied ontop a black background.

RETURNS Returns a SimpleCV Image of the convex hull, cropped to fit.

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].hullImage().show()
hullMask()

SUMMARY

The convex hull of a blob is the shape that would result if you snapped a rubber band around the blob. So if you had the letter “C” as your blob the convex hull would be the letter “O.” This method returns an image where the area of the convex hull is white and the rest of the image is black. This image is cropped to the size of the blob.

RETURNS

Returns a binary SimpleCV image of the convex hull mask, cropped to fit the blob.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-1].hullMask().show()
hullRadius()

SUMMARY

Return the radius of the convex hull contour from the centroid

isCircle(tolerance=0.05)

SUMMARY

Test circle distance against a tolerance to see if the blob is circlular.

PARAMETERS

  • tolerance - the percentage difference between our blob and an ideal circle.

RETURNS

True if the feature is within tolerance for being a circle, false otherwise.

isRectangle(tolerance=0.05)

SUMMARY

Given a tolerance, test the blob against the rectangle distance to see if it is rectangular.

PARAMETERS

  • tolerance - The percentage difference between our blob and its idealized bounding box.

RETURNS

Boolean True if the blob is withing the rectangle tolerage, false otherwise.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs(128)
>>> if(blobs[-1].isRecangle() ):
>>>     print "it is hip to be square." 
isSquare(tolerance=0.05, ratiotolerance=0.05)

SUMMARY

Given a tolerance, test if the blob is a rectangle, and how close its bounding rectangle’s aspect ratio is to 1.0.

PARAMETERS

  • tolerance - A percentage difference between an ideal rectangle and our hull mask.
  • ratiotolerance - A percentage difference of the aspect ratio of our blob and an ideal square.

RETURNS

Boolean True if our object falls within tolerance, false otherwise.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs(128)
>>> if(blobs[-1].isSquare() ):
>>>     print "it is hip to be square." 
m00 = 0
m01 = 0
m02 = 0
m10 = 0
m11 = 0
m12 = 0
m20 = 0
m21 = 0
mArea = 0
mAvgColor = []
mContour = []
mConvexHull = []
mHoleContour = []
mHu = []
mHullImg = ''
mHullMask = ''
mImg = ''
mLabel = ''
mLabelColor = []
mMask = ''
mMinRectangle = []
mPerimeter = 0
match(otherblob)

SUMMARY

Compare the Hu moments between two blobs to see if they match. Returns a comparison factor – lower numbers are a closer match.

PARAMETERS

  • otherblob - The other blob to compare this one to.

RETURNS

A single floating point value that is the match quality.

EXAMPLE

>>> cam = Camera()
>>> img1 = cam.getImage()
>>> img2 = cam.getImage()
>>> b1 = img1.findBlobs()
>>> b2 = img2.findBlobs()
>>> for ba in b1:
>>>     for bb in b2:
>>>         print ba.match(bb)
meanColor()

SUMMARY

This function returns a tuple representing the average color of the blob.

RETURNS

A RGB triplet of the average blob colors.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].meanColor()
minRect()

Returns the corners for the smallest rotated rectangle to enclose the blob. The points are returned as a list of (x,y) tupples.

minRectHeight()

SUMMARY

This is the height, in pixels, of the minimum bounding rectangle.

RETURNS

An integer that is the height of the minimum bounding rectangle for this blob.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].minRectHeight()
minRectWidth()

SUMMARY

This is the width of the minimum bounding rectangle for the blob.

RETURNS

An integer that is the width of the minimum bounding rectangle for this blob.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].minRectWidth()
minRectX()

SUMMARY

This is the x coordinate of the centroid for the minimum bounding rectangle

RETURNS

An integer that is the x position of the centrod of the minimum bounding rectangle.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].minRectX()
minRectY()

SUMMARY

This is the y coordinate of the centroid for the minimum bounding rectangle

RETURNS

An integer that is the y position of the centrod of the minimum bounding rectangle.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].minRectY()
perimeter()

SUMMARY

This function returns the perimeter as an integer number of pixel lengths.

RETURNS

Integer

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> print blobs[-1].perimeter()
radius()

SUMMARY

Return the radius, the avg distance of each contour point from the centroid

rectangleDistance()

SUMMARY

This compares the hull mask to the bounding rectangle. Returns the area of the blob’s hull as a fraction of the bounding rectangle.

RETURNS

The number of pixels in the blobs hull mask over the number of pixels in its bounding box.

rectifyMajorAxis(axis=0)

SUMMARY

Rectify the blob image and the contour such that the major axis is aligned to either horizontal=0 or vertical=1. This is to say, we take the blob, find the longest axis, and rotate the blob such that the axis is either vertical or horizontal.

PARAMETERS

  • axis - if axis is zero we rotate the blobs to fit along the vertical axis, otherwise we use the horizontal axis.

RETURNS

This method works in place, i.e. it rotates the blob’s internal data structures. This method is experimetnal. Use at your own risk.

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-2].mImg.show()
>>> blobs[-2].rectifyToMajorAxis(1)
>>> blobs[-2].mImg.show()
rotate(angle)

SUMMARY

Rotate the blob given an angle in degrees. If you use this method most of the blob elements will be rotated in place , however, this will “break” drawing back to the original image. To draw the blob create a new layer and draw to that layer. Positive rotations are counter clockwise.

PARAMETERS

  • angle - A floating point angle in degrees. Positive is anti-clockwise.

RETURNS

EXAMPLE

>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> blobs[-2].mImg.show()
>>> blobs[-2].rotate(90)
>>> blobs[-2].mImg.show()
seq = ''

BlobMaker Module

class SimpleCV.Features.BlobMaker.BlobMaker

Blob maker encapsulates all of the contour extraction process and data, so it can be used inside the image class, or extended and used outside the image class. The general idea is that the blob maker provides the utilites that one would use for blob extraction. Later implementations may include tracking and other features.

extract(img, threshval=127, minsize=10, maxsize=0, threshblocksize=3, threshconstant=5)

This method performs a threshold operation on the input image and then extracts and returns the blobs. img - The input image (color or b&w) threshval - The threshold value for the binarize operation. If threshval = -1 adaptive thresholding is used minsize - The minimum blob size in pixels. maxsize - The maximum blob size in pixels. 0=uses the default value. threshblocksize - The adaptive threhold block size. threshconstant - The minimum to subtract off the adaptive threshold

extractFromBinary(binaryImg, colorImg, minsize=5, maxsize=-1)

This method performs blob extraction given a binary source image that is used to get the blob images, and a color source image. binaryImg- The binary image with the blobs. colorImg - The color image. minSize - The minimum size of the blobs in pixels. maxSize - The maximum blob size in pixels.

extractUsingModel(img, colormodel, minsize=10, maxsize=0)

Extract blobs using a color model img - The input image colormodel - The color model to use. minsize - The minimum size of the returned features. maxsize - The maximum size of the returned features 0=uses the default value.

Parameters:
img - Image colormodel - ColorModel object minsize - Int maxsize - Int
mMemStorage = None

Detection Module

class SimpleCV.Features.Detection.Barcode(i, zxbc)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The Barcode Feature wrappers the object returned by findBarcode(), a python-zxing object.

  • The x,y coordinate is the center of the code.
  • points represents the four boundary points of the feature. Note: for QR codes, these points are the reference rectangls, and are quadrangular, rather than rectangular with other datamatrix types.
  • data is the parsed data of the code.

SEE ALSO

ImageClass.findBarcodes()

area()

SUMMARY

Returns the area defined by the quandrangle formed by the boundary points

RETURNS

An integer area value.

EXAMPLE

>>> img = Image("mycode.jpg")
>>> bc = img.findBarcode()
>>> print bc[-1].area()
data = ''
draw(color=(255, 0, 0), width=1)

SUMMARY

Draws the bounding area of the barcode, given by points. Note that for QR codes, these points are the reference boxes, and so may “stray” into the actual code.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

length()

SUMMARY

Returns the longest side of the quandrangle formed by the boundary points.

RETURNS

A floating point length value.

EXAMPLE

>>> img = Image("mycode.jpg")
>>> bc = img.findBarcode()
>>> print bc[-1].length()
class SimpleCV.Features.Detection.Chessboard(i, dim, subpixelCorners)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

This class is used for Calibration, it uses a chessboard to calibrate from pixels to real world measurements.

area()

SUMMARY

Returns the mean of the distance between corner points in the chessboard Given that the chessboard is of a known size, this can be used as a proxy for distance from the camera

RETURNS

Returns the mean distance between the corners.

EXAMPLE

>>> img = Image("corners.jpg")
>>> feats = img.findChessboardCorners()
>>> print feats[-1].area()
dimensions = ()
draw(no_needed_color=None)

SUMMARY

Draws the chessboard corners. We take a color param, but ignore it.

PARAMETERS

  • no_needed_color - An RGB color triplet that isn’t used

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

spCorners = []
class SimpleCV.Features.Detection.Circle(i, at_x, at_y, r)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

Class for a general circle feature with a center at (x,y) and a radius r

area()

Area covered by the feature – for a pixel, 1

SUMMARY

Returns a numpy array of the area of each feature in pixels.

RETURNS

A numpy array of all the positions in the featureset.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.coordinates()
>>> print xs
avgColor = None
crop(noMask=False)

SUMMARY

This function returns the largest bounding box for an image.

PARAMETERS

  • noMask - if noMask=True we return the bounding box image of the circle. if noMask=False (default) we return the masked circle with the rest of the area set to black

RETURNS

The masked circle image.

diameter()

SUMMARY

Returns the diameter of the circle in pixels.

distanceFrom(point=(-1, -1))

SUMMARY

Given a point (default to center of the image), return the euclidean distance of x,y from this point.

PARAMETERS

  • point - The point, as an (x,y) tuple on the image to measure distance from.

RETURNS

The distance as a floating point value in pixels.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findCircle()
>>> blobs[-1].distanceFrom(blobs[-2].coordinates())
draw(color=(0, 128, 0), width=1)

SUMMARY

With no dimension information, color the x,y point for the feature.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

height()

SUMMARY

Returns the height of the feature – for compliance just r*2

image = ''
meanColor()

SUMMARY

Returns the average color within the circle.

RETURNS

Returns an RGB triplet that corresponds to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> c = img.findCircle()
>>> c[-1].meanColor()
perimeter()

SUMMARY

Returns the perimeter of the circle feature in pixels.

points = []
radius()

SUMMARY

Returns the radius of the circle in pixels.

show(color=(0, 128, 0))

SUMMARY

This function will automatically draw the features on the image and show it. It is a basically a shortcut function for development and is the same as:

PARAMETERS

  • color - the color of the feature as an rgb triplet.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

EXAMPLE

>>> img = Image("logo")
>>> feat = img.findCircle()
>>> feat[0].show()
width()

SUMMARY

Returns the width of the feature – for compliance just r*2

x = 0.0
y = 0.0
class SimpleCV.Features.Detection.Corner(i, at_x, at_y)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The Corner feature is a point returned by the FindCorners function Corners are used in machine vision as a very computationally efficient way to find unique features in an image. These corners can be used in conjunction with many other algorithms.

SEE ALSO

findCorners()

draw(color=(255, 0, 0), width=1)

SUMMARY

Draw a small circle around the corner. Color tuple is single parameter, default is Red.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

class SimpleCV.Features.Detection.HaarFeature(i, haarobject, haarclassifier=None)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The HaarFeature is a rectangle returned by the FindHaarFeature() function.

  • The x,y coordinates are defined by the center of the bounding rectangle.
  • The classifier property refers to the cascade file used for detection .
  • Points are the clockwise points of the bounding rectangle, starting in upper left.
area()

SUMMARY

Returns the area of the feature in pixels.

RETURNS

The area of the feature in pixels.

EXAMPLE

>>> img = Image("lenna")
>>> face = HaarCascade("face.xml")
>>> faces = img.findHaarFeatures(face)
>>> print faces[-1].area()
classifier = ''
draw(color=(0, 255, 0), width=1)

SUMMARY

Draw the bounding rectangle, default color green.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

featureName = 'None'
meanColor()

SUMMARY

Find the mean color of the boundary rectangle.

RETURNS

Returns an RGB triplet that corresponds to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> face = HaarCascade("face.xml")
>>> faces = img.findHaarFeatures(face)
>>> print faces[-1].meanColor()
neighbors = ''
class SimpleCV.Features.Detection.KeyPoint(i, keypoint, descriptor=None, flavor='SURF')

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The class is place holder for SURF/SIFT/ORB/STAR keypoints.

angle()

SUMMARY

Return the angle (theta) in degrees of the feature. The default is 0 (horizontal).

RETURNS

An angle value in degrees.

colorDistance(color=(0, 0, 0))

Return the euclidean color distance of the color tuple at x,y from a given color (default black)

crop(noMask=False)

SUMMARY

This function returns the largest bounding box for an image.

PARAMETERS

  • noMask - if noMask=True we return the bounding box image of the circle. if noMask=False (default) we return the masked circle with the rest of the area set to black

RETURNS

The masked circle image.

descriptor()

SUMMARY

Returns the raw keypoint descriptor.

diameter()

SUMMARY

Returns the diameter of the circle in pixels.

distanceFrom(point=(-1, -1))

SUMMARY

Given a point (default to center of the image), return the euclidean distance of x,y from this point

draw(color=(0, 128, 0), width=1)

SUMMARY

Draw a circle around the feature. Color tuple is single parameter, default is Green.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

flavor()

SUMMARY

Returns the type of keypoint as a string (e.g. SURF/MSER/ETC)

getObject()

SUMMARY

Returns the raw keypoint object.

height()

SUMMARY

Returns the height of the feature – for compliance just r*2

image = ''
mAngle = 0
mDescriptor = None
mFlavor = ''
mKeyPoint = None
mOctave = 0
mResponse = 0.0
meanColor()

SUMMARY

Return the average color within the feature’s radius

RETURNS

Returns an RGB triplet that corresponds to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> kp = img.findKeypoints()
>>> c = kp[0].meanColor()
octave()

SUMMARY

Returns the raw keypoint’s octave (if it has one).

perimeter()

SUMMARY

Returns the perimeter of the circle feature in pixels.

points = []
quality()

SUMMARY

Returns the quality metric for the keypoint object.

r = 0.0
radius()

SUMMARY

Returns the radius of the circle in pixels.

show(color=(0, 128, 0))

SUMMARY

This function will automatically draw the features on the image and show it. It is a basically a shortcut function for development and is the same as:

>>> img = Image("logo")
>>> feat = img.findBlobs()
>>> if feat: feat.draw()
>>> img.show()
width()

SUMMARY

Returns the width of the feature – for compliance just r*2

x = 0.0
y = 0.0
class SimpleCV.Features.Detection.KeypointMatch(image, template, minRect, _homography)

Bases: SimpleCV.Features.Features.Feature

This class encapsulates a keypoint match between images of an object. It is used to record a template of one image as it appears in another image

crop()

Returns a cropped image of the feature match. This cropped version is the axes aligned box masked to just include the image data of the minimum bounding rectangle.

draw(color=(0, 128, 0), width=1)

The default drawing operation is to draw the min bounding rectangle in an image.

SUMMARY

Draw a small circle around the corner. Color tuple is single parameter, default is Red.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

drawRect(color=(0, 128, 0), width=1)

This method draws the axes alligned square box of the template match. This box holds the minimum bounding rectangle that describes the object. If the minimum bounding rectangle is axes aligned then the two bounding rectangles will match.

getHomography()

Returns the _homography matrix used to calulate the minimum bounding rectangle.

getMinRect()

Returns the minimum bounding rectangle of the feature as a list of (x,y) tuples.

image = ''
meanColor()

return the average color within the circle SUMMARY

Return a numpy array of the average color of the area covered by each Feature.

RETURNS

Returns an array of RGB triplets the correspond to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> kp = img.findKeypoints()
>>> c = kp.meanColor()
points = []
x = 0.0
y = 0.0
class SimpleCV.Features.Detection.Line(i, line)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The Line class is returned by the findLines function, but can also be initialized with any two points.

>>> l = Line(Image, point1, point2) 

Where point1 and point2 are (x,y) coordinate tuples.

>>> l.points 

Returns a tuple of the two points

angle()

SUMMARY

This is the angle of the line, from the leftmost point to the rightmost point Returns angle (theta) in radians, with 0 = horizontal, -pi/2 = vertical positive slope, pi/2 = vertical negative slope

RETURNS

An angle value in degrees.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> ls = img.findLines
>>> for l in ls:
>>>    if l.angle() == 0:
>>>       print "I AM HORIZONTAL."
crop()

SUMMARY

This function crops the source image to the location of the feature and returns a new SimpleCV image.

RETURNS

A SimpleCV image that is cropped to the feature position and size.

EXAMPLE

>>> img = Image("../sampleimages/EdgeTest2.png")
>>> l = img.findLines()
>>> myLine = l[0].crop()
draw(color=(0, 0, 255), width=1)

Draw the line, default color is blue

SUMMARY

Draw a small circle around the corner. Color tuple is single parameter, default is Red.

PARAMETERS

  • color - An RGB color triplet.
  • width - Draw the line using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

length()

SUMMARY

This method returns the length of the line.

RETURNS

A floating point length value.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> lines = img.findLines
>>> for l in lines:
>>>    if l.length() > 100:
>>>       print "OH MY! - WHAT A BIG LINE YOU HAVE!" 
>>>       print "---I bet you say that to all the lines."
meanColor()

SUMMARY

Returns the mean color of pixels under the line. Note that when the line falls “between” pixels, each pixels color contributes to the weighted average.

RETURNS

Returns an RGB triplet corresponding to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> l = img.findLines()
>>> c = l[0].meanColor()
class SimpleCV.Features.Detection.Motion(i, at_x, at_y, dx, dy, wndw)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

The motion feature is used to encapsulate optical flow vectors. The feature holds the length and direction of the vector.

crop()

This function returns the image in the sample window around the flow vector.

Returns Image

draw(color=(0, 128, 0), width=1, normalize=True)

SUMMARY Draw the optical flow vector going from the sample point along the length of the motion vector.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.
  • normalize - normalize the vector size to the size of the block (i.e. the biggest optical flow vector is scaled to the size of the block, all other vectors are scaled relative to the longest vector.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

dx = 0.0
dy = 0.0
image = ''
magnitude()

Returns the magnitude of the optical flow vector.

meanColor()

Return the color tuple from x,y SUMMARY

Return a numpy array of the average color of the area covered by each Feature.

RETURNS

Returns an array of RGB triplets the correspond to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> kp = img.findKeypoints()
>>> c = kp.meanColor()
norm_dx = 0.0
norm_dy = 0.0
normalizeTo(max_mag)

SUMMARY

This helper method normalizes the vector give an input magnitude. This is helpful for keeping the flow vector inside the sample window.

points = []
unitVector()

Returns the unit vector direction of the flow vector as an (x,y) tuple.

vector()

Returns the raw direction vector as an (x,y) tuple.

window = 7
windowSz()

Return the window size that we sampled over.

x = 0.0
y = 0.0
class SimpleCV.Features.Detection.TemplateMatch(image, template, location, quality)

Bases: SimpleCV.Features.Features.Feature

SUMMARY

This class is used for template (pattern) matching in images. The template matching cannot handle scale or rotation.

consume(other)

Given another template feature, make this feature the size of the two features combined.

draw(color=(0, 128, 0), width=1)

SUMMARY

Draw the bounding rectangle, default color green.

PARAMETERS

  • color - An RGB color triplet.
  • width - if width is less than zero we draw the feature filled in, otherwise we draw the contour using the specified width.

RETURNS

Nothing - this is an inplace operation that modifies the source images drawing layer.

h = 0
quality = 0
rescale(w, h)

This method keeps the feature’s center the same but sets a new width and height

template_image = None
w = 0

EdgeHistogramFeatureExtractor Module

class SimpleCV.Features.EdgeHistogramFeatureExtractor.EdgeHistogramFeatureExtractor(bins=10)

Bases: SimpleCV.Features.FeatureExtractorBase.FeatureExtractorBase

Create a 1D edge length histogram and 1D edge angle histogram.

This method takes in an image, applies an edge detector, and calculates the length and direction of lines in the image.

bins = the number of bins

extract(img)

Extract the line orientation and and length histogram.

getFieldNames()

Return the names of all of the length and angle fields.

getNumFields()

This method returns the total number of fields in the feature vector.

mNBins = 10

FeatureExtractorBase Module

class SimpleCV.Features.FeatureExtractorBase.FeatureExtractorBase

Bases: object

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.

extract(img)

Given an image extract the feature vector. The output should be a list object of all of the features. These features can be of any interal type (string, float, integer) but must contain no sub lists.

getFieldNames()

This method gives the names of each field in the feature vector in the order in which they are returned. For example, ‘xpos’ or ‘width’

getNumFields()

This method returns the total number of fields in the feature vector.

classmethod load(fname)

load segmentation settings to file.

save(fname)

Save segmentation settings to file.

Features Module

class SimpleCV.Features.Features.Feature(i, at_x, at_y, points)

Bases: object

SUMMARY

The Feature object is an abstract class which real features descend from. Each feature object has:

  • a draw() method,
  • an image property, referencing the originating Image object
  • x and y coordinates
  • default functions for determining angle, area, meanColor, etc for FeatureSets
  • in the Feature class, these functions assume the feature is 1px
above(object)

SUMMARY

Return true if the feature is above the object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is above the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].above(b) ):
>>>    print "above the biggest blob"
angle()

SUMMARY

Return the angle (theta) in degrees of the feature. The default is 0 (horizontal).

Warning

This is not a valid operation for all features.

RETURNS

An angle value in degrees.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if b.angle() == 0:
>>>       print "I AM HORIZONTAL."

TODO

Double check that values are being returned consistently.

area()

SUMMARY

Returns the area (number of pixels) covered by the feature.

RETURNS

An integer area of the feature.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if b.area() > 200:
>>>       print b.area()       
aspectRatio()

SUMMARY

Return the aspect ratio of the feature, which for our purposes is max(width,height)/min(width,height).

RETURNS

A single floating point value of the aspect ration.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> b[0].aspectRatio()
below(object)

SUMMARY

Return true if the feature is below the object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is below the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].below(b) ):
>>>    print "above the biggest blob"
bottomLeftCorner()

SUMMARY

This method returns the bottom left corner of the bounding box of the blob as an (x,y) tuple.

RESULT

Returns a tupple of the bottom left corner.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].bottomLeftCorner() 
bottomRightCorner()

SUMMARY

This method returns the bottom right corner of the bounding box of the blob as an (x,y) tuple.

RESULT

Returns a tupple of the bottom right corner.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].bottomRightCorner() 
boundingBox()

SUMMARY

This function calculates the corners of the feature and returns them as a list of (x,y) tuples.

RETURNS

A list of (x,y) corner tuples. The order is top left, bottom left, bottom right, top right. EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].boundingBox()

TO DO

Make the order of points go from the top left glockwise.

colorDistance(color=(0, 0, 0))

SUMMARY

Return the euclidean color distance of the color tuple at x,y from a given color (default black).

PARAMETERS

  • color - An RGB triplet to calculate from which to calculate the color distance.

RETURNS

A floating point color distance value.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    print b.colorDistance(color.WHITE):
contains(other)

SUMMARY

Return true if the feature contains the object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature contains the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].contains(b) ):
>>>    print "this blob is contained in the biggest blob"

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

coordinates()

SUMMARY

Returns the x,y position of the feature. This is usually the center coordinate.

RETURNS

Returns an (x,y) tuple of the position of the feature.

EXAMPLE

>>> img = Image("aerospace.png")
>>> blobs = img.findBlobs()
>>> for b in blobs:
>>>    print b.coordinates()
corners()
crop()

SUMMARY

This function crops the source image to the location of the feature and returns a new SimpleCV image.

RETURNS

A SimpleCV image that is cropped to the feature position and size.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> big = blobs[-1].crop()
>>> big.show()
distanceFrom(point=(-1, -1))

SUMMARY

Given a point (default to center of the image), return the euclidean distance of x,y from this point.

PARAMETERS

  • point - The point, as an (x,y) tuple on the image to measure distance from.

RETURNS

The distance as a floating point value in pixels.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> blobs[-1].distanceFrom(blobs[-2].coordinates())
distanceToNearestEdge()

SUMMARY

This method returns the distance, in pixels, from the nearest image edge.

RETURNS

The integer distance to the nearest edge.

EXAMPLE

>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> b[0].distanceToNearestEdge()
doesNotContain(other)

SUMMARY

Return true if the feature does not contain the other object, where other can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • other
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature does not contain the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].doesNotContain(b) ):
>>>    print "above the biggest blob"

Returns true if all of features points are inside this point.

doesNotOverlap(other)

SUMMARY

Return true if the feature does not overlap the object other, where other can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • other
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature does not Overlap the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].doesNotOverlap(b) ):
>>>    print "does not over overlap biggest blob"
draw(color=(0, 128, 0))

SUMMARY

This method will draw the feature on the source image.

PARAMETERS

  • color - The color as an RGB tuple to render the image.

RETURNS

Nothing.

EXAMPLE

>>> img = Image("RedDog2.jpg")
>>> blobs = img.findBlobs()
>>> blobs[-1].draw()
>>> img.show()
extents()

SUMMARY

This function returns the maximum and minimum x and y values for the feature and returns them as a tuple.

RETURNS

A tuple of the extents of the feature. The order is (MaxX,MaxY,MinX,MinY).

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].extents()
height()

SUMMARY

Returns the height of the feature.

RETURNS

An integer value of the feature’s height.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if b.width() > b.height():
>>>       print "wider than tall"
>>>       b.draw()
>>> img.show()
image = ''
isContainedWithin(other)

SUMMARY

Return true if the feature is contained withing the object other, where other can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • other
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is above the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].isContainedWithin(b) ):
>>>    print "inside the blob"
isNotContainedWithin(shape)

SUMMARY

Return true if the feature is not contained within the shape, where shape can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • shape
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is not contained within the shape, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].isNotContainedWithin(b) ):
>>>    print "Not inside the biggest blob"
left(object)

SUMMARY

Return true if the feature is to the left of the object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is to the left of the object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].left(b) ):
>>>    print "left of  the biggest blob"
length()

SUMMARY

This method returns the longest dimension of the feature (i.e max(width,height)).

RETURNS

A floating point length value.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if b.length() > 200:
>>>       print "OH MY! - WHAT A BIG FEATURE YOU HAVE!" 
>>>       print "---I bet you say that to all the features."

TODO

Should this be sqrt(x*x+y*y)?

mBoundingBox = None
mExtents = None
maxX()

SUMMARY

This method return the minimum x value of the bounding box of the the feature.

RETURNS

An integer value of the maxium x value of the feature.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].maxX()
maxY()

SUMMARY

This method return the maximum y value of the bounding box of the the feature.

RETURNS

An integer value of the maximum y value of the feature.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].maxY()
meanColor()

SUMMARY

Return the average color within the feature as a tuple.

RETURNS

An RGB color tuple.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if (b.meanColor() == color.WHITE):
>>>       print "Found a white thing"
minX()

SUMMARY

This method return the minimum x value of the bounding box of the the feature.

RETURNS

An integer value of the minimum x value of the feature.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].minX()
minY()

SUMMARY

This method return the minimum y value of the bounding box of the the feature.

RETURNS

An integer value of the minimum y value of the feature.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].minY()
notOnImageEdge(tolerance=1)

SUMMARY

This method returns True if the feature is greate than tolerance pixels away from the nearest edge.

PARAMETERS

  • tolerance - the distance in pixels at which a feature qualifies as not being on the image edge.

RETURNS

True if the feature is not on the edge of the image, False otherwise.

EXAMPLE

>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> if(b[0].notOnImageEdge()):
>>>     print "I am safe and sound."
onImageEdge(tolerance=1)

SUMMARY

This method returns True if the feature is less than tolerance pixels away from the nearest edge.

PARAMETERS

  • tolerance - the distance in pixels at which a feature qualifies as being on the image edge.

RETURNS

True if the feature is on the edge, False otherwise.

EXAMPLE

>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> if(b[0].onImageEdge()):
>>>     print "HELP! I AM ABOUT TO FALL OFF THE IMAGE"
overlaps(other)

SUMMARY

Return true if the feature overlaps the object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature overlaps object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].overlaps(b) ):
>>>    print "This blob overlaps the biggest blob"

Returns true if this blob contains at least one point, part of a collection of points, or any part of a blob.

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

points = None
right(object)

SUMMARY

Return true if the feature is to the right object, where object can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • object
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a Boolean, True if the feature is to the right object, False otherwise.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].right(b) ):
>>>    print "right of the the blob"
show(color=(0, 128, 0))

SUMMARY

This function will automatically draw the features on the image and show it.

RETURNS

Nothing.

EXAMPLE

>>> img = Image("logo")
>>> feat = img.findBlobs()
>>> feat[-1].show() #window pops up. 
topLeftCorner()

SUMMARY

This method returns the top left corner of the bounding box of the blob as an (x,y) tuple.

RESULT

Returns a tupple of the top left corner.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].topLeftCorner() 
topRightCorner()

SUMMARY

This method returns the top right corner of the bounding box of the blob as an (x,y) tuple.

RESULT

Returns a tupple of the top right corner.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].topRightCorner() 
width()

SUMMARY

Returns the height of the feature.

RETURNS

An integer value for the feature’s width.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>    if b.width() > b.height():
>>>       print "wider than tall"
>>>       b.draw()
>>> img.show()
x = 0.0
y = 0.0
class SimpleCV.Features.Features.FeatureSet

Bases: list

SUMMARY

FeatureSet is a class extended from Python’s list which has special functions so that it is useful for handling feature metadata on an image.

In general, functions dealing with attributes will return numpy arrays, and functions dealing with sorting or filtering will return new FeatureSets.

EXAMPLE

>>> image = Image("/path/to/image.png")
>>> lines = image.findLines()  #lines are the feature set
>>> lines.draw()
>>> lines.x()
>>> lines.crop()
above(region)

SUMMARY

Return only the features that are above a region. Where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are above the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.above(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

angle()

SUMMARY

Return a numpy array of the angles (theta) of each feature. Note that theta is given in degrees, with 0 being horizontal.

RETURNS

An array of angle values corresponding to the features.

EXAMPLE

>>> img = Image("lenna")
>>> l = img.findLines()
>>> angs = l.angle()
>>> print angs
area()

SUMMARY

Returns a numpy array of the area of each feature in pixels.

RETURNS

A numpy array of all the positions in the featureset.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.area()
>>> print xs
aspectRatios()

SUMMARY

Return the aspect ratio of all the features in the feature set, For our purposes aspect ration is max(width,height)/min(width,height).

RETURNS

A numpy array of the aspect ratio of the features in the featureset.

EXAMPLE

>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs.aspectRatio()
below(region)

SUMMARY

Return only the features below the region. where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are below the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> inside = lines.below(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

bottomLeftCorners()

SUMMARY

This method returns the bottom left corner of each feature’s bounding box.

RETURNS

A numpy array of x,y position values.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> bl = img.bottomLeftCorners()
>>> print bl[0] 
bottomRightCorners()

SUMMARY

This method returns the bottom right corner of each feature’s bounding box.

RETURNS

A numpy array of x,y position values.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> br = img.bottomRightCorners()
>>> print br[0] 
center()
colorDistance(color=(0, 0, 0))

SUMMARY

Return a numpy array of the distance each features average color is from a given color tuple (default black, so colorDistance() returns intensity)

PARAMETERS

  • color - The color to calculate the distance from.

RETURNS

The distance of the average color for the feature from given color as a numpy array.

EXAMPLE

>>> img = Image("lenna")
>>> circs = img.findCircle()
>>> d = circs.colorDistance(color=Color.BLUE)
>>> print d
coordinates()

SUMMARY

Returns a 2d numpy array of the x,y coordinates of each feature. This is particularly useful if you want to use Scipy’s Spatial Distance module

RETURNS

A numpy array of all the positions in the featureset.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.coordinates()
>>> print xs
crop()

SUMMARY

Returns a nparray with the cropped features as SimpleCV image.

RETURNS

A SimpleCV image cropped to each image.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>>   newImg = b.crop()
>>>   newImg.show()
>>>   time.sleep(1)
distanceFrom(point=(-1, -1))

SUMMARY

Returns a numpy array of the distance each Feature is from a given coordinate. Default is the center of the image.

PARAMETERS

  • point - A point on the image from which we will calculate distance.

RETURNS

A numpy array of distance values.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.distanceFrom()
>>> d[0]  #show the 0th blobs distance to the center. 

TO DO

Make this accept other features to measure from.

distancePairs()

SUMMARY

Returns the square-form of pairwise distances for the featureset. The resulting N x N array can be used to quickly look up distances between features.

RETURNS

A NxN np matrix of distance values.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.distancePairs()
>>> print d
draw(color=(0, 128, 0), width=1, autocolor=False)

SUMMARY

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 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

Nada. Nothing. Zilch.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats.draw(color=Color.PUCE, width=3)
>>> img.show()
filter(filterarray)

SUMMARY

Return a FeatureSet which is filtered on a numpy boolean array. This will let you use the attribute functions to easily screen Features out of return FeatureSets.

PARAMETERS

  • filterarray - A numpy array, matching the size of the feature set, made of Boolean values, we return the true values and reject the False value.

RETURNS

The revised feature set.

EXAMPLE

Return all lines < 200px

>>> my_lines.filter(my_lines.length() < 200) # returns all lines < 200px
>>> my_blobs.filter(my_blobs.area() > 0.9 * my_blobs.length**2) # returns blobs that are nearly square    
>>> my_lines.filter(abs(my_lines.angle()) < numpy.pi / 4) #any lines within 45 degrees of horizontal
>>> my_corners.filter(my_corners.x() - my_corners.y() > 0) #only return corners in the upper diagonal of the image
height()

Returns a nparray which is the height of all the objects in the FeatureSet

RETURNS

A numpy array of width values.

EXAMPLE

>>> img = Image("NotLenna")
>>> l = img.findLines()
>>> l.height()
image
inside(region)

SUMMARY

Return only the features inside the region. where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are inside the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> inside = lines.inside(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

left(region)

SUMMARY

Return only the features left of the region. where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are left of the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> left = lines.left(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

length()

SUMMARY

Return a numpy array of the length (longest dimension) of each feature.

RETURNS

A numpy array of the length, in pixels, of eatch feature object.

EXAMPLE

>>> img = Image("Lenna")
>>> l = img.findLines()
>>> lengt = l.length()
>>> lengt[0] # length of the 0th element. 
meanColor()

SUMMARY

Return a numpy array of the average color of the area covered by each Feature.

RETURNS

Returns an array of RGB triplets the correspond to the mean color of the feature.

EXAMPLE

>>> img = Image("lenna")
>>> kp = img.findKeypoints()
>>> c = kp.meanColor()
notOnImageEdge(tolerance=1)

SUMMARY

The method returns a feature set of features that are not on or “near” the edge of the image. This is really helpful for removing features that are edge effects.

PARAMETERS

  • tolerance - the distance in pixels from the edge at which a feature qualifies as being “on” the edge of the image.

RETURNS

Returns a featureset of features that are not on the edge of the image.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> es = blobs.notOnImageEdge()
>>> es.draw(color=Color.RED)
>>> img.show()
onImageEdge(tolerance=1)

SUMMARY

The method returns a feature set of features that are on or “near” the edge of the image. This is really helpful for removing features that are edge effects.

PARAMETERS

  • tolerance - the distance in pixels from the edge at which a feature qualifies as being “on” the edge of the image.

RETURNS

Returns a featureset of features that are on the edge of the image.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> es = blobs.onImageEdge()
>>> es.draw(color=Color.RED)
>>> img.show()
outside(region)

SUMMARY

Return only the features outside the region. where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are outside the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.outside(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

overlaps(region)

SUMMARY

Return only the features that overlap or the region. Where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that overlap the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.overlaps(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

right(region)

SUMMARY

Return only the features right of the region. where region can be a bounding box, bounding circle, a list of tuples in a closed polygon, or any other featutres.

PARAMETERS

  • region
    • A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
    • A bounding circle of the form (x,y,r)
    • A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
    • Any two dimensional feature (e.g. blobs, circle ...)

RETURNS

Returns a featureset of features that are right of the region.

EXAMPLE

>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> right = lines.right(b)

NOTE

This currently performs a bounding box test, not a full polygon test for speed.

show(color=(0, 128, 0), autocolor=False, width=1)

EXAMPLE

This function will automatically draw the features on the image and show it. It is a basically a shortcut function for development and is the same as:

PARAMETERS

  • color - The color to draw the object. Either an BGR tuple or a member of the 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

Nada. Nothing. Zilch.

EXAMPLE >>> img = Image(“logo”) >>> feat = img.findBlobs() >>> if feat: feat.draw() >>> img.show()

sortAngle(theta=0)

Return a sorted FeatureSet with the features closest to a given angle first. Note that theta is given in radians, with 0 being horizontal.

RETURNS

An array of angle values corresponding to the features.

EXAMPLE

>>> img = Image("lenna")
>>> l = img.findLines()
>>> l = l.sortAngle()
>>> print angs
sortArea()

SUMMARY

Returns a new FeatureSet, with the largest area features first.

RETURNS

A featureset sorted based on area.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats = feats.sortArea()
>>> print feats[-1] # biggest blob
>>> print feats[0] # smallest blob
sortColorDistance(color=(0, 0, 0))

Return a sorted FeatureSet with features closest to a given color first. Default is black, so sortColorDistance() will return darkest to brightest

sortDistance(point=(-1, -1))

SUMMARY

Returns a sorted FeatureSet with the features closest to a given coordinate first. Default is from the center of the image.

PARAMETERS

  • point - A point on the image from which we will calculate distance.

RETURNS

A numpy array of distance values.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.sortDistance()
>>> d[-1].show()  #show the 0th blobs distance to the center. 
sortLength()

SUMMARY

Return a sorted FeatureSet with the longest features first.

RETURNS

A sorted FeatureSet.

EXAMPLE

>>> img = Image("Lenna")
>>> l = img.findLines().sortLength()
>>> lengt[-1] # length of the 0th element. 
topLeftCorners()

SUMMARY

This method returns the top left corner of each feature’s bounding box.

RETURNS

A numpy array of x,y position values.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> tl = img.bottomLeftCorners()
>>> print tl[0] 
topRightCorners()

SUMMARY

This method returns the top right corner of each feature’s bounding box.

RETURNS

A numpy array of x,y position values.

EXAMPLE

>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> tr = img.topRightCorners()
>>> print tr[0] 
width()

SUMMARY

Returns a nparray which is the width of all the objects in the FeatureSet.

RETURNS

A numpy array of width values.

EXAMPLE

>>> img = Image("NotLenna")
>>> l = img.findLines()
>>> l.width()
x()

SUMMARY

Returns a numpy array of the x (horizontal) coordinate of each feature.

RETURNS

A numpy array.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.x()
>>> print xs
y()

SUMMARY

Returns a numpy array of the y (vertical) coordinate of each feature.

RETURNS

A numpy array.

EXAMPLE

>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.y()
>>> print xs

HaarCascade Module

class SimpleCV.Features.HaarCascade.HaarCascade(fname, name=None)

This class wraps HaarCascade files for the findHaarFeatures file. To use the class provide it with the path to a Haar cascade XML file and optionally a name.

getCascade()
getName()
load(fname, name=None)
setName(name)

HaarLikeFeature Module

class SimpleCV.Features.HaarLikeFeature.HaarLikeFeature(name=None, regions=None)

Create a single Haar feature and optionally set the regions that define the Haar feature and its name. The formal of the feature is

The format is [[[TL],[BR],SIGN],[[TL],[BR],SIGN].....] Where TR and BL are the unit coorinates for the top right and bottom left coodinates.

For example [[[0,0],[0.5,0.5],1],[[0.5.0],[1.0,1.0],-1]]

Takes the right side of the image and subtracts from the left hand side of the image.

apply(intImg)

This method takes in an integral image and applies the haar-cascade to the image, and returns the result.

mName = None
mRegions = None
setName(name)

Set the name of this feature, the name must be unique.

setRegions(regions)

Set the list of regions. The regions are square coordinates on a unit sized image followed by the sign of a region.

The format is [[[TL],[BR],SIGN],[[TL],[BR],SIGN].....] Where TR and BL are the unit coorinates for the top right and bottom left coodinates.

For example [[[0,0],[0.5,0.5],1],[[0.5.0],[1.0,1.0],-1]]

Takes the right side of the image and subtracts from the left hand side of the image.

writeToFile(file)

Write the Haar cascade to a human readable file. file is an open file pointer.

HaarLikeFeatureExtractor Module

class SimpleCV.Features.HaarLikeFeatureExtractor.HaarLikeFeatureExtractor(fname=None, do45=True)

Bases: SimpleCV.Features.FeatureExtractorBase.FeatureExtractorBase

This is used generate Haar like features from an image. These Haar like features are used by a the classifiers of machine learning to help identify objects or things in the picture by their features, or in this case haar features.

For a more in-depth review of Haar Like features see: http://en.wikipedia.org/wiki/Haar-like_features

extract(img)

This extractor takes in an image, creates the integral image, applies the Haar cascades, and returns the result as a feature vector.

getFieldNames()

This method gives the names of each field in the feature vector in the order in which they are returned. For example, ‘xpos’ or ‘width’

getNumFields()

This method returns the total number of fields in the feature vector.

mDo45 = True
mFeatureSet = None
readWavelets(fname, nfeats=-1)

fname = file name nfeats = number of features to load from file -1 -> All features

saveWavelets(fname)

Save wavelets to file

HueHistogramFeatureExtractor Module

class SimpleCV.Features.HueHistogramFeatureExtractor.HueHistogramFeatureExtractor(mNBins=16)

Bases: SimpleCV.Features.FeatureExtractorBase.FeatureExtractorBase

Create a Hue Histogram feature extractor. This feature extractor takes in an image, gets the hue channel, bins the number of pixels with a particular Hue, and returns the results.

mNBins - the number of Hue bins.

extract(img)

This feature extractor takes in a color image and returns a normalized color histogram of the pixel counts of each hue.

getFieldNames()

This method gives the names of each field in the feature vector in the order in which they are returned. For example, ‘xpos’ or ‘width’

getNumFields()

This method returns the total number of fields in the feature vector.

mNBins = 16

MorphologyFeatureExtractor Module

class SimpleCV.Features.MorphologyFeatureExtractor.MorphologyFeatureExtractor(thresholdOperation=None)

Bases: SimpleCV.Features.FeatureExtractorBase.FeatureExtractorBase

This feature extractor collects some basic morphology infromation about a given image. It is assumed that the object to be recognized is the largest object in the image. The user must provide a segmented white on black blob image. This operation then straightens the image and collects the data.

extract(img)

This method takes in a image and returns some basic morphology characteristics about the largest blob in the image. The if a color image is provided the threshold operation is applied.

getFieldNames()

This method gives the names of each field in the feature vector in the order in which they are returned. For example, ‘xpos’ or ‘width’

getNumFields()

This method returns the total number of fields in the feature vector.

mBlobMaker = None
mNBins = 9
mThresholdOpeation = None
setThresholdOperation(threshOp)

The threshold operation is a function of the form binaryimg = threshold(img)

Example:

>>> def binarize_wrap(img):
>>>    return img.binarize()