Skip to content

Instantly share code, notes, and snippets.

View frogermcs's full-sized avatar
🤓
Did you do good today?

Mirosław Stanek frogermcs

🤓
Did you do good today?
View GitHub Profile
LABELS_FILE = 'ImageNetLabels.txt'
with open(LABELS_FILE) as f:
labels = f.read().splitlines()
Prediction for Golden Retriever: golden retriever 0.5627079010009766
Prediction for laptop: laptop 0.42153415083885193
INPUT_TENSOR = "input__0"
OUTPUT_TENSOR = "MobilenetV2__Predictions__Reshape_1__0"
PREDICTED_FEATURE_NAME = "classLabel"
# Prediction is run on CPU
coreml_output_golden = mlmodel.predict({INPUT_TENSOR: img_golden}, useCPUOnly=True)
#Prediction is run on GPU
coreml_output_laptop = mlmodel.predict({INPUT_TENSOR: img_laptop}, useCPUOnly=False)
img_golden = img_golden.resize([224,224], PIL.Image.ANTIALIAS)
img_laptop = img_laptop.resize([224,224], PIL.Image.ANTIALIAS)
# Load previously saved CoreML model of MobileNet v2
mlmodel = coremltools.models.MLModel('mobilenet_v2_1.0_224.mlmodel')
# Get spec from the model
spec = mlmodel.get_spec()
print(spec.description)
# Output
# >> input {
# >> name: "input__0"
img_laptop_url = "https://upload.wikimedia.org/wikipedia/commons/9/90/ThinkPad_X220.jpg"
img_laptop = PIL.Image.open(BytesIO(requests.get(img_laptop_url).content))
imshow(np.asarray(img_laptop))
img_golden_url = "https://upload.wikimedia.org/wikipedia/commons/9/93/Golden_Retriever_Carlos_%2810581910556%29.jpg"
img_golden = PIL.Image.open(BytesIO(requests.get(img_golden_url).content))
imshow(np.asarray(img_golden))
%matplotlib inline #will be useful for images preview
from matplotlib.pyplot import imshow
import tensorflow as tf
import coremltools
#For easier images processing
import numpy as np
import PIL
import requests
Core ML model generated. Saved at location: mobilenet_v2_1.0_224.mlmodel
Core ML input(s):
[name: "input__0"
type {
imageType {
width: 224
height: 224
colorSpace: RGB
}
# Convert TensorFlow model to Core ML format
# Input model definition
IMAGE_INPUT_NAME = ["input:0"]
IMAGE_INPUT_NAME_SHAPE = {'input:0':[1,224,224,3]}
IMAGE_INPUT_SCALE = 1.0/255.0
OUTPUT_NAME = ['MobilenetV2/Predictions/Reshape_1:0']
MODEL_LABELS = 'ImageNetLabels.txt'
# Output model
!cat mobilenet_v2_1.0_224_info.txt
# Output
# >> Model: mobilenet_v2_1.0_224
# >> Input: input
# >> Output: MobilenetV2/Predictions/Reshape_1