File size: 15,931 Bytes
1e04a2b |
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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
# `gradio_patch_selection`
<a href="https://pypi.org/project/gradio_patch_selection/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gradio_patch_selection"></a>
A Gradio component that allows users to select patches from images by overlaying a customizable grid.
## Installation
```bash
pip install gradio_patch_selection
```
## Usage
```python
# filepath: /Users/dgcnz/development/playground/gradio_image_annotator/demo/app_dynamic_inputs.py
import gradio as gr
from gradio_patch_selection import PatchSelector
# Default values for image size and patch size
DEFAULT_IMG_SIZE = 224
DEFAULT_PATCH_SIZE = 16
example_annotation = {
"image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
"patch_index": 42, # Example patch index
"img_size": DEFAULT_IMG_SIZE,
"patch_size": DEFAULT_PATCH_SIZE
}
examples = [
{
"image": "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png",
"patch_index": 10, # Example patch index
"img_size": DEFAULT_IMG_SIZE,
"patch_size": DEFAULT_PATCH_SIZE
},
{
"image": "https://gradio-builds.s3.amazonaws.com/demo-files/base.png",
"patch_index": 42, # Example patch index
"img_size": DEFAULT_IMG_SIZE,
"patch_size": DEFAULT_PATCH_SIZE
},
]
def get_patch_index(annotations):
"""Get the selected patch index from annotations"""
if annotations and annotations.get("patch_index") is not None:
return f"Selected Patch Index: {annotations['patch_index']}"
return "No patch selected"
def update_params(img_size, patch_size, current_annotation):
"""Update patch_size and img_size based on user inputs"""
if not current_annotation:
current_annotation = {"image": None, "patch_index": None}
# Ensure values are integers and within reasonable bounds
img_size = max(32, min(1024, int(img_size)))
patch_size = max(1, min(128, int(patch_size)))
# Preserve the existing image and patch_index if they exist
current_annotation["img_size"] = img_size
current_annotation["patch_size"] = patch_size
# Return updated annotation and parameter info string
param_info = f"Image Size: {img_size}x{img_size}\nPatch Size: {patch_size}x{patch_size}"
# Calculate grid dimensions
grid_width = img_size // patch_size
grid_height = img_size // patch_size
grid_info = f"Grid Dimensions: {grid_width}x{grid_height} ({grid_width * grid_height} patches)"
return current_annotation, param_info, grid_info
with gr.Blocks() as demo:
with gr.Tab("Dynamic Patch Selector", id="tab_dynamic_patch_selector"):
gr.Markdown("# Dynamic Patch Selector Demo")
gr.Markdown("This demo shows how to dynamically update the patch size and image size using number inputs.")
with gr.Row():
with gr.Column(scale=1):
img_size_input = gr.Number(
value=DEFAULT_IMG_SIZE,
label="Image Size",
minimum=32,
maximum=1024,
step=16,
precision=0
)
patch_size_input = gr.Number(
value=DEFAULT_PATCH_SIZE,
label="Patch Size",
minimum=1,
maximum=128,
step=1,
precision=0
)
param_info = gr.Textbox(
value=f"Image Size: {DEFAULT_IMG_SIZE}x{DEFAULT_IMG_SIZE}\nPatch Size: {DEFAULT_PATCH_SIZE}x{DEFAULT_PATCH_SIZE}",
label="Parameters",
interactive=False
)
grid_info = gr.Textbox(
value=f"Grid Dimensions: {DEFAULT_IMG_SIZE//DEFAULT_PATCH_SIZE}x{DEFAULT_IMG_SIZE//DEFAULT_PATCH_SIZE} ({(DEFAULT_IMG_SIZE//DEFAULT_PATCH_SIZE)**2} patches)",
label="Grid Information",
interactive=False
)
with gr.Row():
with gr.Column(scale=2):
annotator = PatchSelector(
example_annotation,
img_size=DEFAULT_IMG_SIZE, # Default image size
patch_size=DEFAULT_PATCH_SIZE, # Default patch size
show_grid=True,
grid_color="rgba(200, 200, 200, 0.5)"
)
with gr.Column(scale=1):
output = gr.Textbox(label="Selected Patch", value="No patch selected")
gr.Markdown("### How it works")
gr.Markdown("1. Adjust the image size and patch size using the number inputs")
gr.Markdown("2. The grid will update automatically based on your inputs")
gr.Markdown("3. Click on any patch to select it and get its index")
# Handle the parameter change events
img_size_input.change(
update_params,
inputs=[img_size_input, patch_size_input, annotator],
outputs=[annotator, param_info, grid_info]
)
patch_size_input.change(
update_params,
inputs=[img_size_input, patch_size_input, annotator],
outputs=[annotator, param_info, grid_info]
)
# Handle the patch selection event
annotator.patch_select(get_patch_index, annotator, output)
gr.Examples(examples, annotator)
if __name__ == "__main__":
demo.launch()
```
## `PatchSelector`
### Initialization
<table>
<thead>
<tr>
<th align="left">name</th>
<th align="left" style="width: 25%;">type</th>
<th align="left">default</th>
<th align="left">description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>value</code></td>
<td align="left" style="width: 25%;">
```python
dict | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">A dict or None. The dictionary must contain a key 'image' with either an URL to an image, a numpy image or a PIL image. It may also contain a key 'patchIndex' with the index of the selected patch.</td>
</tr>
<tr>
<td align="left"><code>height</code></td>
<td align="left" style="width: 25%;">
```python
int | str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">The height of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.</td>
</tr>
<tr>
<td align="left"><code>width</code></td>
<td align="left" style="width: 25%;">
```python
int | str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">The width of the displayed image, specified in pixels if a number is passed, or in CSS units if a string is passed.</td>
</tr>
<tr>
<td align="left"><code>img_size</code></td>
<td align="left" style="width: 25%;">
```python
int | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">If provided, will resize the displayed image to this fixed dimension (img_size × img_size). This takes precedence over height and width parameters. Recommended for ViT models, which typically use square images of fixed dimensions (e.g., 224x224).</td>
</tr>
<tr>
<td align="left"><code>patch_size</code></td>
<td align="left" style="width: 25%;">
```python
int
```
</td>
<td align="left"><code>16</code></td>
<td align="left">The size of each patch in pixels. For a 224x224 image with patch_size=16, there will be a 14x14 grid (196 patches).</td>
</tr>
<tr>
<td align="left"><code>show_grid</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, will display the grid overlay on the image.</td>
</tr>
<tr>
<td align="left"><code>grid_color</code></td>
<td align="left" style="width: 25%;">
```python
str
```
</td>
<td align="left"><code>"rgba(200, 200, 200, 0.5)"</code></td>
<td align="left">The color of the grid overlay lines, specified as a CSS color string.</td>
</tr>
<tr>
<td align="left"><code>image_mode</code></td>
<td align="left" style="width: 25%;">
```python
"1"
| "L"
| "P"
| "RGB"
| "RGBA"
| "CMYK"
| "YCbCr"
| "LAB"
| "HSV"
| "I"
| "F"
```
</td>
<td align="left"><code>"RGB"</code></td>
<td align="left">"RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.</td>
</tr>
<tr>
<td align="left"><code>sources</code></td>
<td align="left" style="width: 25%;">
```python
list["upload" | "webcam" | "clipboard"] | None
```
</td>
<td align="left"><code>["upload", "webcam", "clipboard"]</code></td>
<td align="left">List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"].</td>
</tr>
<tr>
<td align="left"><code>image_type</code></td>
<td align="left" style="width: 25%;">
```python
"numpy" | "pil" | "filepath"
```
</td>
<td align="left"><code>"numpy"</code></td>
<td align="left">The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.</td>
</tr>
<tr>
<td align="left"><code>label</code></td>
<td align="left" style="width: 25%;">
```python
str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.</td>
</tr>
<tr>
<td align="left"><code>container</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, will place the component in a container - providing some extra padding around the border.</td>
</tr>
<tr>
<td align="left"><code>scale</code></td>
<td align="left" style="width: 25%;">
```python
int | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.</td>
</tr>
<tr>
<td align="left"><code>min_width</code></td>
<td align="left" style="width: 25%;">
```python
int
```
</td>
<td align="left"><code>160</code></td>
<td align="left">minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.</td>
</tr>
<tr>
<td align="left"><code>interactive</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>True</code></td>
<td align="left">if True, will allow users to upload and annotate an image; if False, can only be used to display annotated images.</td>
</tr>
<tr>
<td align="left"><code>visible</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If False, component will be hidden.</td>
</tr>
<tr>
<td align="left"><code>elem_id</code></td>
<td align="left" style="width: 25%;">
```python
str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
</tr>
<tr>
<td align="left"><code>elem_classes</code></td>
<td align="left" style="width: 25%;">
```python
list[str] | str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
</tr>
<tr>
<td align="left"><code>render</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.</td>
</tr>
<tr>
<td align="left"><code>show_label</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">if True, will display label.</td>
</tr>
<tr>
<td align="left"><code>show_download_button</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, will show a button to download the image.</td>
</tr>
<tr>
<td align="left"><code>show_share_button</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.</td>
</tr>
<tr>
<td align="left"><code>show_clear_button</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, will show a button to clear the current image.</td>
</tr>
<tr>
<td align="left"><code>show_remove_button</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">If True, will show a button to remove the selected bounding box.</td>
</tr>
<tr>
<td align="left"><code>handles_cursor</code></td>
<td align="left" style="width: 25%;">
```python
bool | None
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, the cursor will change when hovering over box handles in drag mode. Can be CPU-intensive.</td>
</tr>
</tbody></table>
### Events
| name | description |
|:-----|:------------|
| `clear` | This listener is triggered when the user clears the PatchSelector using the clear button for the component. |
| `change` | Triggered when the value of the PatchSelector changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. |
| `upload` | This listener is triggered when the user uploads a file into the PatchSelector. |
| `patch_select` | Triggered when a patch is selected by the user. Returns the patch index. |
### User function
The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).
- When used as an Input, the component only impacts the input signature of the user function.
- When used as an output, the component only impacts the return signature of the user function.
The code snippet below is accurate in cases where the component is used as both an input and an output.
- **As output:** Is passed, a dict with the image, patchIndex, imgSize, and patchSize or None.
- **As input:** Should return, a dict with an image and an optional patchIndex or None.
```python
def predict(
value: dict | None
) -> dict | None:
return value
```
|