|
|
import numpy as np |
|
|
from tensorflow.keras.applications.resnet50 import ( |
|
|
ResNet50, |
|
|
decode_predictions, |
|
|
preprocess_input, |
|
|
) |
|
|
from tensorflow.keras.preprocessing import image |
|
|
|
|
|
|
|
|
model = ResNet50(include_top=True, weights="imagenet") |
|
|
|
|
|
|
|
|
def predict_image(img): |
|
|
""" |
|
|
Preprocesses an image and runs a pre-trained ResNet50 model to get a prediction. |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
img : PIL.Image |
|
|
The image object to classify. |
|
|
|
|
|
Returns |
|
|
------- |
|
|
class_name, pred_probability : tuple(str, float) |
|
|
The model's predicted class as a string and the corresponding confidence |
|
|
score as a number. |
|
|
""" |
|
|
|
|
|
img = img.resize((224, 224)) |
|
|
|
|
|
|
|
|
x = image.img_to_array(img) |
|
|
|
|
|
|
|
|
x_batch = np.expand_dims(x, axis=0) |
|
|
|
|
|
|
|
|
x_batch = preprocess_input(x_batch) |
|
|
|
|
|
|
|
|
predictions = model.predict(x_batch, verbose=0) |
|
|
|
|
|
|
|
|
top_pred = decode_predictions(predictions, top=1)[0][0] |
|
|
_, class_name, pred_probability = top_pred |
|
|
|
|
|
|
|
|
pred_probability = round(float(pred_probability), 4) |
|
|
|
|
|
return class_name, pred_probability |
|
|
|