File size: 1,432 Bytes
de248c7
44a6fc4
f62da53
44a6fc4
 
 
 
 
 
de248c7
f62da53
 
44a6fc4
199a213
b4a47bb
f62da53
de248c7
44a6fc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f62da53
44a6fc4
de248c7
44a6fc4
073ff55
44a6fc4
de248c7
 
f62da53
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
44
45
46
47
48
49
50
51
52
53
54
from transformers import pipeline
from PIL import Image, ImageDraw
import gradio as gr
import torch
import timm  # Required for DETR model

# Load the model
device = 0 if torch.cuda.is_available() else -1
print(f"Using device: {'cuda' if device == 0 else 'cpu'}")

model_pipeline = pipeline(
    "object-detection",
    model="opria123/detr-resnet-50-dc5-hardhat-finetuned",
    device=device,
    threshold=0.2  # Lower threshold to catch more results
)

# Function to classify and draw results
def classify_image(image):
    print("Received image for classification.")

    results = model_pipeline(image)
    print(f"Model results:\n{results}")

    image = image.convert("RGB")
    draw = ImageDraw.Draw(image)

    for item in results:
        box = item["box"]
        label = item["label"]
        score = item["score"]

        print(f"Drawing box for: {label} ({score:.2f}) at {box}")

        draw.rectangle(
            [(box["xmin"], box["ymin"]), (box["xmax"], box["ymax"])],
            outline="red",
            width=3
        )
        draw.text((box["xmin"] + 5, box["ymin"] - 10), f"{label} ({score:.2f})", fill="red")

    return image

# Gradio interface
interface = gr.Interface(
    fn=classify_image,
    inputs=gr.Image(type="pil"),
    outputs=gr.Image(type="pil"),
    title="Hard Hat Detection",
    description="Upload an image to detect hard hats using a fine-tuned DETR model."
)

interface.launch()