|
import numpy as np |
|
import gradio as gr |
|
import tensorflow as tf |
|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
|
def load_modified_model(model_path): |
|
return tf.keras.models.load_model(model_path) |
|
|
|
|
|
print("Loading model...") |
|
model = load_modified_model('food_model_1.h5') |
|
print("Model loaded successfully.") |
|
|
|
|
|
def classify_food_vs_nonfood(image): |
|
try: |
|
|
|
if not isinstance(image, Image.Image): |
|
image = Image.fromarray(image) |
|
|
|
|
|
if image.mode != "RGB": |
|
image = image.convert("RGB") |
|
|
|
|
|
image_size = (224, 224) |
|
image_resized = image.resize(image_size) |
|
image_np = np.array(image_resized) / 255.0 |
|
image_np_expanded = np.expand_dims(image_np, axis=0) |
|
|
|
|
|
prediction = model.predict(image_np_expanded) |
|
final_prediction = np.argmax(prediction[0]) |
|
|
|
|
|
results = {0: 'Food', 1: 'Non Food'} |
|
label = results[final_prediction] |
|
|
|
|
|
draw = ImageDraw.Draw(image) |
|
|
|
|
|
if final_prediction == 0: |
|
label_color = (255, 0, 0) |
|
text_font = ImageFont.truetype("Hack-Regular.ttf", 24) |
|
text_bbox = draw.textbbox((0, 0), label, font=text_font) |
|
text_size = (text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]) |
|
text_position = ((image_size[0] - text_size[0]) // 2, 10) |
|
else: |
|
label_color = (0, 255, 0) |
|
text_font = ImageFont.truetype("Hack-Regular.ttf", 48) |
|
text_bbox = draw.textbbox((0, 0), label, font=text_font) |
|
text_size = (text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]) |
|
text_position = ((image_size[0] - text_size[0]) // 2, (image_size[1] - text_size[1]) // 2) |
|
|
|
|
|
draw.text(text_position, label, fill=label_color, font=text_font) |
|
|
|
|
|
return image |
|
except Exception as e: |
|
print("Error processing image:", e) |
|
|
|
return Image.new("RGB", (224, 224), (255, 255, 255)) |
|
|
|
|
|
image_input = "image" |
|
|
|
|
|
ex_image_paths = ['image_1.jpeg', 'image_2.jpeg', 'image_3.jpeg', 'image_4.jpg', 'image_5.jpg'] |
|
|
|
|
|
food_vs_nonfood_interface = gr.Interface(classify_food_vs_nonfood, |
|
inputs=image_input, |
|
outputs="image", |
|
title="Food vs NonFood Classifier", |
|
description="Upload an image to classify whether it's food or non-food.", |
|
examples=ex_image_paths) |
|
food_vs_nonfood_interface.launch(inline=False) |
|
|