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

changed print statement compatible to run with python3 #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion PCV/classifiers/bayes.py
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ def classify(self,points):
# compute probabilities for each class
est_prob = array([gauss(m,v,points) for m,v in zip(self.mean,self.var)])

print 'est prob',est_prob.shape,self.labels
print('est prob',est_prob.shape,self.labels)
# get index of highest probability, this gives class label
ndx = est_prob.argmax(axis=0)

4 changes: 2 additions & 2 deletions PCV/geometry/warp.py
Original file line number Diff line number Diff line change
@@ -110,7 +110,7 @@ def transf(p):
return (p2[0]/p2[2],p2[1]/p2[2])

if H[1,2]<0: # fromim is to the right
print 'warp - right'
print('warp - right')
# transform fromim
if is_color:
# pad the destination image with zeros to the right
@@ -125,7 +125,7 @@ def transf(p):
fromim_t = ndimage.geometric_transform(fromim,transf,
(toim.shape[0],toim.shape[1]+padding))
else:
print 'warp - left'
print('warp - left')
# add translation to compensate for padding to the left
H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]])
H = dot(H,H_delta)
2 changes: 1 addition & 1 deletion PCV/imagesearch/imagesearch.py
Original file line number Diff line number Diff line change
@@ -42,7 +42,7 @@ def add_to_index(self,imname,descr):
project on vocabulary and add to database. """

if self.is_indexed(imname): return
print 'indexing', imname
print('indexing', imname)

# get the imid
imid = self.get_id(imname)
2 changes: 1 addition & 1 deletion PCV/localdescriptors/dsift.py
Original file line number Diff line number Diff line change
@@ -35,5 +35,5 @@ def process_image_dsift(imagename,resultname,size=20,steps=10,force_orientation=
cmmd = str("sift "+imagename+" --output="+resultname+
" --read-frames=tmp.frame")
os.system(cmmd)
print 'processed', imagename, 'to', resultname
print('processed', imagename, 'to', resultname)

2 changes: 1 addition & 1 deletion PCV/localdescriptors/sift.py
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@ def process_image(imagename,resultname,params="--edge-thresh 10 --peak-thresh 5"
cmmd = str("sift "+imagename+" --output="+resultname+
" "+params)
os.system(cmmd)
print 'processed', imagename, 'to', resultname
print('processed', imagename, 'to', resultname)


def read_features_from_file(filename):
2 changes: 1 addition & 1 deletion PCV/tools/imtools.py
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ def compute_average(imlist):
try:
averageim += array(Image.open(imname))
except:
print imname + "...skipped"
print(imname + "...skipped")
skipped += 1

averageim /= (len(imlist) - skipped)
2 changes: 1 addition & 1 deletion PCV/tools/ncut.py
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ def cluster(S,k,ndim):

# check for symmetry
if sum(abs(S-S.T)) > 1e-10:
print 'not symmetric'
print('not symmetric')

# create Laplacian matrix
rowsum = sum(abs(S),axis=0)
27 changes: 13 additions & 14 deletions PCV/tools/ransac.py
Original file line number Diff line number Diff line change
@@ -80,28 +80,27 @@ def ransac(data,model,n,k,t,d,debug=False,return_all=False):
best_inlier_idxs = None
while iterations < k:
maybe_idxs, test_idxs = random_partition(n,data.shape[0])
maybeinliers = data[maybe_idxs,:]
maybeinliers = data[maybe_idxs, :]
test_points = data[test_idxs]
maybemodel = model.fit(maybeinliers)
test_err = model.get_error( test_points, maybemodel)
also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points
alsoinliers = data[also_idxs,:]
test_err = model.get_error(test_points, maybemodel)
also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points
alsoinliers = data[also_idxs, :]
if debug:
print 'test_err.min()',test_err.min()
print 'test_err.max()',test_err.max()
print 'numpy.mean(test_err)',numpy.mean(test_err)
print 'iteration %d:len(alsoinliers) = %d'%(
iterations,len(alsoinliers))
print('test_err.min()', test_err.min())
print('test_err.max()', test_err.max())
print('numpy.mean(test_err)', numpy.mean(test_err))
print('iteration %d:len(alsoinliers) = %d' % (iterations, len(alsoinliers)))
if len(alsoinliers) > d:
betterdata = numpy.concatenate( (maybeinliers, alsoinliers) )
betterdata = numpy.concatenate((maybeinliers, alsoinliers))
bettermodel = model.fit(betterdata)
better_errs = model.get_error( betterdata, bettermodel)
thiserr = numpy.mean( better_errs )
better_errs = model.get_error(betterdata, bettermodel)
thiserr = numpy.mean(better_errs)
if thiserr < besterr:
bestfit = bettermodel
besterr = thiserr
best_inlier_idxs = numpy.concatenate( (maybe_idxs, also_idxs) )
iterations+=1
best_inlier_idxs = numpy.concatenate((maybe_idxs, also_idxs))
iterations += 1
if bestfit is None:
raise ValueError("did not meet fit acceptance criteria")
if return_all:
4 changes: 2 additions & 2 deletions examples/ch1_morphology.py
Original file line number Diff line number Diff line change
@@ -12,10 +12,10 @@
im = (im<128)

labels, nbr_objects = measurements.label(im)
print "Number of objects:", nbr_objects
print("Number of objects:", nbr_objects)

# morphology - opening to separate objects better
im_open = morphology.binary_opening(im,ones((9,5)),iterations=2)

labels_open, nbr_objects_open = measurements.label(im_open)
print "Number of objects:", nbr_objects_open
print("Number of objects:", nbr_objects_open)
2 changes: 1 addition & 1 deletion examples/ch2_download_panoramio.py
Original file line number Diff line number Diff line change
@@ -20,4 +20,4 @@
for url in imurls:
image = urllib.URLopener()
image.retrieve(url, os.path.basename(urlparse.urlparse(url).path))
print 'downloading:', url
print('downloading:', url)
2 changes: 1 addition & 1 deletion examples/ch2_harris_matching.py
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@
filtered_coords2 = harris.get_harris_points(harrisim,wid+1)
d2 = harris.get_descriptors(im2,filtered_coords2,wid)

print 'starting matching'
print('starting matching')
matches = harris.match_twosided(d1,d2)

figure()
4 changes: 2 additions & 2 deletions examples/ch2_matching_graph.py
Original file line number Diff line number Diff line change
@@ -28,12 +28,12 @@

for i in range(nbr_images):
for j in range(i,nbr_images): # only compute upper triangle
print 'comparing ', imlist[i], imlist[j]
print('comparing ', imlist[i], imlist[j])
l1,d1 = sift.read_features_from_file(featlist[i])
l2,d2 = sift.read_features_from_file(featlist[j])
matches = sift.match_twosided(d1,d2)
nbr_matches = sum(matches > 0)
print 'number of matches = ', nbr_matches
print('number of matches = ', nbr_matches)
matchscores[i,j] = nbr_matches

# copy values
2 changes: 1 addition & 1 deletion examples/ch8_bayes_points.py
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@
labels = pickle.load(f)

# test on the 10 first points
print bc.classify(class_1[:10])[0]
print(bc.classify(class_1[:10])[0])

# define function for plotting
def classify(x, y, bc=bc):
12 changes: 6 additions & 6 deletions examples/ch8_gesture_recognition.py
Original file line number Diff line number Diff line change
@@ -54,20 +54,20 @@ def print_confusion(res,labels,classnames):
for i in range(len(test_labels)):
confuse[class_ind[res[i]],class_ind[test_labels[i]]] += 1

print 'Confusion matrix for'
print classnames
print confuse
print('Confusion matrix for')
print(classnames)
print(confuse)


# read training data
####################
features,labels = read_gesture_features_labels('../data/hand_gesture/train/')
print 'training data is:', features.shape, len(labels)
print('training data is:', features.shape, len(labels))

# read test data
####################
test_features,test_labels = read_gesture_features_labels('../data/hand_gesture/test/')
print 'test data is:', test_features.shape, len(test_labels)
print('test data is:', test_features.shape, len(test_labels))

classnames = unique(labels)
nbr_classes = len(classnames)
@@ -129,6 +129,6 @@ def print_confusion(res,labels,classnames):

# accuracy
acc = sum(1.0*(res==test_labels)) / len(test_labels)
print 'Accuracy:', acc
print('Accuracy:', acc)

print_confusion(res,test_labels,classnames)
4 changes: 3 additions & 1 deletion examples/ch8_knn_points.py
Original file line number Diff line number Diff line change
@@ -28,12 +28,14 @@
labels = pickle.load(f)

# test on the first point
print model.classify(class_1[0])
print(model.classify(class_1[0]))


# define function for plotting
def classify(x, y, model=model):
return array([model.classify([xx,yy]) for (xx,yy) in zip(x,y)])


# plot the classification boundary
imtools.plot_2D_boundary([-6,6,-6,6], [class_1,class_2], classify, [1,-1])
show()
2 changes: 1 addition & 1 deletion examples/ch8_process_handgestures.py
Original file line number Diff line number Diff line change
@@ -29,7 +29,7 @@
# show an image with features
l,d = sift.read_features_from_file(featfile)
im = array(Image.open(filename).resize((50,50)))
print im.shape
print(im.shape)

figure()
sift.plot_features(im, l, True)
2 changes: 1 addition & 1 deletion pcv_book/bayes.py
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ def classify(self,points):
# compute probabilities for each class
est_prob = array([gauss(m,v,points) for m,v in zip(self.mean,self.var)])

print 'est prob',est_prob.shape,self.labels
print('est prob',est_prob.shape,self.labels)
# get index of highest probability, this gives class label
ndx = est_prob.argmax(axis=0)

2 changes: 1 addition & 1 deletion pcv_book/dsift.py
Original file line number Diff line number Diff line change
@@ -34,5 +34,5 @@ def process_image_dsift(imagename,resultname,size=20,steps=10,force_orientation=
cmmd = str("sift "+imagename+" --output="+resultname+
" --read-frames=tmp.frame")
os.system(cmmd)
print 'processed', imagename, 'to', resultname
print('processed', imagename, 'to', resultname)

2 changes: 1 addition & 1 deletion pcv_book/imagesearch.py
Original file line number Diff line number Diff line change
@@ -42,7 +42,7 @@ def add_to_index(self,imname,descr):
project on vocabulary and add to database. """

