File size: 2,098 Bytes
d34354d
 
 
8a2fc35
d34354d
9fc7edf
 
8a2fc35
d34354d
8a2fc35
9fc7edf
8a2fc35
9fc7edf
 
d34354d
8a2fc35
 
 
 
 
 
 
 
 
9fc7edf
 
8a2fc35
9fc7edf
 
 
8a2fc35
 
9fc7edf
8a2fc35
9fc7edf
8a2fc35
 
9fc7edf
 
 
 
 
 
 
 
8a2fc35
d34354d
9fc7edf
d34354d
 
9fc7edf
 
 
 
d34354d
 
 
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
import gradio as gr
from ultralytics import YOLO
import cv2
import numpy as np

# Load YOLOv8 model
model_path = "best(1).pt"
model = YOLO(model_path)

# Assign unique colors to each class
colors = {name: (np.random.randint(100, 255), np.random.randint(100, 255), np.random.randint(100, 255)) for name in model.names.values()}

# Function to detect components in a PCB image
def detect_pcb(image, conf_threshold=0.5):
    results = model(image)
    detected_labels = []
    
    # Convert image format
    image = np.array(image, dtype=np.uint8)
    
    # Process results
    for result in results:
        for box in result.boxes:
            conf = box.conf[0].item()  # Confidence score
            if conf < conf_threshold:
                continue  # Ignore low-confidence detections

            x1, y1, x2, y2 = map(int, box.xyxy[0])  # Bounding box coordinates
            cls = int(box.cls[0])  # Class index
            label = model.names[cls]  # Component name
            detected_labels.append(f"{label} ({conf:.2f}) at ({x1}, {y1})")

            # Define colors and font
            color = colors[label]
            font = cv2.FONT_HERSHEY_SIMPLEX
            
            # Draw bounding box
            cv2.rectangle(image, (x1, y1), (x2, y2), color, 3)

            # Add text with a semi-transparent background
            text = f"{label} ({conf:.2f})"
            (w, h), _ = cv2.getTextSize(text, font, 0.7, 2)
            cv2.rectangle(image, (x1, y1 - h - 10), (x1 + w + 4, y1), color, -1)  # Background
            cv2.putText(image, text, (x1 + 2, y1 - 5), font, 0.7, (255, 255, 255), 2)

    return image, "\n".join(detected_labels)

# Create Gradio Interface
iface = gr.Interface(
    fn=detect_pcb,
    inputs=[gr.Image(type="numpy"), gr.Slider(0.1, 1.0, value=0.5, label="Confidence Threshold")],
    outputs=[gr.Image(type="numpy"), gr.Textbox(label="Detected Components")],
    title="🔍 PCB Component Detection",
    description="Upload a PCB image to detect components with a clearer output. Adjust confidence threshold to filter results.",
)

iface.launch()