Vvaann commited on
Commit
2dc0faa
·
verified ·
1 Parent(s): 2a27deb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -86
app.py CHANGED
@@ -1,11 +1,11 @@
1
  import torch
2
  import torchvision
3
- from torchvision import transforms
4
  import numpy as np
5
  import gradio as gr
6
  from PIL import Image
7
- from pytorch_grad_cam import GradCAM
8
- from pytorch_grad_cam.utils.image import show_cam_on_image
9
  import gradio as gr
10
  from models.yolo import Model
11
 
@@ -16,97 +16,81 @@ import yolov9
16
 
17
  model = yolov9.load('best.pt')
18
 
19
- classes = ('ball', 'goalkeeper', 'player', 'referee')
20
 
21
- model_layer_names = ["1", "2", "3"]
22
-
23
- def get_layer(layer_name):
24
- print("layer name:", layer_name)
25
- if layer_name == 1:
26
- return [model.layer1[-1]]
27
- elif layer_name == 2:
28
- return [model.layer2[-1]]
29
- elif layer_name == 3:
30
- return [model.layer3[-1]]
31
- else:
32
- return None
33
-
34
- def resize_image_pil(image, new_width, new_height):
35
- img = Image.fromarray(np.array(image))
36
- width, height = img.size
37
-
38
- width_scale = new_width/width
39
- height_scale = new_height/height
40
- scale = min(width_scale, height_scale)
41
- resized = img.resize((int(width*scale), int(height*scale)), Image.NEAREST)
42
- resized = resized.crop((0,0,new_width, new_height))
43
-
44
- return resized
45
-
46
-
47
- def inference(input_img, conf_threshold, iou_threshold, show_gradcam, layer_name, transparancy = 0.5):
48
  # Set model parameters
49
  model.conf = conf_threshold
50
  model.iou = iou_threshold
51
- print(show_gradcam, layer_name, num_classes, transparancy)
52
- input_img = resize_image_pil(input_img,32,32)
53
- input_img = np.array(input_img)
54
- org_img = input_img
55
-
56
- input_img= input_img.reshape((32,32,3))
57
- transform = transforms.ToTensor()
58
- input_img = transform(input_img)
59
- input_img = input_img.unsqueeze(0)
60
- outputs = model(input_img)
61
- output_res = outputs.render()
62
- # print(outputs)
63
- softmax = torch.nn.Softmax(dim=0)
64
- o = softmax(outputs.flatten())
65
 
66
- output_numpy = np.squeeze(np.asarray(outputs.detach().numpy()))
67
- index_sort = np.argsort(output_numpy)[::-1]
68
 
69
- # confidences = {}
70
- # for i in range(int(num_classes)):
71
- # confidences[classes[index_sort[i]]] = float(o[index_sort[i]])
72
 
73
-
74
- # prediction= torch.max(outputs, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- if show_gradcam:
77
- target_layers = get_layer(layer_name)
78
- print("target layer",target_layers)
79
- cam = GradCAM(model=model, target_layers=target_layers)
80
- grayscale_cam = cam(input_tensor= input_img)
81
- grayscale_cam = grayscale_cam[0, :]
82
- visualization = show_cam_on_image(org_img/255,grayscale_cam,use_rgb=True,
83
- image_weight=transparancy)
84
- else:
85
- visualization = org_img
 
 
 
 
 
 
 
 
 
 
 
86
 
87
-
88
- return output_res[0], visualization
89
-
90
- demo = gr.Interface(
91
- inference,
92
- inputs = [
93
- gr.Image(width=256,height=256,label="Input image"),
94
- gr.Slider(label='Confidence threshold', minimum=0.1,maximum=1.0,step=0.1,value=0.4),
95
- gr.Slider(label='IOU threshold', minimum=0.1,maximum=1.0,step=0.1,value=0.5),
96
- gr.Checkbox(True, label="Show GradCAM Image"),
97
- gr.Dropdown(model_layer_names, value=3, label="Which layer for Gradcam"),
98
- gr.Slider(0, 1, value=0.5,label="Overall opacity of the overlay"),
99
- ],
100
- outputs = [
101
- gr.Image(width= 256, height=256,label="Output Image"),
102
- gr.Image(width= 256, height=256,label="GradCAM image")
103
- ],
104
- title = "Yolo v9 on custom trained fooball dataset",
105
- description = " A simple gradio inference, and detection results for custom trained yolov9 for 100 epochs",
106
- examples = [["img1.jpg",0.4, 0.6, True, 3, 0.4]],
107
- cache_examples=True
108
- )
109
 
110
- if __name__ == "__main__":
111
- demo.launch()
112
 
 
1
  import torch
2
  import torchvision
3
+ # from torchvision import transforms
4
  import numpy as np
5
  import gradio as gr
6
  from PIL import Image
7
+ # from pytorch_grad_cam import GradCAM
8
+ # from pytorch_grad_cam.utils.image import show_cam_on_image
9
  import gradio as gr
10
  from models.yolo import Model
11
 
 
16
 
17
  model = yolov9.load('best.pt')
18
 
19
+ # classes = ('ball', 'goalkeeper', 'player', 'referee')
20
 
21
+ def inference(input_img, conf_threshold, iou_threshold):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # Set model parameters
23
  model.conf = conf_threshold
24
  model.iou = iou_threshold
25
+ # Perform inference
26
+ results = model(img_path, size=image_size)
27
+
28
+ # Optionally, show detection bounding boxes on image
29
+ output = results.render()
 
 
 
 
 
 
 
 
 
30
 
31
+ return output[0]
 
32
 
 
 
 
33
 
34
+ def app():
35
+ with gr.Blocks():
36
+ with gr.Row():
37
+ with gr.Column():
38
+ input_img = gr.Image(width= 256, height=256,label="Image")
39
+ conf_threshold = gr.Slider(
40
+ label="Confidence threshold",
41
+ minimum=0.1,
42
+ maximum=1.0,
43
+ step=0.1,
44
+ value=0.4
45
+ )
46
+ iou_threshold = gr.Slider(
47
+ label="IoU Threshold",
48
+ minimum=0.1,
49
+ maximum=1.0,
50
+ step=0.1,
51
+ value=0.5,
52
+ )
53
+ yolo_inf = gr.Button(value="Inference")
54
 
55
+ with gr.Column():
56
+ output_val = gr.Image(width= 256, height=256,label="Output Image")
57
+ yolo_inf.click(
58
+ fn= inference,
59
+ inputs = [
60
+ input_img,
61
+ conf_threshold,
62
+ iou_threshold
63
+ ],
64
+ outputs = [output_val],
65
+ )
66
+ gr.Examples(["img1.jpg",0.4, 0.6, 0.4],
67
+ fn= inference,
68
+ inputs = [
69
+ input_img,
70
+ conf_threshold,
71
+ iou_threshold
72
+ ],
73
+ outputs = [output_val],
74
+ cache_examples=True,
75
+ )
76
 
77
+ demo = gr.Blocks()
78
+ with demo:
79
+ gr.HTML(
80
+ """
81
+ <h1 style='text-align: center'>
82
+ YOLOv9
83
+ </h1>
84
+ """)
85
+ gr.HTML(
86
+ """
87
+ <h3 style='text-align: center'>
88
+ Inferencing yolov9 with custom dataset - football players dataset
89
+ </h3>
90
+ """)
91
+ with gr.Row():
92
+ with gr.Column():
93
+ app()
 
 
 
 
 
94
 
95
+ demo.launch(debug=True)
 
96