if self.is_indexed(imname): return
print 'indexing', imname
print('indexing', imname)

# get the imid
imid = self.get_id(imname)
2 changes: 1 addition & 1 deletion pcv_book/imtools.py
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ def compute_average(imlist):
try:
averageim += array(Image.open(imname))
except:
print imname + "...skipped"
print(imname + "...skipped")
skipped += 1

averageim /= (len(imlist) - skipped)
2 changes: 1 addition & 1 deletion pcv_book/ncut.py
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ def cluster(S,k,ndim):

# check for symmetry
if sum(abs(S-S.T)) > 1e-10:
print 'not symmetric'
print('not symmetric')

# create Laplacian matrix
rowsum = sum(abs(S),axis=0)
135 changes: 70 additions & 65 deletions pcv_book/ransac.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy
import scipy # use numpy if scipy unavailable
import scipy.linalg # use numpy if scipy unavailable
import scipy # use numpy if scipy unavailable
import scipy.linalg # use numpy if scipy unavailable

## Copyright (c) 2004-2007, Andrew D. Straw. All rights reserved.

@@ -79,130 +79,135 @@ def ransac(data,model,n,k,t,d,debug=False,return_all=False):
besterr = numpy.inf
best_inlier_idxs = None
while iterations < k:
maybe_idxs, test_idxs = random_partition(n,data.shape[0])
maybeinliers = data[maybe_idxs,:]
maybe_idxs, test_idxs = random_partition(n, data.shape[0])
maybeinliers = data[maybe_idxs, :]
test_points = data[test_idxs]
maybemodel = model.fit(maybeinliers)
test_err = model.get_error( test_points, maybemodel)
also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points
alsoinliers = data[also_idxs,:]
test_err = model.get_error(test_points, maybemodel)
also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points
alsoinliers = data[also_idxs, :]
if debug:
print 'test_err.min()',test_err.min()
print 'test_err.max()',test_err.max()
print 'numpy.mean(test_err)',numpy.mean(test_err)
print 'iteration %d:len(alsoinliers) = %d'%(
iterations,len(alsoinliers))
print('test_err.min()', test_err.min())
print('test_err.max()', test_err.max())
print('numpy.mean(test_err)', numpy.mean(test_err))
print('iteration {}:len(alsoinliers) = {}'.format(iterations, len(alsoinliers)))
if len(alsoinliers) > d:
betterdata = numpy.concatenate( (maybeinliers, alsoinliers) )
betterdata = numpy.concatenate((maybeinliers, alsoinliers))
bettermodel = model.fit(betterdata)
better_errs = model.get_error( betterdata, bettermodel)
thiserr = numpy.mean( better_errs )
better_errs = model.get_error(betterdata, bettermodel)
thiserr = numpy.mean(better_errs)
if thiserr < besterr:
bestfit = bettermodel
besterr = thiserr
best_inlier_idxs = numpy.concatenate( (maybe_idxs, also_idxs) )
iterations+=1
best_inlier_idxs = numpy.concatenate((maybe_idxs, also_idxs))
iterations += 1
if bestfit is None:
raise ValueError("did not meet fit acceptance criteria")
if return_all:
return bestfit, {'inliers':best_inlier_idxs}
return bestfit, {'inliers': best_inlier_idxs}
else:
return bestfit

