qbcode commited on
Commit
7111e92
·
verified ·
1 Parent(s): dc08180

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -130
app.py CHANGED
@@ -1,141 +1,83 @@
1
  import gradio as gr
2
- import spaces
3
- from huggingface_hub import hf_hub_download
4
 
5
- def download_models(model_id):
6
- hf_hub_download("qbcode/chicken_detection", filename=f"{model_id}", local_dir=f"./")
7
- return f"./{model_id}"
8
-
9
- @spaces.GPU
10
- def yolov8_inference(img_path, model_id, image_size, conf_threshold, iou_threshold):
11
- """
12
- Load a YOLOv9 model, configure it, perform inference on an image, and optionally adjust
13
- the input size and apply test time augmentation.
14
-
15
- :param model_path: Path to the YOLOv9 model file.
16
- :param conf_threshold: Confidence threshold for NMS.
17
- :param iou_threshold: IoU threshold for NMS.
18
- :param img_path: Path to the image file.
19
- :param size: Optional, input size for inference.
20
- :return: Annotated image with the number of objects detected.
21
- """
22
- # Import YOLOv9
23
- import yolov8
24
-
25
-
26
- # Load the model
27
- model_path = download_models(model_id)
28
- model = yolov8.load(model_path, device="cuda:0")
29
 
30
- # Set model parameters
31
- model.conf = conf_threshold
32
- model.iou = iou_threshold
33
-
34
- # Perform inference
35
- results = model(img_path, size=image_size)
36
 
