Skip to content

Commit 376d597

Browse files
committed
Examples for Chapter 8
1 parent 3e940bc commit 376d597

7 files changed

+381
-0
lines changed

examples/ch8_bayes_points.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from pylab import *
2+
from numpy import *
3+
import pickle
4+
5+
from PCV.classifiers import bayes
6+
from PCV.tools import imtools
7+
8+
"""
9+
This is the simple 2D classification example in Section 8.2
10+
using Bayes classifier.
11+
12+
If you have created the data files, it will reproduce the plot
13+
in Figure 8-4.
14+
"""
15+
16+
17+
# load 2D points using Pickle
18+
with open('../data/points_normal.pkl', 'r') as f:
19+
class_1 = pickle.load(f)
20+
class_2 = pickle.load(f)
21+
labels = pickle.load(f)
22+
23+
# train Bayes classifier
24+
bc = bayes.BayesClassifier()
25+
bc.train([class_1,class_2], [1,-1])
26+
27+
# load test data using Pickle
28+
with open('../data/points_normal_test.pkl', 'r') as f:
29+
class_1 = pickle.load(f)
30+
class_2 = pickle.load(f)
31+
labels = pickle.load(f)
32+
33+
# test on the 10 first points
34+
print bc.classify(class_1[:10])[0]
35+
36+
# define function for plotting
37+
def classify(x, y, bc=bc):
38+
points = vstack((x,y))
39+
return bc.classify(points.T)[0]
40+
41+
# plot the classification boundary
42+
imtools.plot_2D_boundary([-6,6,-6,6], [class_1,class_2], classify, [1,-1])
43+
show()

examples/ch8_dsift.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from PIL import Imagefrom pylab import *from numpy import *from PCV.localdescriptors import dsift, sift"""This is the dense SIFT illustration, it will reproduce the plotin Figure 8-2."""dsift.process_image_dsift('../data/empire.jpg', 'empire.sift', 90, 40, True)l,d = sift.read_features_from_file('empire.sift')im = array(Image.open('../data/empire.jpg'))sift.plot_features(im, l, True)show()

examples/ch8_generate_dataset.py

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from numpy import *
2+
from numpy.random import randn
3+
import pickle
4+
5+
"""
6+
This generates the 2D point data sets used in chapter 8.
7+
8+
(both training and test)
9+
"""
10+
11+
###
12+
# Training data
13+
###
14+
15+
# create sample data of 2D points
16+
n = 200
17+
18+
# two normal distributions
19+
class_1 = 0.6 * randn(n,2)
20+
class_2 = 1.2 * randn(n,2) + array([5,1])
21+
labels = hstack((ones(n),-ones(n)))
22+
23+
# save with Pickle
24+
with open('../data/points_normal.pkl', 'w') as f:
25+
pickle.dump(class_1,f)
26+
pickle.dump(class_2,f)
27+
pickle.dump(labels,f)
28+
29+
# normal distribution and ring around it
30+
class_1 = 0.6 * randn(n,2)
31+
r = 0.8 * randn(n,1) + 5
32+
angle = 2*pi * randn(n,1)
33+
class_2 = hstack((r*cos(angle),r*sin(angle)))
34+
labels = hstack((ones(n),-ones(n)))
35+
36+
# save with Pickle
37+
with open('../data/points_ring.pkl', 'w') as f:
38+
pickle.dump(class_1,f)
39+
pickle.dump(class_2,f)
40+
pickle.dump(labels,f)
41+
42+
43+
###
44+
# Test data
45+
###
46+
47+
# create sample data of 2D points
48+
n = 200
49+
50+
# two normal distributions
51+
class_1 = 0.6 * randn(n,2)
52+
class_2 = 1.2 * randn(n,2) + array([5,1])
53+
labels = hstack((ones(n),-ones(n)))
54+
55+
# save with Pickle
56+
with open('../data/points_normal_test.pkl', 'w') as f:
57+
pickle.dump(class_1,f)
58+
pickle.dump(class_2,f)
59+
pickle.dump(labels,f)
60+
61+
# normal distribution and ring around it
62+
class_1 = 0.6 * randn(n,2)
63+
r = 0.8 * randn(n,1) + 5
64+
angle = 2*pi * randn(n,1)
65+
class_2 = hstack((r*cos(angle),r*sin(angle)))
66+
labels = hstack((ones(n),-ones(n)))
67+
68+
# save with Pickle
69+
with open('../data/points_ring_test.pkl', 'w') as f:
70+
pickle.dump(class_1,f)
71+
pickle.dump(class_2,f)
72+
pickle.dump(labels,f)

