Spaces:
Sleeping
Sleeping
Upload dogbreaddetection.py
Browse files- dogbreaddetection.py +99 -0
dogbreaddetection.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""DogBreadDetection.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1asSnC5KEvsnOmOzCEdX839PgCTd_zWfU
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
'''
|
| 11 |
+
The code is designed to identify dog breeds from uploaded images by leveraging a pretrained image classification model, such as VGG16 or ResNet, fine-tuned specifically for dog breed classification. This is achieved by using a Convolutional Neural Network (CNN) within TensorFlow or PyTorch frameworks. Additionally, Gradio is used to build a user-friendly web-based interface for easy image uploads and breed predictions.
|
| 12 |
+
'''
|
| 13 |
+
|
| 14 |
+
!pip install torch torchvision
|
| 15 |
+
!pip install matplotlib
|
| 16 |
+
!pip install gradio
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import torchvision.models as models
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import torchvision.transforms as transforms
|
| 23 |
+
import requests
|
| 24 |
+
import gradio as gr
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
# Load pretrained VGG16 model
|
| 28 |
+
VGG16 = models.vgg16(weights="IMAGENET1K_V1")
|
| 29 |
+
use_cuda = torch.cuda.is_available()
|
| 30 |
+
if use_cuda:
|
| 31 |
+
VGG16 = VGG16.cuda()
|
| 32 |
+
|
| 33 |
+
# Global cache for labels
|
| 34 |
+
LABELS_CACHE = None
|
| 35 |
+
|
| 36 |
+
def prefetch_labels():
|
| 37 |
+
global LABELS_CACHE
|
| 38 |
+
LABELS_MAP_URL = "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
|
| 39 |
+
try:
|
| 40 |
+
LABELS_CACHE = requests.get(LABELS_MAP_URL, timeout=5).json()
|
| 41 |
+
except requests.exceptions.RequestException as e:
|
| 42 |
+
LABELS_CACHE = None
|
| 43 |
+
print(f"Error fetching labels: {e}")
|
| 44 |
+
|
| 45 |
+
# Fetch labels on startup
|
| 46 |
+
prefetch_labels()
|
| 47 |
+
|
| 48 |
+
def load_convert_image_to_tensor(image):
|
| 49 |
+
if isinstance(image, np.ndarray):
|
| 50 |
+
image = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 51 |
+
elif isinstance(image, str):
|
| 52 |
+
image = Image.open(image).convert('RGB')
|
| 53 |
+
|
| 54 |
+
in_transform = transforms.Compose([
|
| 55 |
+
transforms.Resize(size=(224, 224)),
|
| 56 |
+
transforms.ToTensor()
|
| 57 |
+
])
|
| 58 |
+
image = in_transform(image)[:3, :, :].unsqueeze(0)
|
| 59 |
+
return image
|
| 60 |
+
|
| 61 |
+
def get_human_readable_label_for_class_id(class_id, labels_cache=None):
|
| 62 |
+
if labels_cache is None or class_id >= len(labels_cache):
|
| 63 |
+
return f"Unknown class ID: {class_id}"
|
| 64 |
+
return labels_cache[class_id]
|
| 65 |
+
|
| 66 |
+
def classify_image(image, confidence_threshold=0.0):
|
| 67 |
+
global LABELS_CACHE
|
| 68 |
+
if LABELS_CACHE is None:
|
| 69 |
+
return "Error: Labels not loaded"
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
image_tensor = load_convert_image_to_tensor(image)
|
| 73 |
+
if use_cuda:
|
| 74 |
+
image_tensor = image_tensor.cuda()
|
| 75 |
+
|
| 76 |
+
output = VGG16(image_tensor)
|
| 77 |
+
softmax_output = torch.nn.functional.softmax(output, dim=1)
|
| 78 |
+
top_probs, top_classes = torch.topk(softmax_output, 3)
|
| 79 |
+
top_probs = top_probs.cpu().detach().numpy() if use_cuda else top_probs.detach().numpy()
|
| 80 |
+
top_classes = top_classes.cpu().detach().numpy() if use_cuda else top_classes.detach().numpy()
|
| 81 |
+
|
| 82 |
+
result = {}
|
| 83 |
+
for prob, cls_id in zip(top_probs[0], top_classes[0]):
|
| 84 |
+
if prob >= confidence_threshold:
|
| 85 |
+
label = get_human_readable_label_for_class_id(int(cls_id), LABELS_CACHE)
|
| 86 |
+
result[label] = prob
|
| 87 |
+
return result if result else "No predictions above the confidence threshold."
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return f"Error: {str(e)}"
|
| 90 |
+
|
| 91 |
+
# Gradio Interface
|
| 92 |
+
image_input = gr.Image()
|
| 93 |
+
confidence_slider = gr.Slider(0, 1, 0.0, label="Confidence Threshold (Optional)") # Changed this line
|
| 94 |
+
label_output = gr.Label(num_top_classes=3)
|
| 95 |
+
|
| 96 |
+
interface = gr.Interface(fn=classify_image, inputs=[image_input, confidence_slider], outputs=label_output)
|
| 97 |
+
|
| 98 |
+
# Launch Gradio with shareable link
|
| 99 |
+
interface.launch(share=True)
|