def random_partition(n,n_data):

def random_partition(n, n_data):
"""return n random rows of data (and also the other len(data)-n rows)"""
all_idxs = numpy.arange( n_data )
all_idxs = numpy.arange(n_data)
numpy.random.shuffle(all_idxs)
idxs1 = all_idxs[:n]
idxs2 = all_idxs[n:]
return idxs1, idxs2


class LinearLeastSquaresModel:
"""linear system solved using linear least squares
This class serves as an example that fulfills the model interface
needed by the ransac() function.
"""
def __init__(self,input_columns,output_columns,debug=False):

def __init__(self, input_columns, output_columns, debug=False):
self.input_columns = input_columns
self.output_columns = output_columns
self.debug = debug

def fit(self, data):
A = numpy.vstack([data[:,i] for i in self.input_columns]).T
B = numpy.vstack([data[:,i] for i in self.output_columns]).T
x,resids,rank,s = numpy.linalg.lstsq(A,B)
A = numpy.vstack([data[:, i] for i in self.input_columns]).T
B = numpy.vstack([data[:, i] for i in self.output_columns]).T
x, resids, rank, s = numpy.linalg.lstsq(A, B)
return x
def get_error( self, data, model):
A = numpy.vstack([data[:,i] for i in self.input_columns]).T
B = numpy.vstack([data[:,i] for i in self.output_columns]).T
B_fit = scipy.dot(A,model)
err_per_point = numpy.sum((B-B_fit)**2,axis=1) # sum squared error per row

