SivaResearch/OpenSourceObjectDetectionModelComparision
0
1import io2import gradio as gr3import matplotlib.pyplot as plt4import requests, validators5import torch6import pathlib7from PIL import Image8from transformers import AutoFeatureExtractor, DetrForObjectDetection, YolosForObjectDetection9 10import os11 12# colors for visualization13COLORS = [14 [0.000, 0.447, 0.741],15 [0.850, 0.325, 0.098],16 [0.929, 0.694, 0.125],17 [0.494, 0.184, 0.556],18 [0.466, 0.674, 0.188],19 [0.301, 0.745, 0.933]20]21 22def make_prediction(img, feature_extractor, model):23 inputs = feature_extractor(img, return_tensors="pt")24 outputs = model(**inputs)25 img_size = torch.tensor([tuple(reversed(img.size))])26 processed_outputs = feature_extractor.post_process(outputs, img_size)27 return processed_outputs[0]28 29def fig2img(fig):30 buf = io.BytesIO()31 fig.savefig(buf)32 buf.seek(0)33 img = Image.open(buf)34 return img35 36 37def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):38 keep = output_dict["scores"] > threshold39 boxes = output_dict["boxes"][keep].tolist()40 scores = output_dict["scores"][keep].tolist()41 labels = output_dict["labels"][keep].tolist()42 if id2label is not None:43 labels = [id2label[x] for x in labels]44 45 plt.figure(figsize=(16, 10))46 plt.imshow(pil_img)47 ax = plt.gca()48 colors = COLORS * 10049 for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):50 ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))51 ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))52 plt.axis("off")53 return fig2img(plt.gcf())54 55 56 57 58models = ["facebook/detr-resnet-50",59 "facebook/detr-resnet-101",60 'hustvl/yolos-small',61 'hustvl/yolos-tiny']62 63def detect_objects(image_input,threshold):64 65 labels = []66 67 #Extract model and feature extractor68 feature_extractor_1 = AutoFeatureExtractor.from_pretrained("facebook/detr-resnet-50")69 feature_extractor_2 = AutoFeatureExtractor.from_pretrained("facebook/detr-resnet-101")70 feature_extractor_3 = AutoFeatureExtractor.from_pretrained('hustvl/yolos-small')71 feature_extractor_4 = AutoFeatureExtractor.from_pretrained('hustvl/yolos-tiny')72 73 74 model_1 = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")75 76 model_2 = YolosForObjectDetection.from_pretrained('hustvl/yolos-small')77 78 model_3 = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-101")79 80 model_4 = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')81 82 83 #Make prediction84 processed_outputs_1 = make_prediction(image_input, feature_extractor_1, model_1)85 processed_outputs_2 = make_prediction(image_input, feature_extractor_2, model_2)86 processed_outputs_3 = make_prediction(image_input, feature_extractor_3, model_3)87 processed_outputs_4 = make_prediction(image_input, feature_extractor_4, model_4)88 89 #Visualize prediction90 viz_img_1 = visualize_prediction(image_input, processed_outputs_1, threshold, model_1.config.id2label)91 viz_img_2 = visualize_prediction(image_input, processed_outputs_2, threshold, model_2.config.id2label)92 viz_img_3 = visualize_prediction(image_input, processed_outputs_3, threshold, model_3.config.id2label)93 viz_img_4 = visualize_prediction(image_input, processed_outputs_4, threshold, model_4.config.id2label)94 95 return viz_img_1,viz_img_2,viz_img_3,viz_img_496 97 98 99title = """<h1 id="title">Object Detection App with DETR and YOLOS</h1>"""100 101 102 103 104 105css = '''106h1#title {107 text-align: center;108}109'''110demo = gr.Blocks(css=css)111 112with demo:113 gr.Markdown(title)114 # gr.Markdown(description)115 # gr.Markdown(twitter_link)116 options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)117 slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.7,label='Prediction Threshold')118 119 with gr.Tabs():120 with gr.TabItem('Image URL'):121 with gr.Row():122 url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')123 img_output_from_url = gr.Image(shape=(650,650))124 125 url_but = gr.Button('Detect')126 127 with gr.TabItem('Image Upload'):128 with gr.Row():129 img_input = gr.Image(type='pil')130 img_output_from_upload= gr.Image(shape=(650,650))131 132 with gr.Row(): 133 example_images = gr.Dataset(components=[img_input],134 samples=[[path.as_posix()]135 for path in sorted(pathlib.Path('images').rglob('*.JPG'))])136 137 img_but = gr.Button('Detect')138 139 140 # url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_url,queue=True)141 img_but.click(detect_objects,inputs=[img_input,slider_input],outputs=img_output_from_upload,queue=True)142 # example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])143 # example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input])144 145 146 147 148demo.launch(enable_queue=True)149 150 151 152 153 154 155 