# -*- coding: utf-8 -*- """ Created on Fri Sep 11 13:12:03 2015 @author: Camil Staps, s4498062 Use Python 2.* """ # exercise 3.2.1 from __future__ import print_function from pylab import * from scipy.io import loadmat from similarity import similarity # Image to use as query i = 635 # Similarity: 'SMC', 'Jaccard', 'ExtendedJaccard', 'Cosine', 'Correlation' similarity_measure = 'jaccard' # Load the CBCL face database # Load Matlab data file to python dict structure X = loadmat('./Data/wildfaces_grayscale.mat')['X'] N, M = shape(X) # Search the face database for similar faces # Index of all other images than i noti = range(0,i) + range(i+1,N) # Compute similarity between image i and all others sim = similarity(X[i,:], X[noti,:], similarity_measure) sim = sim.tolist()[0] # Tuples of sorted similarities and their indices sim_to_index = sorted(zip(sim,noti)) # Visualize query image and 5 most/least similar images figure(figsize=(12,8)) subplot(3,1,1) imshow(np.reshape(X[i],(40,40)).T, cmap=cm.gray) xticks([]); yticks([]) title('Query image') ylabel('image #{0}'.format(i)) for ms in range(5): # 5 most similar images found subplot(3,5,6+ms) im_id = sim_to_index[-ms-1][1] im_sim = sim_to_index[-ms-1][0] imshow(np.reshape(X[im_id],(40,40)).T, cmap=cm.gray) xlabel('sim={0:.3f}'.format(im_sim)) ylabel('image #{0}'.format(im_id)) xticks([]); yticks([]) if ms==2: title('Most similar images') # 5 least similar images found subplot(3,5,11+ms) im_id = sim_to_index[ms][1] im_sim = sim_to_index[ms][0] imshow(np.reshape(X[im_id],(40,40)).T, cmap=cm.gray) xlabel('sim={0:.3f}'.format(im_sim)) ylabel('image #{0}'.format(im_id)) xticks([]); yticks([]) if ms==2: title('Least similar images') show() # 1.3.1 # For any two similarity measures, the five least similar are quite different. # Based on the five most similar images, SMC and Jaccard produce similar # results. Correlation and Cosine produce some similar results. # Using image 2 it is clear that SMC and ExtendedJaccard are sensitive to # lighting conditions, and thus maybe not a very good choice to compare faces. # Also Correlation seems a little sensitive to this. Lastly Cosine seems to # recognise faces somewhat better than Jaccard (take e.g. #635). # 1.3.2 measures = {'Cosine': 'cos', 'ExtJac': 'ext', 'Correl': 'cor'} scalar = 0.5 # Note: pick from (0,1), values > 1 aren't handled nicely translation = 0.1 # Note: pick a small value, for similar reasons # Round list to resist numerical variances (hint #2) X = np.around(X, decimals = 4) for name, measure in measures.iteritems(): sim1 = similarity(scalar * X[i,:], X[noti,:], measure) sim2 = similarity(X[i,:], X[noti,:], measure) print("Scalar,", name, ":", (sim1 == sim2).all()) for name, measure in measures.iteritems(): sim1 = similarity(translation + X[i,:], X[noti,:], measure) sim2 = similarity(X[i,:], X[noti,:], measure) print("Translation,", name, ":", (sim1 == sim2).any())