I hope everyone is doing great today <3.
But if you have hard times don't give up we believe in you.
Anyways, I'm kinda new to ML/DL.
The problem is that I m trying to make a script that takes an image and re-use this model to analyze it and prints the predictions.
https://tfhub.dev/google/aiy/vision/classifier/food_V1/1
Can someone help me by providing some resources or a script to solve my problem?
I'll so grateful this may save my life and thanks for your time.
CodePudding user response:
This should work in TF2:
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
import numpy as np
import pandas as pd
import cv2
from skimage import io
cake_url = "https://storage.googleapis.com/tfhub-visualizers/google/aiy/vision/classifier/food_V1/1/image_1.jpg"
labelmap_url = "https://www.gstatic.com/aihub/tfhub/labelmaps/aiy_food_V1_labelmap.csv"
input_shape = (224, 224)
m = hub.KerasLayer("https://tfhub.dev/google/aiy/vision/classifier/food_V1/1")
image = np.asarray(io.imread(cake_url), dtype="float")
image = cv2.resize(image, dsize=input_shape, interpolation=cv2.INTER_CUBIC)
# Scale values to [0, 1].
image = image / image.max()
# The model expects an input of (?, 224, 224, 3).
images = np.expand_dims(image, 0)
output = m(images)
predicted_index = output.numpy().argmax()
classes = list(pd.read_csv(labelmap_url)["name"])
print("Prediction: ", classes[predicted_index])
CodePudding user response:
**Thanks i added some touch to it it now shows the first 6 class with % **
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
import numpy as np
import pandas as pd
import cv2
from skimage import io
def predict_image(image_path="a_img_url"): #local path works too
labelmap_url = "https://www.gstatic.com/aihub/tfhub/labelmaps/aiy_food_V1_labelmap.csv"
input_shape = (224, 224)
m = hub.KerasLayer(
"https://tfhub.dev/google/aiy/vision/classifier/food_V1/1")
image = np.asarray(io.imread(image_path), dtype="float")
image = cv2.resize(image, dsize=input_shape, interpolation=cv2.INTER_CUBIC)
# Scale values to [0, 1].
image = image / image.max()
# The model expects an input of (?, 224, 224, 3).
images = np.expand_dims(image, 0)
output = m(images)
results = np.squeeze(output)
# return the 6 prections
top_k = results.argsort()[-6:][::-1]
lables = list(pd.read_csv(labelmap_url)["name"])
names = [lables[i] for i in top_k]
# get thier percentages
percentages = [results[i] for i in top_k]
return names, percentages
if __name__ == "__main__":
import time
start_time = time.time()
predict_image()
print("--- %s seconds ---" % (time.time() - start_time) )