Spaces:
Sleeping
Sleeping
File size: 1,295 Bytes
f8835e9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import gradio as gr
import joblib
from tensorflow.keras.models import load_model
import numpy as np
from PIL import Image, ImageDraw
# Load your saved CNN or ANN model
model = load_model('CNN_model.h5', compile=False)
model.compile(optimizer='adam', loss='mean_squared_error')
def predict_and_draw_box(img):
try:
# Convert to grayscale & resize
img_gray = img.convert('L').resize((128, 128))
img_array = np.array(img_gray).astype("float32") / 255.0
img_array = img_array.reshape(1, 128, 128, 1)
# Predict bounding box
pred = model.predict(img_array)[0]
x, y, w, h = np.clip(pred, 0, 128)
# Draw box on the image
draw_img = img_gray.convert("RGB")
draw = ImageDraw.Draw(draw_img)
draw.rectangle([x, y, x + w, y + h], outline="red", width=3)
return draw_img
except Exception as e:
return f"Error: {str(e)}"
import gradio as gr
gr.Interface(
fn=predict_and_draw_box,
inputs=gr.Image(type="pil", label="Upload Image"),
outputs=gr.Image(type="pil", label="Predicted Bounding Box"),
title="Object Localization (CNN Model)",
description="Upload a grayscale image (128x128 or any size). The model will predict and draw a red bounding box."
).launch(share=True)
|