Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -10,23 +10,23 @@ model = tf.keras.models.load_model("denis_mnist_cnn_model.h5")
|
|
10 |
def preprocess_image(image):
|
11 |
# Convert PIL image to a tensor
|
12 |
image = tf.convert_to_tensor(image)
|
13 |
-
|
14 |
-
# Check if the image has a single channel (grayscale) and reshape if needed
|
15 |
-
if image.shape[-1] != 1:
|
16 |
-
# Convert to grayscale if the image is not in grayscale format (e.g., RGB)
|
17 |
-
image = tf.image.rgb_to_grayscale(image)
|
18 |
-
|
19 |
# Resize the image to 28x28 as expected by the model
|
20 |
image = tf.image.resize(image, (28, 28)) # Resize to 28x28
|
21 |
|
22 |
-
#
|
23 |
-
|
|
|
24 |
|
25 |
# Normalize pixel values to [0, 1]
|
26 |
image = image / 255.0
|
|
|
|
|
|
|
27 |
|
28 |
# Add batch dimension (model expects batch of images)
|
29 |
image = tf.expand_dims(image, axis=0)
|
|
|
30 |
return image
|
31 |
|
32 |
# Function to make predictions
|
@@ -34,7 +34,8 @@ def predict(image):
|
|
34 |
image = preprocess_image(image)
|
35 |
prediction = model.predict(image) # Predict
|
36 |
predicted_class = np.argmax(prediction, axis=-1)[0] # Get the predicted class
|
37 |
-
|
|
|
38 |
|
39 |
# Create a Gradio interface
|
40 |
interface = gr.Interface(fn=predict, inputs="image", outputs="json")
|
|
|
10 |
def preprocess_image(image):
|
11 |
# Convert PIL image to a tensor
|
12 |
image = tf.convert_to_tensor(image)
|
13 |
+
|
|
|
|
|
|
|
|
|
|
|
14 |
# Resize the image to 28x28 as expected by the model
|
15 |
image = tf.image.resize(image, (28, 28)) # Resize to 28x28
|
16 |
|
17 |
+
# If the image is RGB, convert it to grayscale
|
18 |
+
if image.shape[-1] == 3:
|
19 |
+
image = tf.image.rgb_to_grayscale(image) # Convert RGB to grayscale
|
20 |
|
21 |
# Normalize pixel values to [0, 1]
|
22 |
image = image / 255.0
|
23 |
+
|
24 |
+
# Convert grayscale to RGB (3 channels)
|
25 |
+
image = tf.image.grayscale_to_rgb(image) # Convert grayscale to RGB (3 channels)
|
26 |
|
27 |
# Add batch dimension (model expects batch of images)
|
28 |
image = tf.expand_dims(image, axis=0)
|
29 |
+
|
30 |
return image
|
31 |
|
32 |
# Function to make predictions
|
|
|
34 |
image = preprocess_image(image)
|
35 |
prediction = model.predict(image) # Predict
|
36 |
predicted_class = np.argmax(prediction, axis=-1)[0] # Get the predicted class
|
37 |
+
class_confidence = np.max(prediction, axis=-1)[0] # Get the confidence score
|
38 |
+
return {"prediction": int(predicted_class), "confidence": class_confidence}
|
39 |
|
40 |
# Create a Gradio interface
|
41 |
interface = gr.Interface(fn=predict, inputs="image", outputs="json")
|