File size: 3,528 Bytes
d10f466
 
 
 
65f769b
69c84d2
d10f466
65f769b
 
 
d10f466
 
bf51623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d10f466
69c84d2
 
 
d10f466
69c84d2
 
 
d10f466
69c84d2
 
 
 
 
 
 
 
 
 
 
65f769b
69c84d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d10f466
 
 
bf51623
 
69c84d2
 
 
 
 
bf51623
d10f466
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import gradio as gr
import cv2
import torch
from PIL import Image
from transformers import DetrImageProcessor, DetrForObjectDetection
import numpy as np

# Load the pre-trained DETR model
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
model.eval()

# Function for image object detection
def image_object_detection(image_pil):
    # Process the image with the DETR model
    inputs = processor(images=image_pil, return_tensors="pt")
    outputs = model(**inputs)

    # Convert the image to numpy array for drawing bounding boxes
    image_np = cv2.cvtColor(cv2.cvtColor(cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR), cv2.COLOR_BGR2RGB), cv2.COLOR_RGB2BGR)

    # convert outputs (bounding boxes and class logits) to COCO API
    # let's only keep detections with score > 0.9
    target_sizes = torch.tensor([image_pil.size[::-1]])
    results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]

    # Draw bounding boxes on the image
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [int(round(i)) for i in box.tolist()]
        cv2.rectangle(image_np, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
        label_text = f"{model.config.id2label[label.item()]}: {round(score.item(), 3)}"
        cv2.putText(image_np, label_text, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    return image_np

# Function for live object detection from the camera
def live_object_detection():
    # Open a connection to the camera (replace with your own camera setup)
    cap = cv2.VideoCapture(0)

    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Convert the frame to PIL Image
        frame_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

        # Process the frame with the DETR model
        inputs = processor(images=frame_pil, return_tensors="pt")
        outputs = model(**inputs)

        # convert outputs (bounding boxes and class logits) to COCO API
        # let's only keep detections with score > 0.9
        target_sizes = torch.tensor([frame_pil.size[::-1]])
        results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]

        # Draw bounding boxes on the frame
        for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
            box = [int(round(i)) for i in box.tolist()]
            cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
            label_text = f"{model.config.id2label[label.item()]}: {round(score.item(), 3)}"
            cv2.putText(frame, label_text, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # Display the resulting frame
        cv2.imshow('Object Detection', frame)

        # Break the loop when 'q' key is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release the camera and close all windows
    cap.release()
    cv2.destroyAllWindows()

# Define the Gradio interface
iface = gr.Interface(
    fn=[image_object_detection, live_object_detection],
    inputs=[
        gr.Image(type="pil", label="Upload an image for object detection") # Remove this line
    ],
    outputs=[
        "image",
        "image",
    ],
    live=True,
)

# Launch the Gradio interface
iface.launch()