Created
July 7, 2021 05:41
-
-
Save karlschriek/07030528a232d7c145556e1fd0fa3442 to your computer and use it in GitHub Desktop.
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
import argparse | |
import matplotlib.pyplot as plt | |
from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions | |
import numpy as np | |
import requests | |
import json | |
import os | |
from PIL import Image | |
import ssl | |
ssl._create_default_https_context = ssl._create_unverified_context | |
def get_image_data(image_path): | |
data = [] | |
image_shape = (299, 299, 3) | |
target_size = image_shape[:2] | |
image = Image.open(image_path).convert('RGB') | |
image = np.expand_dims(image.resize(target_size), axis=0) | |
data.append(image) | |
data = np.concatenate(data, axis=0) | |
return data | |
def predict(url, headers, cookies, image_path): | |
data = get_image_data(image_path) | |
images = preprocess_input(data) | |
payload = { | |
"instances": [images[0].tolist()] | |
} | |
# sending post request to TensorFlow Serving server | |
print("Calling ", url) | |
r = requests.post(url, json=payload, headers=headers, cookies=cookies) | |
resp_json = json.loads(r.content.decode('utf-8')) | |
preds = np.array(resp_json["predictions"]) | |
label = decode_predictions(preds, top=1) | |
plt.imshow(data[0]) | |
plt.title(label[0]) | |
plt.show() | |
def explain(url, headers, cookies, image_path): | |
data = get_image_data(image_path) | |
images = preprocess_input(data) | |
payload = { | |
"instances": [images[0].tolist()] | |
} | |
# sending post request to TensorFlow Serving server | |
print("Calling ", url) | |
r = requests.post(url, json=payload, headers=headers, cookies=cookies) | |
if r.status_code == 200: | |
explanation = json.loads(r.content.decode('utf-8')) | |
f, axarr = plt.subplots(1, 2) | |
axarr[0].imshow(data[0]) | |
axarr[1].imshow(explanation['data']['anchor']) | |
plt.show() | |
else: | |
print("Received response code and content", r.status_code, r.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment