dst.argmin()
will tell you the index of the element in dst
which is smallest.
So the closest image would be
idx = dst.argmin()
closest = a[idx]
since a
is a list of arrays representing training faces.
To display the closest image, you could use:
img = Image.fromarray(closest, 'L')
img.show()
To find the file path of the closest image, I would alter read_images
to return a list of all the file paths, so it could be indexed just like the list of images.
def read_images(path, sz=None):
X, y = [], []
for dirname, dirnames, filenames in os.walk(path):
for filename in filenames:
subject_path = os.path.join(dirname, filename)
try:
im = Image.open(subject_path)
except IOError as err:
print "I/O error: {e}: {f}".format(e=err, f=subject_path)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
else:
im = im.convert("L")
# resize to given size (if given)
if (sz is not None):
im = im.resize(sz, Image.ANTIALIAS)
X.append(np.asarray(im, dtype=np.uint8))
y.append(subject_path)
return [X, y]
Below, call it like this:
images, paths = read_images(TRAINING_DIR, (90, 90))
You can then obtain the full path to the closest image with
idx = dst.argmin()
filename = paths[idx]
If you want just the path to the subdirectory, use
os.path.dirname(filename)
And for the name of the subdirectory, use
os.path.basename(os.path.dirname(filename))