Last active
September 4, 2020 08:38
-
-
Save ozgurshn/85cf74558d82c831827e12f015f752a1 to your computer and use it in GitHub Desktop.
Prediction on Core ML model with PIL image input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##https://github.com/apple/coremltools/blob/master/examples/APIExamples.md | |
import coremltools | |
import numpy as np | |
import PIL.Image | |
# load a model whose input type is "Image" | |
model = coremltools.models.MLModel('path/to/the/saved/model.mlmodel') | |
Height = 20 # use the correct input image height | |
Width = 60 # use the correct input image width | |
# Scenario 1: load an image from disk | |
def load_image(path, resize_to=None): | |
# resize_to: (Width, Height) | |
img = PIL.Image.open(path) | |
if resize_to is not None: | |
img = img.resize(resize_to, PIL.Image.ANTIALIAS) | |
img_np = np.array(img).astype(np.float32) | |
return img_np, img | |
# load the image and resize using PIL utilities | |
_, img = load_image('/path/to/image.jpg', resize_to=(Width, Height)) | |
out_dict = model.predict({'image': img}) | |
# Scenario 2: load an image from a numpy array | |
shape = (Height, Width, 3) # height x width x RGB | |
data = np.zeros(shape, dtype=np.uint8) | |
# manipulate numpy data | |
pil_img = PIL.Image.fromarray(data) | |
out_dict = model.predict({'image': pil_img}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment