這是一個使用resnet50 的簡單例子。 其中 th.jpeg 是需要識别的圖像,一隻滑鼠:

import numpy as np
from keras.preprocessing import image
from keras.applications import resnet50
# Load Keras' resNet50 model that was pre-trained
# against the ImageNet database
model = resnet50.ResNet50()
# Load the image file, resizing it to 224x224 pixels(required by this model)
img = image.load_img("th.jpeg", target_size=(224,224))
# Convert the image to a numpy array
x = image.img_to_array(img)
# Add a forth dimension since Keras expects a list of images
x = np.expand_dims(x, axis=0)
# scale the input image to the range used in the trained network
x = resnet50.preprocess_input(x)
# Run the image through the deep neural network to make a prediction
predictions = model.predict(x)
# Look up the names of the predicted classed. Index
# zero is the results for the first image
predicted_classes = resnet50.decode_predictions(predictions, top=9)
print("This is an image of:")
for imagenet_id, name, likelihood in predicted_classes[0]:
print(" - {}: {:2f} likelihood".format(name, likelihood))
最後列印圖像的類别,并給出了可能性。圖像為滑鼠的可能性最高, 為82%,為遊戲杆的可能性為3%, 其餘的可能性都很小 ?
This is an image of:
- mouse: 0.827389 likelihood
- joystick: 0.032186 likelihood
- iron: 0.014061 likelihood
- clog: 0.012318 likelihood
- radio: 0.007359 likelihood
- can_opener: 0.005806 likelihood
- remote_control: 0.005791 likelihood
- ladle: 0.005054 likelihood
- vase: 0.004762 likelihood