-
Notifications
You must be signed in to change notification settings - Fork 0
/
use_keras_pretrained_models.py
88 lines (70 loc) · 2.62 KB
/
use_keras_pretrained_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
## using Keras pretrained models
import keras
import numpy as np
from keras.applications import vgg16, inception_v3, resnet50, mobilenet
def load_model(model_name):
if model_name == 'vgg':
#Load the VGG model
model = vgg16.VGG16(weights='imagenet')
#Load the Inception_V3 model
#inception_model = inception_v3.InceptionV3(weights='imagenet')
#Load the ResNet50 model
if model_name == 'resnet50':
model = resnet50.ResNet50(weights='imagenet')
#Load the MobileNet model
if model_name == 'mobilenet':
mobilenet_model = mobilenet.MobileNet(weights='imagenet')
return model
#%%
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import decode_predictions
import matplotlib.pyplot as plt
#matplotlib inline
filename = 'D:/AG/Keras/Lamborghini.jpg'
# load an image in PIL format
original = load_img(filename, target_size=(224, 224))
print('PIL image size',original.size)
plt.imshow(original)
plt.show()
# convert the PIL image to a numpy array
# IN PIL - image is in (width, height, channel)
# In Numpy - image is in (height, width, channel)
numpy_image = img_to_array(original)
plt.imshow(np.uint8(numpy_image))
plt.show()
print('numpy array size',numpy_image.shape)
# Convert the image into batch format
image_batch = np.expand_dims(numpy_image, axis=0)
print('image batch size', image_batch.shape)
plt.imshow(np.uint8(image_batch[0]))
#%%
# prepare the image for the VGG model
processed_image = vgg16.preprocess_input(image_batch.copy())
# get the predicted probabilities for each class
predictions = vgg_model.predict(processed_image)
#print(predictions)
# convert the probabilities to class labels
# We will get top 5 predictions which is the default
label = decode_predictions(predictions)
print(label)
#%%
# prepare the image for the Resnet model
processed_image = resnet50.preprocess_input(image_batch.copy())
# get the predicted probabilities for each class
predictions = resnet_model.predict(processed_image)
#print(predictions)
# convert the probabilities to class labels
# We will get top 5 predictions which is the default
label = decode_predictions(predictions)
print(label)
#%%
# prepare the image for the Resnet model
processed_image = mobilenet.preprocess_input(image_batch.copy())
# get the predicted probabilities for each class
predictions = mobilenet_model.predict(processed_image)
#print(predictions)
# convert the probabilities to class labels
# We will get top 5 predictions which is the default
label = decode_predictions(predictions)
print(label)