Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from keras.models import load_model
|
| 2 |
+
from PIL import Image, ImageOps
|
| 3 |
+
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
# Load the model
|
| 7 |
+
classify_model = load_model('keras_model.h5')
|
| 8 |
+
|
| 9 |
+
def format_label(label):
|
| 10 |
+
"""
|
| 11 |
+
From '0 class 1\n' to 'class 1'
|
| 12 |
+
"""
|
| 13 |
+
return label[:-1]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def classify(image):
|
| 17 |
+
# Create the array of the right shape to feed into the keras model
|
| 18 |
+
# The 'length' or number of images you can put into the array is
|
| 19 |
+
# determined by the first position in the shape tuple, in this case 1.
|
| 20 |
+
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
|
| 21 |
+
|
| 22 |
+
#resize the image to a 224x224 with the same strategy as in TM2:
|
| 23 |
+
#resizing the image to be at least 224x224 and then cropping from the center
|
| 24 |
+
size = (224, 224)
|
| 25 |
+
image = ImageOps.fit(image, size, Image.ANTIALIAS)
|
| 26 |
+
|
| 27 |
+
#turn the image into a numpy array
|
| 28 |
+
image_array = np.asarray(image)
|
| 29 |
+
# Normalize the image
|
| 30 |
+
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
|
| 31 |
+
# Load the image into the array
|
| 32 |
+
data[0] = normalized_image_array
|
| 33 |
+
|
| 34 |
+
# run the inference
|
| 35 |
+
pred = classify_model.predict(data)
|
| 36 |
+
pred = pred.tolist()
|
| 37 |
+
|
| 38 |
+
with open('labels.txt','r') as f:
|
| 39 |
+
labels = f.readlines()
|
| 40 |
+
|
| 41 |
+
result = {format_label(labels[i]): round(pred[0][i],2) for i in range(len(pred[0]))}
|
| 42 |
+
sorted_result = {k: v for k, v in sorted(result.items(), key=lambda item: item[1], reverse=True) if v > 0}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
return sorted_result
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
title = "🐢"
|
| 49 |
+
|
| 50 |
+
gr.Interface(
|
| 51 |
+
fn=classify,
|
| 52 |
+
inputs=gr.Image(type="pil", label="Input Image"),
|
| 53 |
+
outputs=[gr.JSON()],
|
| 54 |
+
title=title,
|
| 55 |
+
).launch()
|