examples/ch8_gesture_recognition.py

+134
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
from PIL import Image
2+
from numpy import *
3+
from pylab import *
4+
5+
from svmutil import *
6+
import os
7+
8+
from PCV.classifiers import knn, bayes
9+
from PCV.tools import imtools
10+
from PCV.localdescriptors import dsift, sift
11+
12+
13+
"""
14+
This script collects the three classifiers applied to the hand gesture
15+
recognition test.
16+
17+
If you have created the data files with the dsift features, this will
18+
reproduce all confucion matrices in Chapter 8.
19+
20+
Use the if statements at the bottom to turn on/off different combinations.
21+
"""
22+
23+
24+
def read_gesture_features_labels(path):
25+
# create list of all files ending in .dsift
26+
featlist = [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.dsift')]
27+
28+
# read the features
29+
features = []
30+
for featfile in featlist:
31+
l,d = sift.read_features_from_file(featfile)
32+
features.append(d.flatten())
33+
features = array(features)
34+
35+
# create labels
36+
labels = [featfile.split('/')[-1][0] for featfile in featlist]
37+
38+
return features,array(labels)
39+
40+
41+
def convert_labels(labels,transl):
42+
""" Convert between strings and numbers. """
43+
return [transl[l] for l in labels]
44+
45+
46+
def print_confusion(res,labels,classnames):
47+
48+
n = len(classnames)
49+
50+
# confusion matrix
51+
class_ind = dict([(classnames[i],i) for i in range(n)])
52+
53+
confuse = zeros((n,n))
54+
for i in range(len(test_labels)):
55+
confuse[class_ind[res[i]],class_ind[test_labels[i]]] += 1
56+
57+
print 'Confusion matrix for'
58+
print classnames
59+
print confuse
60+
61+
62+
# read training data
63+
####################
64+
features,labels = read_gesture_features_labels('../data/hand_gesture/train/')
65+
print 'training data is:', features.shape, len(labels)
66+
67+
# read test data
68+
####################
69+
test_features,test_labels = read_gesture_features_labels('../data/hand_gesture/test/')
70+
print 'test data is:', test_features.shape, len(test_labels)
71+
72+
classnames = unique(labels)
73+
nbr_classes = len(classnames)
74+
75+
76+
if False:
77+
# reduce dimensions with PCA
78+
from PCV.tools import pca
79+
80+
V,S,m = pca.pca(features)
81+
82+
# keep most important dimensions
83+
V = V[:50]
84+
features = array([dot(V,f-m) for f in features])
85+
test_features = array([dot(V,f-m) for f in test_features])
86+
87+
88+
if True:
89+
# test kNN
90+
k = 1
91+
knn_classifier = knn.KnnClassifier(labels,features)
92+
res = array([knn_classifier.classify(test_features[i],k) for i in range(len(test_labels))]) # TODO kan goras battre
93+
94+
95+
if False:
96+
# test Bayes
97+
bc = bayes.BayesClassifier()
98+
blist = [features[where(labels==c)[0]] for c in classnames]
99+
100+
bc.train(blist,classnames)
101+
res = bc.classify(test_features)[0]
102+
103+
104+
if False:
105+
# test SVM
106+
# convert to lists for libsvm
107+
features = map(list,features)
108+
test_features = map(list,test_features)
109+
110+
# create conversion function for the labels
111+
transl = {}
112+
for i,c in enumerate(classnames):
113+
transl[c],transl[i] = i,c
114+
115+
# create SVM
116+
prob = svm_problem(convert_labels(labels,transl),features)
117+
param = svm_parameter('-t 0')
118+
119+
# train SVM on data
120+
m = svm_train(prob,param)
121+
122+
# how did the training do?
123+
res = svm_predict(convert_labels(labels,transl),features,m)
124+
125+
# test the SVM
126+
res = svm_predict(convert_labels(test_labels,transl),test_features,m)[0]
127+
res = convert_labels(res,transl)
128+
129+
130+
# accuracy
131+
acc = sum(1.0*(res==test_labels)) / len(test_labels)
132+
print 'Accuracy:', acc
133+
134+
print_confusion(res,test_labels,classnames)

examples/ch8_knn_points.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from pylab import *
2+
from numpy import *
3+
import pickle
4+
5+
from PCV.classifiers import knn
6+
from PCV.tools import imtools
7+
8+
"""
9+
This is the simple 2D classification example in Section 8.1.
10+
11+
If you have created the data files, it will reproduce the plot
12+
in Figure 8-1.
13+
"""
14+
15+
16+
# load 2D points using Pickle
17+
with open('../data/points_normal.pkl', 'r') as f:
18+
class_1 = pickle.load(f)
19+
class_2 = pickle.load(f)
20+
labels = pickle.load(f)
21+
22+
model = knn.KnnClassifier(labels,vstack((class_1,class_2)))
23+
24+
# load test data using Pickle
25+
with open('../data/points_normal_test.pkl', 'r') as f:
26+
class_1 = pickle.load(f)
27+
class_2 = pickle.load(f)
28+
labels = pickle.load(f)
29+
30+
# test on the first point
31+
print model.classify(class_1[0])
32+
33+
# define function for plotting
34+
def classify(x, y, model=model):
35+
return array([model.classify([xx,yy]) for (xx,yy) in zip(x,y)])
36+
37+
# plot the classification boundary
38+
imtools.plot_2D_boundary([-6,6,-6,6], [class_1,class_2], classify, [1,-1])
39+
show()

examples/ch8_process_handgestures.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from PIL import Image
2+
from pylab import *
3+
from numpy import *
4+
import os
5+
6+
from PCV.localdescriptors import dsift, sift
7+
from PCV.tools import imtools
8+
9+
"""
10+
This will process all hand gesture images with the dense SIFT descriptor.
11+
12+
Assumes you downloaded the hand images to ..data/hand_gesture.
13+
The plot at the end generates one of the images of Figure 8-3.
14+
"""
15+
16+
path = '../data/hand_gesture/train/'
17+
imlist = []
18+
for filename in os.listdir(path):
19+
if os.path.splitext(filename)[1] == '.ppm':
20+
imlist.append(path+filename)
21+
22+
23+
# process images at fixed size (50,50)
24+
for filename in imlist:
25+
featfile = filename[:-3]+'dsift'
26+
dsift.process_image_dsift(filename, featfile, 10, 5, resize=(50,50))
27+
28+
29+
# show an image with features
30+
l,d = sift.read_features_from_file(featfile)
31+
im = array(Image.open(filename).resize((50,50)))
32+
print im.shape
33+
34+
figure()
35+
sift.plot_features(im, l, True)
36+
show()

examples/ch8_svm_points.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from pylab import *
2+
from numpy import *
3+
from svmutil import *
4+
import pickle
5+
6+
from PCV.tools import imtools
7+
8+
"""
9+
This is the simple 2D classification example in Section 8.2
10+
using a SVM classifier.
11+
12+
If you have created the data files, it will reproduce the plot
13+
in Figure 8-5.
14+
"""
15+
16+
17+
# load 2D points using Pickle
18+
with open('../data/points_normal.pkl', 'r') as f:
19+
class_1 = pickle.load(f)
20+
class_2 = pickle.load(f)
21+
labels = pickle.load(f)
22+
23+
# convert to lists for libsvm
24+
class_1 = map(list, class_1)
25+
class_2 = map(list, class_2)
26+
labels = list(labels)
27+
samples = class_1+class_2 # concatenate the two lists
28+
29+
# create SVM
30+
prob = svm_problem(labels, samples)
31+
param = svm_parameter('-t 2')
32+
# train SVM on data
33+
m = svm_train(prob, param)
34+
35+
# how did the training do?
36+
res = svm_predict(labels, samples, m)
37+
38+
39+
# load test data using Pickle
40+
with open('../data/points_normal_test.pkl', 'r') as f:
41+
class_1 = pickle.load(f)
42+
class_2 = pickle.load(f)
43+
labels = pickle.load(f)
44+
45+
# convert to lists for libsvm
46+
class_1 = map(list, class_1)
47+
class_2 = map(list, class_2)
48+
49+
50+
# define function for plotting
51+
def predict(x, y, model=m):
52+
return array(svm_predict([0]*len(x), map(list, zip(x,y)), model)[0])
53+
54+
# plot the classification boundary
55+
imtools.plot_2D_boundary([-6,6,-6,6], [array(class_1),array(class_2)], predict, [-1,1])
56+
show()

0 commit comments

Comments
 (0)