def get_error(self, data, model):
A = numpy.vstack([data[:, i] for i in self.input_columns]).T
B = numpy.vstack([data[:, i] for i in self.output_columns]).T
B_fit = scipy.dot(A, model)
err_per_point = numpy.sum((B - B_fit) ** 2, axis=1) # sum squared error per row
return err_per_point



def test():
# generate perfect input data

n_samples = 500
n_inputs = 1
n_outputs = 1
A_exact = 20*numpy.random.random((n_samples,n_inputs) )
perfect_fit = 60*numpy.random.normal(size=(n_inputs,n_outputs) ) # the model
B_exact = scipy.dot(A_exact,perfect_fit)
assert B_exact.shape == (n_samples,n_outputs)
A_exact = 20 * numpy.random.random((n_samples, n_inputs))
perfect_fit = 60 * numpy.random.normal(size=(n_inputs, n_outputs)) # the model
B_exact = scipy.dot(A_exact, perfect_fit)
assert B_exact.shape == (n_samples, n_outputs)

# add a little gaussian noise (linear least squares alone should handle this well)
A_noisy = A_exact + numpy.random.normal(size=A_exact.shape )
B_noisy = B_exact + numpy.random.normal(size=B_exact.shape )
A_noisy = A_exact + numpy.random.normal(size=A_exact.shape)
B_noisy = B_exact + numpy.random.normal(size=B_exact.shape)

if 1:
# add some outliers
n_outliers = 100
all_idxs = numpy.arange( A_noisy.shape[0] )
all_idxs = numpy.arange(A_noisy.shape[0])
numpy.random.shuffle(all_idxs)
outlier_idxs = all_idxs[:n_outliers]
non_outlier_idxs = all_idxs[n_outliers:]
A_noisy[outlier_idxs] = 20*numpy.random.random((n_outliers,n_inputs) )
B_noisy[outlier_idxs] = 50*numpy.random.normal(size=(n_outliers,n_outputs) )
A_noisy[outlier_idxs] = 20 * numpy.random.random((n_outliers, n_inputs))
B_noisy[outlier_idxs] = 50 * numpy.random.normal(size=(n_outliers, n_outputs))

# setup model

all_data = numpy.hstack( (A_noisy,B_noisy) )
input_columns = range(n_inputs) # the first columns of the array
output_columns = [n_inputs+i for i in range(n_outputs)] # the last columns of the array
input_columns = range(n_inputs) # the first columns of the array
output_columns = [n_inputs+i for i in range(n_outputs)] # the last columns of the array
debug = True
model = LinearLeastSquaresModel(input_columns,output_columns,debug=debug)

linear_fit,resids,rank,s = numpy.linalg.lstsq(all_data[:,input_columns],all_data[:,output_columns])
model = LinearLeastSquaresModel(input_columns, output_columns, debug=debug)

linear_fit, resids, rank, s = numpy.linalg.lstsq(numpy.hstack((A_noisy, B_noisy))[:, input_columns],
numpy.hstack((A_noisy, B_noisy))[:, output_columns])

# run RANSAC algorithm
ransac_fit, ransac_data = ransac(all_data,model,
5, 5000, 7e4, 50, # misc. parameters
debug=debug,return_all=True)
ransac_fit, ransac_data = ransac(numpy.hstack((A_noisy, B_noisy)), model,
5, 5000, 7e4, 50, # misc. parameters
debug=debug, return_all=True)
if 1:
import pylab

