Spaces:
Sleeping
Sleeping
File size: 7,860 Bytes
e161a2a d9de329 dfcbf3d 62e321b f919213 d9de329 034e449 e161a2a dfcbf3d e161a2a d9de329 034e449 d9de329 62e321b f919213 ba8cae1 428026a d9de329 f919213 d9de329 dfcbf3d d9de329 034e449 62e321b d9de329 e161a2a d9de329 e161a2a d9de329 e161a2a d9de329 e161a2a 62e321b e161a2a 62e321b d9de329 e161a2a d9de329 034e449 d9de329 034e449 d9de329 034e449 d9de329 f919213 64f336c f919213 d9de329 f919213 d9de329 034e449 d9de329 034e449 d9de329 034e449 d9de329 034e449 d9de329 f919213 d9de329 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
import hashlib
import tempfile
from pathlib import Path
from typing import Any
import gradio as gr
import torch
from PIL import Image
from rfdetr.detr import (
RFDETR,
RFDETRBase,
RFDETRLarge,
RFDETRMedium,
RFDETRNano,
RFDETRSmall,
)
from rfdetr.util.coco_classes import COCO_CLASSES
from sahi import AutoDetectionModel
from sahi.predict import get_prediction, get_sliced_prediction
from kofi import SCRIPT
APP_DIR = Path(__file__).parent
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
EXAMPLES_DIR = APP_DIR / "examples"
HEADER = """# [RF-DETR](https://github.com/roboflow/rf-detr) + [SAHI](https://github.com/obss/sahi) 🔥"""
IMAGE_PROCESSING_EXAMPLES = [
[
Image.open(EXAMPLES_DIR / "xingchen-yan-uDn6y3jii0Q-unsplash.jpg"),
"medium",
896,
0.6,
300,
380,
0.2,
0.2,
],
]
def load_model(checkpoint: str, resolution: int) -> RFDETR:
if checkpoint == "nano":
return RFDETRNano(resolution=resolution)
if checkpoint == "small":
return RFDETRSmall(resolution=resolution)
if checkpoint == "medium":
return RFDETRMedium(resolution=resolution)
if checkpoint == "base":
return RFDETRBase(resolution=resolution)
elif checkpoint == "large":
return RFDETRLarge(resolution=resolution)
raise TypeError("checkpoint must be a base or large")
def extend_model(
model: Any,
confidence_threshold: float,
category_mapping: dict,
):
model = AutoDetectionModel.from_pretrained(
model_type="roboflow",
model=model,
confidence_threshold=confidence_threshold,
category_mapping=category_mapping,
device=DEVICE,
)
return model
def run(
image_processing_input_image: Image.Image,
image_processing_checkpoint_dropdown: str,
image_processing_resolution_slider: int,
image_processing_confidence_slider: float,
slice_height: int,
slice_width: int,
overlap_height_ratio: float,
overlap_width_ratio: float,
):
image_processing_input_image = image_processing_input_image.convert("RGB")
image_hash = hashlib.md5(image_processing_input_image.tobytes()).hexdigest()
with tempfile.TemporaryDirectory() as temp_dir:
temp_dir = Path(temp_dir)
image_path = temp_dir / f"{image_hash}.jpg"
image_processing_input_image.save(str(image_path))
# Load model:
original_model = load_model(
checkpoint=image_processing_checkpoint_dropdown,
resolution=image_processing_resolution_slider,
)
# Extend model with SAHI:
model = extend_model(
model=original_model,
confidence_threshold=image_processing_confidence_slider,
category_mapping=COCO_CLASSES,
)
# Run original model prediction
prediction = get_prediction(
str(image_path),
model,
)
original_filename = f"{image_path.stem}_prediction"
prediction.export_visuals(
export_dir=str(temp_dir),
file_name=original_filename,
)
original_path = temp_dir / f"{original_filename}.png"
original_pil = Image.open(original_path)
# Run sliced model prediction
prediction_sliced = get_sliced_prediction(
str(image_path),
model,
slice_width=slice_width,
slice_height=slice_height,
overlap_width_ratio=overlap_width_ratio,
overlap_height_ratio=overlap_height_ratio,
postprocess_match_threshold=image_processing_confidence_slider,
)
scliced_filename = f"{image_path.stem}_sliced_prediction"
prediction_sliced.export_visuals(
export_dir=str(temp_dir),
file_name=scliced_filename,
)
sliced_path = temp_dir / f"{scliced_filename}.png"
sliced_pil = Image.open(sliced_path)
return original_pil, sliced_pil
with gr.Blocks(js=SCRIPT) as demo:
gr.Markdown(HEADER)
with gr.Row():
with gr.Column():
gr.Markdown("## Input")
image_processing_input_image = gr.Image(
label="Original Image",
image_mode="RGB",
type="pil",
height=600,
)
with gr.Column():
gr.Markdown("## Output")
image_processing_output_image = gr.ImageSlider(
label="Original vs Sliced Prediction",
image_mode="RGB",
type="pil",
height=600,
)
with gr.Row():
with gr.Column():
gr.Markdown("## RF-DETR Configuration")
image_processing_confidence_slider = gr.Slider(
label="Confidence",
minimum=0.0,
maximum=1.0,
step=0.05,
value=0.5,
)
image_processing_resolution_dropdown = gr.Dropdown(
label="Inference Resolution (dividable by 32 and 56)",
choices=[224, 448, 672, 896, 1008, 1120, 1344, 1568, 1792, 2016, 2240],
value=896,
)
image_processing_checkpoint_dropdown = gr.Dropdown(
label="Model Size",
choices=["nano", "small", "medium", "base", "large"],
value="base",
)
with gr.Column():
gr.Markdown("## SAHI Configuration")
slice_width = gr.Slider(
label="Slice Width",
minimum=100,
maximum=500,
step=1,
value=224,
)
slice_height = gr.Slider(
label="Slice Height",
minimum=100,
maximum=500,
step=1,
value=224,
)
overlap_width_ratio = gr.Slider(
label="Overlap Width Ratio",
minimum=0.0,
maximum=1.0,
step=0.05,
value=0.2,
)
overlap_height_ratio = gr.Slider(
label="Overlap Height Ratio",
minimum=0.0,
maximum=1.0,
step=0.05,
value=0.2,
)
with gr.Row():
with gr.Column():
image_processing_submit_button = gr.Button("Run")
with gr.Row():
with gr.Column():
gr.Markdown("## Examples")
gr.Examples(
fn=run,
examples=IMAGE_PROCESSING_EXAMPLES,
inputs=[
image_processing_input_image,
image_processing_checkpoint_dropdown,
image_processing_resolution_dropdown,
image_processing_confidence_slider,
slice_height,
slice_width,
overlap_height_ratio,
overlap_width_ratio,
],
outputs=[image_processing_output_image],
run_on_click=True,
cache_examples=False,
cache_mode="eager",
)
with gr.Row():
with gr.Column():
gr.HTML('<div id="kofi" style="text-align: center;"></div>')
image_processing_submit_button.click(
fn=run,
inputs=[
image_processing_input_image,
image_processing_checkpoint_dropdown,
image_processing_resolution_dropdown,
image_processing_confidence_slider,
slice_height,
slice_width,
overlap_height_ratio,
overlap_width_ratio,
],
outputs=[image_processing_output_image],
)
if __name__ == "__main__":
demo.launch(
debug=False,
)
|