|
| 1 | +# This code is supporting material for the book |
| 2 | +# Building Machine Learning Systems with Python |
| 3 | +# by Willi Richert and Luis Pedro Coelho |
| 4 | +# published by PACKT Publishing |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import mahotas as mh |
| 8 | +from glob import glob |
| 9 | +from features import texture, color_histogram |
| 10 | +from matplotlib import pyplot as plt |
| 11 | +from sklearn.preprocessing import StandardScaler |
| 12 | +from scipy.spatial import distance |
| 13 | + |
| 14 | +basedir = '../SimpleImageDataset/' |
| 15 | + |
| 16 | + |
| 17 | +haralicks = [] |
| 18 | +chists = [] |
| 19 | + |
| 20 | +print('Computing features...') |
| 21 | +# Use glob to get all the images |
| 22 | +images = glob('{}/*.jpg'.format(basedir)) |
| 23 | +# We sort the images to ensure that they are always processed in the same order |
| 24 | +# Otherwise, this would introduce some variation just based on the random |
| 25 | +# ordering that the filesystem uses |
| 26 | +images.sort() |
| 27 | + |
| 28 | +for fname in images: |
| 29 | + imc = mh.imread(fname) |
| 30 | + imc = imc[200:-200,200:-200] |
| 31 | + haralicks.append(texture(mh.colors.rgb2grey(imc))) |
| 32 | + chists.append(color_histogram(imc)) |
| 33 | + |
| 34 | +haralicks = np.array(haralicks) |
| 35 | +chists = np.array(chists) |
| 36 | +features = np.hstack([chists, haralicks]) |
| 37 | + |
| 38 | +print('Computing neighbors...') |
| 39 | +sc = StandardScaler() |
| 40 | +dists = distance.squareform(distance.pdist(features)) |
| 41 | + |
| 42 | +print('Plotting...') |
| 43 | +fig, axes = plt.subplots(2, 9, figsize=(16,8)) |
| 44 | + |
| 45 | +# Remove ticks from all subplots |
| 46 | +for ax in axes.flat: |
| 47 | + ax.set_xticks([]) |
| 48 | + ax.set_yticks([]) |
| 49 | + |
| 50 | +for ci,i in enumerate(range(0,90,10)): |
| 51 | + left = images[i] |
| 52 | + dists_left = dists[i] |
| 53 | + right = dists_left.argsort() |
| 54 | + right = right[1] |
| 55 | + right = images[right] |
| 56 | + left = mh.imread(left) |
| 57 | + right = mh.imread(right) |
| 58 | + axes[0, ci].imshow(left) |
| 59 | + axes[1, ci].imshow(right) |
| 60 | + |
| 61 | +fig.tight_layout() |
| 62 | +fig.savefig('figure_neighbors.png', dpi=300) |
0 commit comments