|
import tkinter as tk
|
|
from tkinter import filedialog, messagebox
|
|
from PIL import Image, ImageTk
|
|
import numpy as np
|
|
import tensorflow as tf
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
def resource_path(relative_path):
|
|
"""Get absolute path to resource, works for dev and for PyInstaller."""
|
|
try:
|
|
base_path = sys._MEIPASS
|
|
except Exception:
|
|
base_path = os.path.abspath(".")
|
|
return os.path.join(base_path, relative_path)
|
|
|
|
try:
|
|
model = tf.keras.models.load_model(resource_path("dog_breed_classifier.h5"), compile=False)
|
|
except Exception as e:
|
|
messagebox.showerror("Model Load Error", f"Could not load model:\n{e}")
|
|
sys.exit(1)
|
|
|
|
try:
|
|
with open(resource_path("class_indices.json"), "r") as f:
|
|
class_indices = json.load(f)
|
|
class_names = {int(v): k for k, v in class_indices.items()}
|
|
except Exception as e:
|
|
messagebox.showerror("Class Index Load Error", f"Could not load labels:\n{e}")
|
|
sys.exit(1)
|
|
|
|
def predict_image(image_path):
|
|
try:
|
|
img = Image.open(image_path).resize((224, 224)).convert("RGB")
|
|
img_array = np.array(img) / 255.0
|
|
img_array = np.expand_dims(img_array, axis=0)
|
|
predictions = model.predict(img_array)[0]
|
|
top_idx = np.argmax(predictions)
|
|
breed = class_names[top_idx]
|
|
confidence = predictions[top_idx] * 100
|
|
return breed, confidence
|
|
except Exception as e:
|
|
messagebox.showerror("Prediction Error", str(e))
|
|
return "Error", 0
|
|
|
|
def upload_image():
|
|
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg *.png *.jpeg")])
|
|
if not file_path:
|
|
return
|
|
image = Image.open(file_path)
|
|
image = image.resize((250, 250))
|
|
img_tk = ImageTk.PhotoImage(image)
|
|
img_label.configure(image=img_tk)
|
|
img_label.image = img_tk
|
|
|
|
breed, confidence = predict_image(file_path)
|
|
result_label.config(text=f"Breed: {breed}\nConfidence: {confidence:.2f}%")
|
|
|
|
root = tk.Tk()
|
|
root.title("Dog Breed Detector")
|
|
root.geometry("400x500")
|
|
root.configure(bg="white")
|
|
|
|
title = tk.Label(root, text="Dog Breed Classification", font=("Arial", 18), bg="white")
|
|
title.pack(pady=10)
|
|
|
|
btn = tk.Button(root, text="Upload Image", command=upload_image, font=("Arial", 12), bg="#4CAF50", fg="white")
|
|
btn.pack(pady=10)
|
|
|
|
img_label = tk.Label(root, bg="white")
|
|
img_label.pack()
|
|
|
|
result_label = tk.Label(root, text="", font=("Arial", 14), bg="white", fg="#333")
|
|
result_label.pack(pady=20)
|
|
|
|
root.mainloop()
|
|
|