https://qiita.com/uz29/items/ec854106355bf783e316 Since the preparation was completed last time, I first made an image discrimination program using the existing learning model VGG16.
The model will be downloaded for the first time.
import glob
import pprint
import numpy as np
import tensorflow as tf
from PIL import Image
model = tf.keras.applications.vgg16.VGG16(weights='imagenet')
I wanted to make predictions for all the images in the folder, so I used glob to get a list of paths and create an array of each image. Prediction seems to be able to process multiple images at the same time with a single function call.
#Predict all photos in a folder
file_list = glob.glob("./images/*")
pil = []
imgs = []
for path in file_list:
#Image loading
img_pil = tf.keras.preprocessing.image.load_img(path, target_size=(224, 224))
pil.append(img_pil)
#Convert images to arrays
img = tf.keras.preprocessing.image.img_to_array(img_pil)
#Convert to a 4-dimensional array
imgs.append(img)
imgs = np.stack(imgs, 0)
#Preprocessing
img_p = tf.keras.applications.vgg16.preprocess_input(imgs)
#Forecast
predict = model.predict(img_p)
result = tf.keras.applications.vgg16.decode_predictions(predict, top=5)
The prediction results can be seen below.
pprint.pprint(result[0])
plt.imshow(pil[0])
[('n02124075', 'Egyptian_cat', 0.42277277), ('n02123159', 'tiger_cat', 0.18187998), ('n02123045', 'tabby', 0.12070633), ('n02883205', 'bow_tie', 0.0892005), ('n02127052', 'lynx', 0.024664408)]
pprint.pprint(result[1])
plt.imshow(pil[1])
[('n02119789', 'kit_fox', 0.6857688), ('n02119022', 'red_fox', 0.24295172), ('n02120505', 'grey_fox', 0.065218925), ('n02114855', 'coyote', 0.004371826), ('n02115913', 'dhole', 0.00046840237)]
pprint.pprint(result[2])
plt.imshow(pil[2])
[('n02138441', 'meerkat', 0.9073721), ('n02137549', 'mongoose', 0.092063464), ('n02447366', 'badger', 0.00037895824), ('n02361337', 'marmot', 8.514335e-05), ('n02441942', 'weasel', 2.4436611e-05)]
The subtle species of animals are not included in VGG16 and may differ, but they generally return the exact species. In the future, I would like to make my own learning model and make predictions.
Recommended Posts