itbetyar commited on
Commit
b95fc70
·
verified ·
1 Parent(s): 065d95a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -49
app.py CHANGED
@@ -1,61 +1,32 @@
1
  import gradio as gr
2
- import torch
3
- import torchvision.transforms as transforms
4
- from PIL import Image, ImageDraw
 
5
 
6
- # Load your YOLOv8 PyTorch model
7
  model_path = 'best_hat_detection_model_100.pt' # Your model file on Hugging Face Space
8
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
 
10
- # Load the model
11
- model = torch.load(model_path, map_location=device)['model'].float()
12
- model.eval()
13
-
14
- # Define transformations needed for your model
15
- transform = transforms.Compose([
16
- transforms.Resize((640, 640)),
17
- transforms.ToTensor(),
18
- ])
19
-
20
- # Function to draw bounding boxes on the image
21
- def draw_bboxes(image, predictions, threshold=0.5):
22
- draw = ImageDraw.Draw(image)
23
-
24
- for pred in predictions:
25
- # YOLO model typically returns a list or tensor of bounding boxes and confidence scores
26
- # pred: [x1, y1, x2, y2, confidence, class_id]
27
- # Make sure to unpack these values correctly.
28
-
29
- x1, y1, x2, y2, confidence = pred[:4] # Coordinates and confidence score
30
- if confidence > threshold: # Only draw boxes above the threshold
31
- draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
32
- draw.text((x1, y1), f"{confidence:.2f}", fill="red")
33
-
34
- return image
35
-
36
- # Function to predict and return image with bounding boxes
37
  def predict_safety_hat(image):
38
- pil_image = Image.fromarray(image.astype('uint8'), 'RGB') # Convert numpy array to PIL Image
39
- input_tensor = transform(pil_image).unsqueeze(0).to(device) # Apply transformations
40
-
41
- with torch.no_grad():
42
- predictions = model(input_tensor)[0] # Model output
43
 
44
- # Assuming predictions is a tensor, convert it to a list
45
- predictions = predictions.cpu().numpy() # Convert tensor to numpy array
46
 
47
- # Convert the image back to draw bounding boxes
48
- pil_image = pil_image.convert("RGB")
49
 
50
- # Assuming `predictions` contains the bounding box coordinates and confidence scores
51
- # Format of predictions: [x1, y1, x2, y2, confidence, class_id]
52
- return draw_bboxes(pil_image, predictions)
53
 
54
  # Gradio Interface
55
- inputs = gr.Image(label="Input Image")
56
- outputs = gr.Image(label="Output Image with Bounding Boxes") # Change to output image
57
 
58
- title = "Safety Hat Recognition"
59
- description = "Upload an image to detect safety hats and get bounding boxes."
60
 
61
- gr.Interface(predict_safety_hat, inputs, outputs, title=title, description=description).launch()
 
1
  import gradio as gr
2
+ from ultralytics import YOLO
3
+ import cv2
4
+ import numpy as np
5
+ from PIL import Image
6
 
7
+ # Load your YOLO model
8
  model_path = 'best_hat_detection_model_100.pt' # Your model file on Hugging Face Space
9
+ model = YOLO(model_path)
10
 
11
+ # Function to perform object detection and return the image with bounding boxes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def predict_safety_hat(image):
13
+ # Convert image from numpy array (Gradio format) to a format YOLO can process
14
+ image = np.array(image)
 
 
 
15
 
16
+ # Run inference using the YOLO model
17
+ results = model(image)
18
 
19
+ # Get the image with predictions drawn (bounding boxes, etc.)
20
+ result_image = results[0].plot() # YOLOv8 returns an image with the bounding boxes drawn
21
 
22
+ # Convert the result image back to PIL format for Gradio
23
+ return Image.fromarray(result_image)
 
24
 
25
  # Gradio Interface
26
+ inputs = gr.Image(label="Input Image", type="numpy")
27
+ outputs = gr.Image(label="Output Image with Bounding Boxes")
28
 
29
+ title = "Safety Hat Detection"
30
+ description = "Upload an image to detect safety hats and see bounding boxes."
31
 
32
+ gr.Interface(fn=predict_safety_hat, inputs=inputs, outputs=outputs, title=title, description=description).launch()