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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import requests, validators
|
| 5 |
+
import torch
|
| 6 |
+
import pathlib
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from transformers import AutoFeatureExtractor, YolosForObjectDetection
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
|
| 12 |
+
|
| 13 |
+
# colors for visualization
|
| 14 |
+
COLORS = [
|
| 15 |
+
[0.000, 0.447, 0.741],
|
| 16 |
+
[0.850, 0.325, 0.098],
|
| 17 |
+
[0.929, 0.694, 0.125],
|
| 18 |
+
[0.494, 0.184, 0.556],
|
| 19 |
+
[0.466, 0.674, 0.188],
|
| 20 |
+
[0.301, 0.745, 0.933]
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
def make_prediction(img, feature_extractor, model):
|
| 24 |
+
inputs = feature_extractor(img, return_tensors="pt")
|
| 25 |
+
outputs = model(**inputs)
|
| 26 |
+
img_size = torch.tensor([tuple(reversed(img.size))])
|
| 27 |
+
processed_outputs = feature_extractor.post_process(outputs, img_size)
|
| 28 |
+
return processed_outputs[0]
|
| 29 |
+
|
| 30 |
+
def fig2img(fig):
|
| 31 |
+
buf = io.BytesIO()
|
| 32 |
+
fig.savefig(buf)
|
| 33 |
+
buf.seek(0)
|
| 34 |
+
pil_img = Image.open(buf)
|
| 35 |
+
basewidth = 750
|
| 36 |
+
wpercent = (basewidth/float(pil_img.size[0]))
|
| 37 |
+
hsize = int((float(pil_img.size[1])*float(wpercent)))
|
| 38 |
+
img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
|
| 39 |
+
return img
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
| 43 |
+
keep = output_dict["scores"] > threshold
|
| 44 |
+
boxes = output_dict["boxes"][keep].tolist()
|
| 45 |
+
scores = output_dict["scores"][keep].tolist()
|
| 46 |
+
labels = output_dict["labels"][keep].tolist()
|
| 47 |
+
if id2label is not None:
|
| 48 |
+
labels = [id2label[x] for x in labels]
|
| 49 |
+
|
| 50 |
+
plt.figure(figsize=(25, 20))
|
| 51 |
+
plt.imshow(img)
|
| 52 |
+
ax = plt.gca()
|
| 53 |
+
colors = COLORS * 100
|
| 54 |
+
for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
|
| 55 |
+
ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
|
| 56 |
+
ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
|
| 57 |
+
plt.axis("off")
|
| 58 |
+
return fig2img(plt.gcf())
|
| 59 |
+
|
| 60 |
+
def get_original_image(url_input):
|
| 61 |
+
if validators.url(url_input):
|
| 62 |
+
image = Image.open(requests.get(url_input, stream=True).raw)
|
| 63 |
+
|
| 64 |
+
return image
|
| 65 |
+
|
| 66 |
+
def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
|
| 67 |
+
|
| 68 |
+
#Extract model and feature extractor
|
| 69 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
| 70 |
+
|
| 71 |
+
model = YolosForObjectDetection.from_pretrained(model_name)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if validators.url(url_input):
|
| 75 |
+
image = get_original_image(url_input)
|
| 76 |
+
|
| 77 |
+
elif image_input:
|
| 78 |
+
image = image_input
|
| 79 |
+
|
| 80 |
+
elif webcam_input:
|
| 81 |
+
image = webcam_input
|
| 82 |
+
|
| 83 |
+
#Make prediction
|
| 84 |
+
processed_outputs = make_prediction(image, feature_extractor, model)
|
| 85 |
+
|
| 86 |
+
#Visualize prediction
|
| 87 |
+
viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
|
| 88 |
+
|
| 89 |
+
return viz_img
|
| 90 |
+
|
| 91 |
+
def set_example_image(example: list) -> dict:
|
| 92 |
+
return gr.Image.update(value=example[0])
|
| 93 |
+
|
| 94 |
+
def set_example_url(example: list) -> dict:
|
| 95 |
+
return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
title = """<h1 id="title">Face Mask Detection with YOLOS</h1>"""
|
| 99 |
+
|
| 100 |
+
description = """
|
| 101 |
+
|
| 102 |
+
YOLOS is a Vision Transformer (ViT) trained using the DETR loss. Despite its simplicity, a base-sized YOLOS model is able to achieve 42 AP on COCO validation 2017 (similar to DETR and more complex frameworks such as Faster R-CNN).
|
| 103 |
+
|
| 104 |
+
The YOLOS model was fine-tuned on COCO 2017 object detection (118k annotated images). It was introduced in the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Fang et al. and first released in [this repository](https://github.com/hustvl/YOLOS).
|
| 105 |
+
|
| 106 |
+
This model was further fine-tuned on the [face mask dataset]("https://www.kaggle.com/datasets/andrewmvd/face-mask-detection") from Kaggle. The dataset consists of 853 images of people with annotations categorised as "with mask","without mask" and "mask not worn correctly". The model was trained for 200 epochs on a single GPU.
|
| 107 |
+
|
| 108 |
+
Links to HuggingFace Models:
|
| 109 |
+
- [nickmuchi/yolos-small-finetuned-masks](https://huggingface.co/nickmuchi/yolos-small-finetuned-masks)
|
| 110 |
+
- [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
models = ["nickmuchi/yolos-small-finetuned-masks","nickmuchi/yolos-base-finetuned-masks"]
|
| 114 |
+
urls = ["https://drive.google.com/uc?id=1VwYLbGak5c-2P5qdvfWVOeg7DTDYPbro","https://api.time.com/wp-content/uploads/2020/03/hong-kong-mask-admiralty.jpg"]
|
| 115 |
+
|
| 116 |
+
twitter_link = """
|
| 117 |
+
[](https://twitter.com/nickmuchi)
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
css = '''
|
| 121 |
+
h1#title {
|
| 122 |
+
text-align: center;
|
| 123 |
+
}
|
| 124 |
+
'''
|
| 125 |
+
demo = gr.Blocks(css=css)
|
| 126 |
+
|
| 127 |
+
with demo:
|
| 128 |
+
gr.Markdown(title)
|
| 129 |
+
gr.Markdown(description)
|
| 130 |
+
gr.Markdown(twitter_link)
|
| 131 |
+
options = gr.Dropdown(choices=models,label='Object Detection Model',show_label=True)
|
| 132 |
+
slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
|
| 133 |
+
|
| 134 |
+
with gr.Tabs():
|
| 135 |
+
with gr.TabItem('Image URL'):
|
| 136 |
+
with gr.Row():
|
| 137 |
+
with gr.Column():
|
| 138 |
+
url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
|
| 139 |
+
original_image = gr.Image(shape=(500,500))
|
| 140 |
+
with gr.Column():
|
| 141 |
+
img_output_from_url = gr.Image(shape=(750,750))
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
|
| 145 |
+
|
| 146 |
+
url_but = gr.Button('Detect')
|
| 147 |
+
|
| 148 |
+
with gr.TabItem('Image Upload'):
|
| 149 |
+
with gr.Row():
|
| 150 |
+
img_input = gr.Image(type='pil',shape=(500,500))
|
| 151 |
+
img_output_from_upload= gr.Image(shape=(750,750))
|
| 152 |
+
|
| 153 |
+
with gr.Row():
|
| 154 |
+
example_images = gr.Dataset(components=[img_input],
|
| 155 |
+
samples=[[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
img_but = gr.Button('Detect')
|
| 159 |
+
|
| 160 |
+
with gr.TabItem('WebCam'):
|
| 161 |
+
with gr.Row():
|
| 162 |
+
web_input = gr.Image(source='webcam',type='pil',shape=(500,500),streaming=True)
|
| 163 |
+
img_output_from_webcam= gr.Image(shape=(750,750))
|
| 164 |
+
|
| 165 |
+
cam_but = gr.Button('Detect')
|
| 166 |
+
|
| 167 |
+
url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
|
| 168 |
+
img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
|
| 169 |
+
cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
|
| 170 |
+
example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
|
| 171 |
+
example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input,original_image])
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
gr.Markdown("")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
demo.launch(debug=True,enable_queue=True)
|