37
- # Optionally, show detection bounding boxes on image
38
- annotated_image = results.render()
39
-
40
- # Count the number of detected objects
41
- num_objects_detected = len(results.pred[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- return annotated_image, f"Number of objects detected: {num_objects_detected}"
 
 
 
 
 
 
 
44
 
45
- def app():
46
- with gr.Blocks():
47
- with gr.Row():
48
- with gr.Column():
49
- img_path = gr.Image(type="filepath", label="Image")
50
- model_path = gr.Dropdown(
51
- label="Model",
52
- choices=[
53
- "best.pt",
54
- "gelan-e.pt",
55
- "yolov9-c.pt",
56
- "yolov9-e.pt",
57
- ],
58
- value="gelan-e.pt",
59
- )
60
- image_size = gr.Slider(
61
- label="Image Size",
62
- minimum=320,
63
- maximum=1280,
64
- step=32,
65
- value=640,
66
- )
67
- conf_threshold = gr.Slider(
68
- label="Confidence Threshold",
69
- minimum=0.1,
70
- maximum=1.0,
71
- step=0.1,
72
- value=0.4,
73
- )
74
- iou_threshold = gr.Slider(
75
- label="IoU Threshold",
76
- minimum=0.1,
77
- maximum=1.0,
78
- step=0.1,
79
- value=0.5,
80
- )
81
- yolov8_infer = gr.Button(value="Inference")
82
 
83
- with gr.Column():
84
- output_image = gr.Image(type="numpy",label="Output")
85
- num_objects_detected = gr.Textbox(label="Number of Objects Detected")
86
 
87
- yolov8_infer.click(
88
- fn=yolov8_inference,
89
- inputs=[
90
- img_path,
91
- model_path,
92
- image_size,
93
- conf_threshold,
94
- iou_threshold,
95
- ],
96
- outputs=[output_image, num_objects_detected],
97
- )
98
-
99
- gr.Examples(
100
- examples=[
101
- [
102
- "eg/test1",
103
- "best.pt",
104
- 640,
105
- 0.4,
106
- 0.5,
107
- ],
108
- ],
109
- fn=yolov8_inference,
110
- inputs=[
111
- img_path,
112
- model_path,
113
- image_size,
114
- conf_threshold,
115
- iou_threshold,
116
- ],
117
- outputs=[output_image, num_objects_detected],
118
- cache_examples=True,
119
- )
120
 
 
121
 
122
- gradio_app = gr.Blocks()
123
- with gradio_app:
124
- gr.HTML(
125
- """
126
- <h1 style='text-align: center'>
127
- YOLOv9: Learning What You Want to Learn Using Programmable Gradient Information
128
- </h1>
129
- """)
130
- gr.HTML(
131
- """
132
- <h3 style='text-align: center'>
133
- Follow me for more!
134
- <a href='https://twitter.com/kadirnar_ai' target='_blank'>Twitter</a> | <a href='https://github.com/kadirnar' target='_blank'>Github</a> | <a href='https://www.linkedin.com/in/kadir-nar/' target='_blank'>Linkedin</a> | <a href='https://www.huggingface.co/kadirnar/' target='_blank'>HuggingFace</a>
135
- </h3>
136
- """)
137
- with gr.Row():
138
- with gr.Column():
139
- app()
140
 
141
- gradio_app.launch(debug=True)
 
1
  import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
 
5
+ # Define function to detect objects using YOLO
6
+ def detect_objects(image, model_type):
7
+ # Load the YOLO model based on the model type
8
+ if model_type == 'YOLOv7':
9
+ weights_path = "path_to_yolov7_weights"
10
+ config_path = "path_to_yolov7_config"
11
+ net = cv2.dnn.readNet(weights_path, config_path)
12
+ layer_names = net.getLayerNames()
13
+ output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
14
+ elif model_type == 'YOLOv8':
15
+ weights_path = "path_to_yolov8_weights"
16
+ config_path = "path_to_yolov8_config"
17
+ net = cv2.dnn.readNet(weights_path, config_path)
18
+ layer_names = net.getLayerNames()
19
+ output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
20
+ elif model_type == 'YOLO-NAS':
21
+ weights_path = "path_to_yolo_nas_weights"
22
+ config_path = "path_to_yolo_nas_config"
23
+ net = cv2.dnn.readNet(weights_path, config_path)
24
+ layer_names = net.getLayerNames()
25
+ output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
26
+ else:
27
+ return "Invalid Model Type"
 
28
 
29
+ # Detect objects in the image
30
+ blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
31
+ net.setInput(blob)
32
+ outs = net.forward(output_layers)
 
 
33
 
34
+ # Process detection results
35
+ class_ids = []
36
+ confidences = []
37
+ boxes = []
38
+ for out in outs:
39
+ for detection in out:
40
+ scores = detection[5:]
41
+ class_id = np.argmax(scores)
42
+ confidence = scores[class_id]
43
+ if confidence > 0.5:
44
+ # Object detected
45
+ center_x = int(detection[0] * image.shape[1])
46
+ center_y = int(detection[1] * image.shape[0])
47
+ w = int(detection[2] * image.shape[1])
48
+ h = int(detection[3] * image.shape[0])
49
+ x = int(center_x - w / 2)
50
+ y = int(center_y - h / 2)
51
+ boxes.append([x, y, w, h])
52
+ confidences.append(float(confidence))
53
+ class_ids.append(class_id)
54
+
55
+ # Non-max suppression to remove overlapping boxes
56
+ indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
57
 
58
+ # Draw bounding boxes on the image
59
+ for i in range(len(boxes)):
60
+ if i in indexes:
61
+ x, y, w, h = boxes[i]
62
+ label = str(class_ids[i])
63
+ color = (255, 0, 0) # BGR color format
64
+ cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
65
+ cv2.putText(image, label, (x, y + 30), cv2.FONT_HERSHEY_PLAIN, 3, color, 3)
66
 
67
+ return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ # Create Gradio interface
70
+ models = ["YOLOv7", "YOLOv8", "YOLO-NAS"]
 
71
 
72
+ pages = []
73
+ for model in models:
74
+ inputs = [
75
+ gr.inputs.Image(label="Upload Image or Video"),
76
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ outputs = gr.outputs.Image(label=f"{model} Output")
79
 
80
+ page = gr.Interface(detect_objects, inputs, outputs, title=f"{model} Object Detection", description=f"Identify objects in images or videos using {model}").launch()
81
+ pages.append((f"{model} Model", page))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ gr.Interface(pages, gr.Interface.MULTIPAGE).launch()