sort_idxs = numpy.argsort(A_exact[:,0])
A_col0_sorted = A_exact[sort_idxs] # maintain as rank-2 array
sort_idxs = numpy.argsort(A_exact[:, 0])
A_col0_sorted = A_exact[sort_idxs] # maintain as rank-2 array

if 1:
pylab.plot( A_noisy[:,0], B_noisy[:,0], 'k.', label='data' )
pylab.plot( A_noisy[ransac_data['inliers'],0], B_noisy[ransac_data['inliers'],0], 'bx', label='RANSAC data' )
pylab.plot(A_noisy[:, 0], B_noisy[:, 0], 'k.', label='data')
pylab.plot(A_noisy[ransac_data['inliers'], 0], B_noisy[ransac_data['inliers'], 0], 'bx', label='RANSAC data')
else:
pylab.plot( A_noisy[non_outlier_idxs,0], B_noisy[non_outlier_idxs,0], 'k.', label='noisy data' )
pylab.plot( A_noisy[outlier_idxs,0], B_noisy[outlier_idxs,0], 'r.', label='outlier data' )
pylab.plot( A_col0_sorted[:,0],
numpy.dot(A_col0_sorted,ransac_fit)[:,0],
label='RANSAC fit' )
pylab.plot( A_col0_sorted[:,0],
numpy.dot(A_col0_sorted,perfect_fit)[:,0],
label='exact system' )
pylab.plot( A_col0_sorted[:,0],
numpy.dot(A_col0_sorted,linear_fit)[:,0],
label='linear fit' )
pylab.plot(A_noisy[non_outlier_idxs, 0], B_noisy[non_outlier_idxs, 0], 'k.', label='noisy data')
pylab.plot(A_noisy[outlier_idxs, 0], B_noisy[outlier_idxs, 0], 'r.', label='outlier data')
pylab.plot(A_col0_sorted[:, 0],
numpy.dot(A_col0_sorted, ransac_fit)[:, 0],
label='RANSAC fit')
pylab.plot(A_col0_sorted[:, 0],
numpy.dot(A_col0_sorted, perfect_fit)[:, 0],
label='exact system')
pylab.plot(A_col0_sorted[:, 0],
numpy.dot(A_col0_sorted, linear_fit)[:, 0],
label='linear fit')
pylab.legend()
pylab.show()

if __name__=='__main__':

if __name__ == '__main__':
test()

15 changes: 7 additions & 8 deletions pcv_book/sift.py
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
from pylab import *


def process_image(imagename,resultname,params="--edge-thresh 10 --peak-thresh 5"):
def process_image(imagename, resultname, params="--edge-thresh 10 --peak-thresh 5"):
""" Process an image and save the results in a file. """

if imagename[-3:] != 'pgm':
@@ -13,22 +13,21 @@ def process_image(imagename,resultname,params="--edge-thresh 10 --peak-thresh 5"
im.save('tmp.pgm')
imagename = 'tmp.pgm'

cmmd = str("sift "+imagename+" --output="+resultname+
" "+params)
cmmd = str("sift " + imagename + " --output=" + resultname + " " + params)
os.system(cmmd)
print 'processed', imagename, 'to', resultname
print('processed', imagename, 'to', resultname)


def read_features_from_file(filename):
""" Read feature properties and return in matrix form. """

f = loadtxt(filename)
return f[:,:4],f[:,4:] # feature locations, descriptors
return f[:, :4], f[:, 4:] # feature locations, descriptors


def write_features_to_file(filename,locs,desc):
def write_features_to_file(filename, locs, desc):
""" Save feature location and descriptor to file. """
savetxt(filename,hstack((locs,desc)))
savetxt(filename, hstack((locs, desc)))


def plot_features(im,locs,circle=False):
4 changes: 2 additions & 2 deletions pcv_book/warp.py
Original file line number Diff line number Diff line change
@@ -110,7 +110,7 @@ def transf(p):
return (p2[0]/p2[2],p2[1]/p2[2])

if H[1,2]<0: # fromim is to the right
print 'warp - right'
print('warp - right')
# transform fromim
if is_color:
# pad the destination image with zeros to the right
@@ -125,7 +125,7 @@ def transf(p):
fromim_t = ndimage.geometric_transform(fromim,transf,
(toim.shape[0],toim.shape[1]+padding))
else:
print 'warp - left'
print('warp - left')
# add translation to compensate for padding to the left
H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]])
H = dot(H,H_delta)