Upload 6 files
Browse files- .gitignore +30 -0
- LICENSE +199 -0
- README.md +140 -0
- examples/index.html +624 -0
- examples/infer.py +242 -0
- inspyrenet_swinb_1024.onnx +3 -0
.gitignore
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*$py.class
|
| 4 |
+
*.so
|
| 5 |
+
.Python
|
| 6 |
+
build/
|
| 7 |
+
develop-eggs/
|
| 8 |
+
dist/
|
| 9 |
+
downloads/
|
| 10 |
+
eggs/
|
| 11 |
+
.eggs/
|
| 12 |
+
lib/
|
| 13 |
+
lib64/
|
| 14 |
+
parts/
|
| 15 |
+
sdist/
|
| 16 |
+
var/
|
| 17 |
+
wheels/
|
| 18 |
+
*.egg-info/
|
| 19 |
+
.installed.cfg
|
| 20 |
+
*.egg
|
| 21 |
+
.env
|
| 22 |
+
.venv
|
| 23 |
+
env/
|
| 24 |
+
venv/
|
| 25 |
+
ENV/
|
| 26 |
+
.DS_Store
|
| 27 |
+
Thumbs.db
|
| 28 |
+
*.swp
|
| 29 |
+
*.swo
|
| 30 |
+
test_output*
|
LICENSE
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
Copyright 2026 Pink Pixel (https://pinkpixel.dev)
|
| 179 |
+
|
| 180 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 181 |
+
you may not use this file except in compliance with the License.
|
| 182 |
+
You may obtain a copy of the License at
|
| 183 |
+
|
| 184 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 185 |
+
|
| 186 |
+
Unless required by applicable law or agreed to in writing, software
|
| 187 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 188 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 189 |
+
See the License for the specific language governing permissions and
|
| 190 |
+
limitations under the License.
|
| 191 |
+
|
| 192 |
+
----------------------------------------------------------------------
|
| 193 |
+
Third-Party Attribution:
|
| 194 |
+
This distribution contains an ONNX export of InSPyReNet:
|
| 195 |
+
"InSPyReNet: Incongruent Salient Object Detection",
|
| 196 |
+
developed by Taehun Kim, Kunhee Kim, Joonyeong Lee, Dongmin Cha,
|
| 197 |
+
Jiho Lee, and Daijin Kim.
|
| 198 |
+
Original InSPyReNet repository: https://github.com/plemeri/InSPyReNet
|
| 199 |
+
InSPyReNet is licensed under the MIT License.
|
README.md
CHANGED
|
@@ -1,3 +1,143 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
pipeline_tag: image-segmentation
|
| 4 |
+
tags:
|
| 5 |
+
- background-removal
|
| 6 |
+
- image-segmentation
|
| 7 |
+
- onnx
|
| 8 |
+
- onnxruntime
|
| 9 |
+
- webgpu
|
| 10 |
+
- salient-object-detection
|
| 11 |
+
- inspyrenet
|
| 12 |
+
library_name: onnx
|
| 13 |
---
|
| 14 |
+
|
| 15 |
+
# InSPyReNet ONNX (Swin-B 1024x1024)
|
| 16 |
+
|
| 17 |
+
An ONNX export of **InSPyReNet** (Incongruent Salient Object Detection) using the Swin-B transformer backbone at 1024x1024 resolution. This model outputs fine-grained alpha mattes for zero-shot background removal, hair matting, and salient object extraction.
|
| 18 |
+
|
| 19 |
+
The model file `inspyrenet_swinb_1024.onnx` is self-contained (all initializers and weights are embedded directly in the 357 MB file). You can run it on CPU, CUDA, Apple Silicon via CoreML, or inside web browsers with WebGPU through ONNX Runtime.
|
| 20 |
+
|
| 21 |
+
## Model Summary
|
| 22 |
+
|
| 23 |
+
| Property | Value |
|
| 24 |
+
|---|---|
|
| 25 |
+
| Architecture | InSPyReNet (Swin-B backbone) |
|
| 26 |
+
| Task | Salient Object Detection / Background Removal |
|
| 27 |
+
| Format | ONNX (IR version 10, Opset 17) |
|
| 28 |
+
| Model Size | 357 MB |
|
| 29 |
+
| Input Tensor | `input`: `[1, 3, 1024, 1024]` (Float32, RGB) |
|
| 30 |
+
| Output Tensor | `alpha`: `[1, 1, 1024, 1024]` (Float32, range `[0.0, 1.0]`) |
|
| 31 |
+
| Preprocessing | Resize to 1024x1024, scale to `[0, 1]`, ImageNet mean/std |
|
| 32 |
+
| License | Apache 2.0 (Upstream InSPyReNet is MIT) |
|
| 33 |
+
|
| 34 |
+
## Quickstart (Python)
|
| 35 |
+
|
| 36 |
+
Install `onnxruntime` and `pillow`:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install onnxruntime pillow numpy
|
| 40 |
+
# Or for GPU support:
|
| 41 |
+
# pip install onnxruntime-gpu pillow numpy
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Run background removal in Python:
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
import numpy as np
|
| 48 |
+
import onnxruntime as ort
|
| 49 |
+
from PIL import Image
|
| 50 |
+
|
| 51 |
+
# 1. Load image and keep original dimensions
|
| 52 |
+
img = Image.open("input.jpg").convert("RGB")
|
| 53 |
+
orig_w, orig_h = img.size
|
| 54 |
+
|
| 55 |
+
# 2. Resize to 1024x1024 and normalize
|
| 56 |
+
resized = img.resize((1024, 1024), Image.Resampling.BILINEAR)
|
| 57 |
+
arr = np.array(resized, dtype=np.float32) / 255.0
|
| 58 |
+
|
| 59 |
+
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 60 |
+
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
| 61 |
+
norm = (arr - mean) / std
|
| 62 |
+
|
| 63 |
+
# 3. Shape to [1, 3, 1024, 1024]
|
| 64 |
+
tensor = np.transpose(norm, (2, 0, 1))[np.newaxis, ...]
|
| 65 |
+
|
| 66 |
+
# 4. Run inference
|
| 67 |
+
session = ort.InferenceSession("inspyrenet_swinb_1024.onnx", providers=["CPUExecutionProvider"])
|
| 68 |
+
out = session.run(None, {"input": tensor})[0]
|
| 69 |
+
|
| 70 |
+
# 5. Extract alpha and resize back to original size
|
| 71 |
+
alpha = (np.clip(out[0, 0], 0.0, 1.0) * 255.0).astype(np.uint8)
|
| 72 |
+
alpha_img = Image.fromarray(alpha, mode="L").resize((orig_w, orig_h), Image.Resampling.BILINEAR)
|
| 73 |
+
|
| 74 |
+
# 6. Save transparent cutout
|
| 75 |
+
cutout = img.convert("RGBA")
|
| 76 |
+
cutout.putalpha(alpha_img)
|
| 77 |
+
cutout.save("cutout.png")
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
## CLI Usage
|
| 81 |
+
|
| 82 |
+
This repository includes a ready-to-use Python script in `examples/infer.py`:
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
# Process a single image to a transparent PNG
|
| 86 |
+
python examples/infer.py --image photo.jpg --output cutout.png
|
| 87 |
+
|
| 88 |
+
# Process a single image on CUDA
|
| 89 |
+
python examples/infer.py --image photo.jpg --provider cuda
|
| 90 |
+
|
| 91 |
+
# Save only the grayscale alpha matte mask
|
| 92 |
+
python examples/infer.py --image photo.jpg --mask-only --output mask.png
|
| 93 |
+
|
| 94 |
+
# Batch process a folder of images
|
| 95 |
+
python examples/infer.py --dir path/to/images --output-dir path/to/cutouts
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
## Browser Usage (WebGPU & WASM)
|
| 99 |
+
|
| 100 |
+
You can run this model directly on client devices inside the browser using `onnxruntime-web`.
|
| 101 |
+
|
| 102 |
+
A complete demo application is provided in `examples/index.html`. To test it locally:
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
cd examples
|
| 106 |
+
python3 -m http.server 8000
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
Open `http://localhost:8000` in your browser. You can load the model via WebGPU or WASM, drag and drop any image, view the live alpha mask, and download transparent PNG cutouts.
|
| 110 |
+
|
| 111 |
+
Minimal JavaScript snippet:
|
| 112 |
+
|
| 113 |
+
```javascript
|
| 114 |
+
import * as ort from "onnxruntime-web";
|
| 115 |
+
|
| 116 |
+
// Initialize session with WebGPU
|
| 117 |
+
const session = await ort.InferenceSession.create("inspyrenet_swinb_1024.onnx", {
|
| 118 |
+
executionProviders: ["webgpu"]
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
// Prepare Float32Array tensor with shape [1, 3, 1024, 1024]
|
| 122 |
+
// normalized with ImageNet mean/std
|
| 123 |
+
const feeds = { input: inputTensor };
|
| 124 |
+
const results = await session.run(feeds);
|
| 125 |
+
const alphaData = results.alpha.data; // Float32Array of 1024 * 1024 alpha values
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
## Technical Notes
|
| 129 |
+
|
| 130 |
+
* **Input resolution:** The model expects an input tensor of `1x3x1024x1024`. Non-square images should be resized to 1024x1024 for inference, and the resulting alpha mask resized back to the original image dimensions.
|
| 131 |
+
* **Output range:** The output values represent foreground probability between `0.0` (background) and `1.0` (foreground). Soft edges (such as hair or transparent objects) contain fractional values between `0.0` and `1.0`.
|
| 132 |
+
* **Hardware acceleration:** On modern desktop GPUs (RTX series, Apple Silicon M-series), inference runs in 50 to 120 ms. On multi-core CPUs, inference typically completes in 500 to 1200 ms depending on thread count.
|
| 133 |
+
|
| 134 |
+
## Upstream Research & Attribution
|
| 135 |
+
|
| 136 |
+
This model is derived from the research project:
|
| 137 |
+
* **Paper:** *InSPyReNet: Incongruent Salient Object Detection* (ACM MM 2023)
|
| 138 |
+
* **Authors:** Taehun Kim, Kunhee Kim, Joonyeong Lee, Dongmin Cha, Jiho Lee, Daijin Kim
|
| 139 |
+
* **Upstream Code:** [github.com/plemeri/InSPyReNet](https://github.com/plemeri/InSPyReNet)
|
| 140 |
+
|
| 141 |
+
## License
|
| 142 |
+
|
| 143 |
+
The files in this repository are licensed under the Apache 2.0 License. See [LICENSE](LICENSE) for details. Upstream research code for InSPyReNet is licensed under the MIT License.
|
examples/index.html
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>InSPyReNet ONNX - Background Removal Demo</title>
|
| 7 |
+
<!-- ONNX Runtime Web -->
|
| 8 |
+
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.21.0/dist/ort.all.min.js"></script>
|
| 9 |
+
<style>
|
| 10 |
+
:root {
|
| 11 |
+
--bg: #121417;
|
| 12 |
+
--card-bg: #1a1d22;
|
| 13 |
+
--border: #2d3139;
|
| 14 |
+
--text: #f0f2f5;
|
| 15 |
+
--text-muted: #9ba3af;
|
| 16 |
+
--primary: #3b82f6;
|
| 17 |
+
--primary-hover: #2563eb;
|
| 18 |
+
--success: #10b981;
|
| 19 |
+
--surface: #22262e;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
* {
|
| 23 |
+
box-sizing: border-box;
|
| 24 |
+
margin: 0;
|
| 25 |
+
padding: 0;
|
| 26 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
body {
|
| 30 |
+
background-color: var(--bg);
|
| 31 |
+
color: var(--text);
|
| 32 |
+
min-height: 100vh;
|
| 33 |
+
display: flex;
|
| 34 |
+
flex-direction: column;
|
| 35 |
+
padding: 1.5rem;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
header {
|
| 39 |
+
max-width: 1100px;
|
| 40 |
+
margin: 0 auto 1.5rem auto;
|
| 41 |
+
width: 100%;
|
| 42 |
+
display: flex;
|
| 43 |
+
justify-content: space-between;
|
| 44 |
+
align-items: center;
|
| 45 |
+
flex-wrap: wrap;
|
| 46 |
+
gap: 1rem;
|
| 47 |
+
border-bottom: 1px solid var(--border);
|
| 48 |
+
padding-bottom: 1rem;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
.title-group h1 {
|
| 52 |
+
font-size: 1.5rem;
|
| 53 |
+
font-weight: 700;
|
| 54 |
+
letter-spacing: -0.02em;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
.title-group p {
|
| 58 |
+
color: var(--text-muted);
|
| 59 |
+
font-size: 0.9rem;
|
| 60 |
+
margin-top: 0.2rem;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
.status-badge {
|
| 64 |
+
display: inline-flex;
|
| 65 |
+
align-items: center;
|
| 66 |
+
gap: 0.5rem;
|
| 67 |
+
padding: 0.35rem 0.75rem;
|
| 68 |
+
background: var(--surface);
|
| 69 |
+
border: 1px solid var(--border);
|
| 70 |
+
border-radius: 9999px;
|
| 71 |
+
font-size: 0.8rem;
|
| 72 |
+
font-weight: 500;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
.status-dot {
|
| 76 |
+
width: 8px;
|
| 77 |
+
height: 8px;
|
| 78 |
+
border-radius: 50%;
|
| 79 |
+
background-color: #eab308;
|
| 80 |
+
}
|
| 81 |
+
.status-dot.ready { background-color: var(--success); }
|
| 82 |
+
.status-dot.error { background-color: #ef4444; }
|
| 83 |
+
|
| 84 |
+
main {
|
| 85 |
+
max-width: 1100px;
|
| 86 |
+
margin: 0 auto;
|
| 87 |
+
width: 100%;
|
| 88 |
+
display: grid;
|
| 89 |
+
grid-template-columns: 340px 1fr;
|
| 90 |
+
gap: 1.5rem;
|
| 91 |
+
flex: 1;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
@media (max-width: 840px) {
|
| 95 |
+
main {
|
| 96 |
+
grid-template-columns: 1fr;
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
.sidebar {
|
| 101 |
+
display: flex;
|
| 102 |
+
flex-direction: column;
|
| 103 |
+
gap: 1.25rem;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
.card {
|
| 107 |
+
background: var(--card-bg);
|
| 108 |
+
border: 1px solid var(--border);
|
| 109 |
+
border-radius: 10px;
|
| 110 |
+
padding: 1.25rem;
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
.card h2 {
|
| 114 |
+
font-size: 1rem;
|
| 115 |
+
font-weight: 600;
|
| 116 |
+
margin-bottom: 0.75rem;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
.control-group {
|
| 120 |
+
display: flex;
|
| 121 |
+
flex-direction: column;
|
| 122 |
+
gap: 0.5rem;
|
| 123 |
+
margin-bottom: 1rem;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
.control-group:last-child {
|
| 127 |
+
margin-bottom: 0;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
label {
|
| 131 |
+
font-size: 0.85rem;
|
| 132 |
+
color: var(--text-muted);
|
| 133 |
+
font-weight: 500;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
select, button, input[type="file"] {
|
| 137 |
+
font-size: 0.9rem;
|
| 138 |
+
color: var(--text);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
select {
|
| 142 |
+
background: var(--surface);
|
| 143 |
+
border: 1px solid var(--border);
|
| 144 |
+
border-radius: 6px;
|
| 145 |
+
padding: 0.6rem 0.75rem;
|
| 146 |
+
outline: none;
|
| 147 |
+
width: 100%;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
.btn {
|
| 151 |
+
background: var(--primary);
|
| 152 |
+
border: 1px solid transparent;
|
| 153 |
+
border-radius: 6px;
|
| 154 |
+
padding: 0.65rem 1rem;
|
| 155 |
+
color: white;
|
| 156 |
+
font-weight: 600;
|
| 157 |
+
cursor: pointer;
|
| 158 |
+
display: inline-flex;
|
| 159 |
+
align-items: center;
|
| 160 |
+
justify-content: center;
|
| 161 |
+
gap: 0.5rem;
|
| 162 |
+
transition: background-color 0.15s ease;
|
| 163 |
+
width: 100%;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
.btn:hover:not(:disabled) {
|
| 167 |
+
background: var(--primary-hover);
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
.btn:disabled {
|
| 171 |
+
opacity: 0.5;
|
| 172 |
+
cursor: not-allowed;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
.btn-secondary {
|
| 176 |
+
background: var(--surface);
|
| 177 |
+
border: 1px solid var(--border);
|
| 178 |
+
color: var(--text);
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
.btn-secondary:hover:not(:disabled) {
|
| 182 |
+
background: var(--border);
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
.dropzone {
|
| 186 |
+
border: 2px dashed var(--border);
|
| 187 |
+
border-radius: 8px;
|
| 188 |
+
padding: 1.5rem 1rem;
|
| 189 |
+
text-align: center;
|
| 190 |
+
cursor: pointer;
|
| 191 |
+
background: var(--surface);
|
| 192 |
+
transition: border-color 0.15s ease;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
.dropzone.dragover {
|
| 196 |
+
border-color: var(--primary);
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
.dropzone p {
|
| 200 |
+
font-size: 0.85rem;
|
| 201 |
+
color: var(--text-muted);
|
| 202 |
+
margin-top: 0.4rem;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
.workspace {
|
| 206 |
+
display: flex;
|
| 207 |
+
flex-direction: column;
|
| 208 |
+
gap: 1rem;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
.view-toggles {
|
| 212 |
+
display: flex;
|
| 213 |
+
gap: 0.5rem;
|
| 214 |
+
flex-wrap: wrap;
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
.tab-btn {
|
| 218 |
+
background: var(--surface);
|
| 219 |
+
border: 1px solid var(--border);
|
| 220 |
+
color: var(--text-muted);
|
| 221 |
+
padding: 0.45rem 0.9rem;
|
| 222 |
+
border-radius: 6px;
|
| 223 |
+
font-size: 0.85rem;
|
| 224 |
+
cursor: pointer;
|
| 225 |
+
font-weight: 500;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
.tab-btn.active {
|
| 229 |
+
background: var(--primary);
|
| 230 |
+
color: white;
|
| 231 |
+
border-color: var(--primary);
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
.preview-container {
|
| 235 |
+
background: var(--card-bg);
|
| 236 |
+
border: 1px solid var(--border);
|
| 237 |
+
border-radius: 10px;
|
| 238 |
+
min-height: 440px;
|
| 239 |
+
display: flex;
|
| 240 |
+
align-items: center;
|
| 241 |
+
justify-content: center;
|
| 242 |
+
position: relative;
|
| 243 |
+
overflow: hidden;
|
| 244 |
+
padding: 1rem;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
.checkerboard {
|
| 248 |
+
background-image:
|
| 249 |
+
linear-gradient(45deg, #1e2229 25%, transparent 25%),
|
| 250 |
+
linear-gradient(-45deg, #1e2229 25%, transparent 25%),
|
| 251 |
+
linear-gradient(45deg, transparent 75%, #1e2229 75%),
|
| 252 |
+
linear-gradient(-45deg, transparent 75%, #1e2229 75%);
|
| 253 |
+
background-size: 20px 20px;
|
| 254 |
+
background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
canvas {
|
| 258 |
+
max-width: 100%;
|
| 259 |
+
max-height: 600px;
|
| 260 |
+
object-fit: contain;
|
| 261 |
+
border-radius: 4px;
|
| 262 |
+
display: none;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
.placeholder-msg {
|
| 266 |
+
color: var(--text-muted);
|
| 267 |
+
text-align: center;
|
| 268 |
+
font-size: 0.95rem;
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
.meta-bar {
|
| 272 |
+
display: flex;
|
| 273 |
+
justify-content: space-between;
|
| 274 |
+
align-items: center;
|
| 275 |
+
font-size: 0.85rem;
|
| 276 |
+
color: var(--text-muted);
|
| 277 |
+
flex-wrap: wrap;
|
| 278 |
+
gap: 0.5rem;
|
| 279 |
+
}
|
| 280 |
+
</style>
|
| 281 |
+
</head>
|
| 282 |
+
<body>
|
| 283 |
+
|
| 284 |
+
<header>
|
| 285 |
+
<div class="title-group">
|
| 286 |
+
<h1>InSPyReNet ONNX Background Removal</h1>
|
| 287 |
+
<p>Client-side background matting powered by InSPyReNet Swin-B & ONNX Runtime Web</p>
|
| 288 |
+
</div>
|
| 289 |
+
<div class="status-badge">
|
| 290 |
+
<span id="status-dot" class="status-dot"></span>
|
| 291 |
+
<span id="status-text">Model not loaded</span>
|
| 292 |
+
</div>
|
| 293 |
+
</header>
|
| 294 |
+
|
| 295 |
+
<main>
|
| 296 |
+
<div class="sidebar">
|
| 297 |
+
<div class="card">
|
| 298 |
+
<h2>1. Model Setup</h2>
|
| 299 |
+
<div class="control-group">
|
| 300 |
+
<label for="backend-select">Execution Backend</label>
|
| 301 |
+
<select id="backend-select">
|
| 302 |
+
<option value="webgpu">WebGPU (Fastest)</option>
|
| 303 |
+
<option value="wasm">WASM (CPU Fallback)</option>
|
| 304 |
+
</select>
|
| 305 |
+
</div>
|
| 306 |
+
|
| 307 |
+
<div class="control-group">
|
| 308 |
+
<button id="load-model-btn" class="btn">Load Model</button>
|
| 309 |
+
</div>
|
| 310 |
+
|
| 311 |
+
<div class="control-group">
|
| 312 |
+
<label>Or select local .onnx file</label>
|
| 313 |
+
<input type="file" id="local-model-input" accept=".onnx" style="display: none;">
|
| 314 |
+
<button id="select-model-btn" class="btn btn-secondary">Choose .onnx File</button>
|
| 315 |
+
</div>
|
| 316 |
+
</div>
|
| 317 |
+
|
| 318 |
+
<div class="card">
|
| 319 |
+
<h2>2. Image Input</h2>
|
| 320 |
+
<div id="dropzone" class="dropzone">
|
| 321 |
+
<strong>Drag & drop an image</strong>
|
| 322 |
+
<p>or click to browse</p>
|
| 323 |
+
<input type="file" id="image-input" accept="image/*" style="display: none;">
|
| 324 |
+
</div>
|
| 325 |
+
|
| 326 |
+
<div class="control-group" style="margin-top: 1rem;">
|
| 327 |
+
<button id="run-btn" class="btn" disabled>Remove Background</button>
|
| 328 |
+
</div>
|
| 329 |
+
</div>
|
| 330 |
+
|
| 331 |
+
<div class="card">
|
| 332 |
+
<h2>3. Export</h2>
|
| 333 |
+
<button id="download-btn" class="btn btn-secondary" disabled>Download Cutout (PNG)</button>
|
| 334 |
+
</div>
|
| 335 |
+
</div>
|
| 336 |
+
|
| 337 |
+
<div class="workspace">
|
| 338 |
+
<div class="meta-bar">
|
| 339 |
+
<div class="view-toggles">
|
| 340 |
+
<button class="tab-btn active" data-view="cutout">Cutout</button>
|
| 341 |
+
<button class="tab-btn" data-view="mask">Alpha Mask</button>
|
| 342 |
+
<button class="tab-btn" data-view="original">Original</button>
|
| 343 |
+
</div>
|
| 344 |
+
<span id="timing-info">Ready</span>
|
| 345 |
+
</div>
|
| 346 |
+
|
| 347 |
+
<div class="preview-container checkerboard" id="preview-box">
|
| 348 |
+
<div id="placeholder" class="placeholder-msg">
|
| 349 |
+
Upload an image and load the model to preview results
|
| 350 |
+
</div>
|
| 351 |
+
<canvas id="output-canvas"></canvas>
|
| 352 |
+
</div>
|
| 353 |
+
</div>
|
| 354 |
+
</main>
|
| 355 |
+
|
| 356 |
+
<script>
|
| 357 |
+
let session = null;
|
| 358 |
+
let originalImage = null;
|
| 359 |
+
let alphaMaskData = null; // Uint8ClampedArray for 1024x1024 or rescaled
|
| 360 |
+
let originalWidth = 0;
|
| 361 |
+
let originalHeight = 0;
|
| 362 |
+
let currentView = 'cutout';
|
| 363 |
+
|
| 364 |
+
const statusDot = document.getElementById('status-dot');
|
| 365 |
+
const statusText = document.getElementById('status-text');
|
| 366 |
+
const loadModelBtn = document.getElementById('load-model-btn');
|
| 367 |
+
const selectModelBtn = document.getElementById('select-model-btn');
|
| 368 |
+
const localModelInput = document.getElementById('local-model-input');
|
| 369 |
+
const backendSelect = document.getElementById('backend-select');
|
| 370 |
+
const dropzone = document.getElementById('dropzone');
|
| 371 |
+
const imageInput = document.getElementById('image-input');
|
| 372 |
+
const runBtn = document.getElementById('run-btn');
|
| 373 |
+
const downloadBtn = document.getElementById('download-btn');
|
| 374 |
+
const canvas = document.getElementById('output-canvas');
|
| 375 |
+
const ctx = canvas.getContext('2d');
|
| 376 |
+
const placeholder = document.getElementById('placeholder');
|
| 377 |
+
const timingInfo = document.getElementById('timing-info');
|
| 378 |
+
const tabBtns = document.querySelectorAll('.tab-btn');
|
| 379 |
+
|
| 380 |
+
const MODEL_PATH = '../inspyrenet_swinb_1024.onnx';
|
| 381 |
+
const INPUT_SIZE = 1024;
|
| 382 |
+
|
| 383 |
+
function setStatus(text, state) {
|
| 384 |
+
statusText.textContent = text;
|
| 385 |
+
statusDot.className = 'status-dot ' + (state || '');
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
async function initSession(source) {
|
| 389 |
+
const backend = backendSelect.value;
|
| 390 |
+
setStatus(`Loading model with ${backend.toUpperCase()}...`, '');
|
| 391 |
+
loadModelBtn.disabled = true;
|
| 392 |
+
selectModelBtn.disabled = true;
|
| 393 |
+
|
| 394 |
+
try {
|
| 395 |
+
const options = {
|
| 396 |
+
executionProviders: [backend]
|
| 397 |
+
};
|
| 398 |
+
|
| 399 |
+
if (source instanceof ArrayBuffer) {
|
| 400 |
+
session = await ort.InferenceSession.create(source, options);
|
| 401 |
+
} else {
|
| 402 |
+
session = await ort.InferenceSession.create(source, options);
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
setStatus(`Model ready (${backend.toUpperCase()})`, 'ready');
|
| 406 |
+
if (originalImage) runBtn.disabled = false;
|
| 407 |
+
} catch (err) {
|
| 408 |
+
console.error('Session init error:', err);
|
| 409 |
+
setStatus('Failed to load: ' + err.message, 'error');
|
| 410 |
+
loadModelBtn.disabled = false;
|
| 411 |
+
selectModelBtn.disabled = false;
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
loadModelBtn.addEventListener('click', () => initSession(MODEL_PATH));
|
| 416 |
+
|
| 417 |
+
selectModelBtn.addEventListener('click', () => localModelInput.click());
|
| 418 |
+
localModelInput.addEventListener('change', async (e) => {
|
| 419 |
+
const file = e.target.files[0];
|
| 420 |
+
if (!file) return;
|
| 421 |
+
const buffer = await file.arrayBuffer();
|
| 422 |
+
await initSession(buffer);
|
| 423 |
+
});
|
| 424 |
+
|
| 425 |
+
dropzone.addEventListener('click', () => imageInput.click());
|
| 426 |
+
dropzone.addEventListener('dragover', (e) => {
|
| 427 |
+
e.preventDefault();
|
| 428 |
+
dropzone.classList.add('dragover');
|
| 429 |
+
});
|
| 430 |
+
dropzone.addEventListener('dragleave', () => dropzone.classList.remove('dragover'));
|
| 431 |
+
dropzone.addEventListener('drop', (e) => {
|
| 432 |
+
e.preventDefault();
|
| 433 |
+
dropzone.classList.remove('dragover');
|
| 434 |
+
if (e.dataTransfer.files.length) handleImageFile(e.dataTransfer.files[0]);
|
| 435 |
+
});
|
| 436 |
+
imageInput.addEventListener('change', (e) => {
|
| 437 |
+
if (e.target.files.length) handleImageFile(e.target.files[0]);
|
| 438 |
+
});
|
| 439 |
+
|
| 440 |
+
function handleImageFile(file) {
|
| 441 |
+
const reader = new FileReader();
|
| 442 |
+
reader.onload = (e) => {
|
| 443 |
+
const img = new Image();
|
| 444 |
+
img.onload = () => {
|
| 445 |
+
originalImage = img;
|
| 446 |
+
originalWidth = img.naturalWidth;
|
| 447 |
+
originalHeight = img.naturalHeight;
|
| 448 |
+
alphaMaskData = null;
|
| 449 |
+
renderOriginal();
|
| 450 |
+
if (session) runBtn.disabled = false;
|
| 451 |
+
downloadBtn.disabled = true;
|
| 452 |
+
timingInfo.textContent = `Image: ${originalWidth}x${originalHeight}px`;
|
| 453 |
+
};
|
| 454 |
+
img.src = e.target.result;
|
| 455 |
+
};
|
| 456 |
+
reader.readAsDataURL(file);
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
function renderOriginal() {
|
| 460 |
+
if (!originalImage) return;
|
| 461 |
+
placeholder.style.display = 'none';
|
| 462 |
+
canvas.style.display = 'block';
|
| 463 |
+
canvas.width = originalWidth;
|
| 464 |
+
canvas.height = originalHeight;
|
| 465 |
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 466 |
+
ctx.drawImage(originalImage, 0, 0);
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// Preprocessing for InSPyReNet Swin-B 1024
|
| 470 |
+
// Normalization: ImageNet mean [0.485, 0.456, 0.406], std [0.229, 0.224, 0.225]
|
| 471 |
+
function prepareInputTensor(img) {
|
| 472 |
+
const offCanvas = document.createElement('canvas');
|
| 473 |
+
offCanvas.width = INPUT_SIZE;
|
| 474 |
+
offCanvas.height = INPUT_SIZE;
|
| 475 |
+
const offCtx = offCanvas.getContext('2d');
|
| 476 |
+
offCtx.drawImage(img, 0, 0, INPUT_SIZE, INPUT_SIZE);
|
| 477 |
+
const imgData = offCtx.getImageData(0, 0, INPUT_SIZE, INPUT_SIZE).data;
|
| 478 |
+
|
| 479 |
+
const numPixels = INPUT_SIZE * INPUT_SIZE;
|
| 480 |
+
const floatData = new Float32Array(3 * numPixels);
|
| 481 |
+
|
| 482 |
+
const mean = [0.485, 0.456, 0.406];
|
| 483 |
+
const std = [0.229, 0.224, 0.225];
|
| 484 |
+
|
| 485 |
+
for (let i = 0; i < numPixels; i++) {
|
| 486 |
+
const r = imgData[i * 4] / 255.0;
|
| 487 |
+
const g = imgData[i * 4 + 1] / 255.0;
|
| 488 |
+
const b = imgData[i * 4 + 2] / 255.0;
|
| 489 |
+
|
| 490 |
+
floatData[i] = (r - mean[0]) / std[0]; // R channel
|
| 491 |
+
floatData[numPixels + i] = (g - mean[1]) / std[1]; // G channel
|
| 492 |
+
floatData[2 * numPixels + i] = (b - mean[2]) / std[2]; // B channel
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
return new ort.Tensor('float32', floatData, [1, 3, INPUT_SIZE, INPUT_SIZE]);
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
runBtn.addEventListener('click', async () => {
|
| 499 |
+
if (!session || !originalImage) return;
|
| 500 |
+
|
| 501 |
+
runBtn.disabled = true;
|
| 502 |
+
timingInfo.textContent = 'Running inference...';
|
| 503 |
+
|
| 504 |
+
const t0 = performance.now();
|
| 505 |
+
|
| 506 |
+
try {
|
| 507 |
+
const inputTensor = prepareInputTensor(originalImage);
|
| 508 |
+
const feeds = { input: inputTensor };
|
| 509 |
+
const results = await session.run(feeds);
|
| 510 |
+
|
| 511 |
+
const outputTensor = results[session.outputNames[0]];
|
| 512 |
+
const alphaFloat = outputTensor.data; // Float32Array of 1024*1024
|
| 513 |
+
|
| 514 |
+
// Render alpha to 1024x1024 offscreen canvas
|
| 515 |
+
const maskCanvas = document.createElement('canvas');
|
| 516 |
+
maskCanvas.width = INPUT_SIZE;
|
| 517 |
+
maskCanvas.height = INPUT_SIZE;
|
| 518 |
+
const maskCtx = maskCanvas.getContext('2d');
|
| 519 |
+
const maskImgData = maskCtx.createImageData(INPUT_SIZE, INPUT_SIZE);
|
| 520 |
+
|
| 521 |
+
for (let i = 0; i < alphaFloat.length; i++) {
|
| 522 |
+
const val = Math.min(255, Math.max(0, Math.round(alphaFloat[i] * 255)));
|
| 523 |
+
maskImgData.data[i * 4] = val;
|
| 524 |
+
maskImgData.data[i * 4 + 1] = val;
|
| 525 |
+
maskImgData.data[i * 4 + 2] = val;
|
| 526 |
+
maskImgData.data[i * 4 + 3] = 255;
|
| 527 |
+
}
|
| 528 |
+
maskCtx.putImageData(maskImgData, 0, 0);
|
| 529 |
+
|
| 530 |
+
// Resize mask back to original dimensions
|
| 531 |
+
const scaledMaskCanvas = document.createElement('canvas');
|
| 532 |
+
scaledMaskCanvas.width = originalWidth;
|
| 533 |
+
scaledMaskCanvas.height = originalHeight;
|
| 534 |
+
const scaledMaskCtx = scaledMaskCanvas.getContext('2d');
|
| 535 |
+
scaledMaskCtx.drawImage(maskCanvas, 0, 0, originalWidth, originalHeight);
|
| 536 |
+
|
| 537 |
+
alphaMaskData = scaledMaskCtx.getImageData(0, 0, originalWidth, originalHeight).data;
|
| 538 |
+
|
| 539 |
+
const elapsed = (performance.now() - t0).toFixed(1);
|
| 540 |
+
timingInfo.textContent = `Inference completed in ${elapsed}ms`;
|
| 541 |
+
|
| 542 |
+
currentView = 'cutout';
|
| 543 |
+
updateTabActive();
|
| 544 |
+
renderView();
|
| 545 |
+
|
| 546 |
+
downloadBtn.disabled = false;
|
| 547 |
+
} catch (err) {
|
| 548 |
+
console.error('Inference error:', err);
|
| 549 |
+
timingInfo.textContent = 'Error: ' + err.message;
|
| 550 |
+
} finally {
|
| 551 |
+
runBtn.disabled = false;
|
| 552 |
+
}
|
| 553 |
+
});
|
| 554 |
+
|
| 555 |
+
function renderView() {
|
| 556 |
+
if (!originalImage) return;
|
| 557 |
+
|
| 558 |
+
canvas.width = originalWidth;
|
| 559 |
+
canvas.height = originalHeight;
|
| 560 |
+
|
| 561 |
+
if (currentView === 'original' || !alphaMaskData) {
|
| 562 |
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 563 |
+
ctx.drawImage(originalImage, 0, 0);
|
| 564 |
+
return;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
if (currentView === 'mask') {
|
| 568 |
+
const maskImg = ctx.createImageData(originalWidth, originalHeight);
|
| 569 |
+
for (let i = 0; i < alphaMaskData.length; i += 4) {
|
| 570 |
+
const val = alphaMaskData[i];
|
| 571 |
+
maskImg.data[i] = val;
|
| 572 |
+
maskImg.data[i + 1] = val;
|
| 573 |
+
maskImg.data[i + 2] = val;
|
| 574 |
+
maskImg.data[i + 3] = 255;
|
| 575 |
+
}
|
| 576 |
+
ctx.putImageData(maskImg, 0, 0);
|
| 577 |
+
return;
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
// Cutout view
|
| 581 |
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 582 |
+
ctx.drawImage(originalImage, 0, 0);
|
| 583 |
+
const composite = ctx.getImageData(0, 0, originalWidth, originalHeight);
|
| 584 |
+
for (let i = 0; i < alphaMaskData.length; i += 4) {
|
| 585 |
+
composite.data[i + 3] = alphaMaskData[i]; // Apply mask to alpha channel
|
| 586 |
+
}
|
| 587 |
+
ctx.putImageData(composite, 0, 0);
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
function updateTabActive() {
|
| 591 |
+
tabBtns.forEach(btn => {
|
| 592 |
+
if (btn.dataset.view === currentView) {
|
| 593 |
+
btn.classList.add('active');
|
| 594 |
+
} else {
|
| 595 |
+
btn.classList.remove('active');
|
| 596 |
+
}
|
| 597 |
+
});
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
tabBtns.forEach(btn => {
|
| 601 |
+
btn.addEventListener('click', () => {
|
| 602 |
+
currentView = btn.dataset.view;
|
| 603 |
+
updateTabActive();
|
| 604 |
+
renderView();
|
| 605 |
+
});
|
| 606 |
+
});
|
| 607 |
+
|
| 608 |
+
downloadBtn.addEventListener('click', () => {
|
| 609 |
+
if (!alphaMaskData) return;
|
| 610 |
+
const prevView = currentView;
|
| 611 |
+
currentView = 'cutout';
|
| 612 |
+
renderView();
|
| 613 |
+
|
| 614 |
+
const link = document.createElement('a');
|
| 615 |
+
link.download = 'cutout.png';
|
| 616 |
+
link.href = canvas.toDataURL('image/png');
|
| 617 |
+
link.click();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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
PinkPixel InSPyReNet ONNX Background Removal Tool
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python infer.py --image path/to/input.jpg --output cutout.png
|
| 7 |
+
python infer.py --dir path/to/images --output-dir path/to/output
|
| 8 |
+
python infer.py --image path/to/input.jpg --mask-only --output mask.png
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import List, Tuple
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import onnxruntime as ort
|
| 23 |
+
except ImportError:
|
| 24 |
+
sys.exit(
|
| 25 |
+
"onnxruntime is required. Install it with:\n"
|
| 26 |
+
" pip install onnxruntime # for CPU\n"
|
| 27 |
+
" pip install onnxruntime-gpu # for CUDA"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# ImageNet normalization statistics
|
| 31 |
+
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 32 |
+
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
| 33 |
+
INPUT_SIZE = 1024
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def resolve_model_path(custom_path: str = None) -> Path:
|
| 37 |
+
if custom_path:
|
| 38 |
+
p = Path(custom_path)
|
| 39 |
+
if p.exists():
|
| 40 |
+
return p
|
| 41 |
+
sys.exit(f"Error: Specified model file not found at {custom_path}")
|
| 42 |
+
|
| 43 |
+
# Look in current directory or parent directory
|
| 44 |
+
candidates = [
|
| 45 |
+
Path("inspyrenet_swinb_1024.onnx"),
|
| 46 |
+
Path(__file__).resolve().parent / "inspyrenet_swinb_1024.onnx",
|
| 47 |
+
Path(__file__).resolve().parent.parent / "inspyrenet_swinb_1024.onnx",
|
| 48 |
+
]
|
| 49 |
+
for c in candidates:
|
| 50 |
+
if c.exists():
|
| 51 |
+
return c
|
| 52 |
+
|
| 53 |
+
sys.exit(
|
| 54 |
+
"Error: inspyrenet_swinb_1024.onnx not found. "
|
| 55 |
+
"Provide the path using --model <path>"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def create_session(model_path: Path, provider: str = "cpu") -> ort.InferenceSession:
|
| 60 |
+
providers = []
|
| 61 |
+
provider_lower = provider.lower()
|
| 62 |
+
if provider_lower == "cuda":
|
| 63 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 64 |
+
elif provider_lower == "coreml":
|
| 65 |
+
providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"]
|
| 66 |
+
elif provider_lower == "directml":
|
| 67 |
+
providers = ["DmlExecutionProvider", "CPUExecutionProvider"]
|
| 68 |
+
else:
|
| 69 |
+
providers = ["CPUExecutionProvider"]
|
| 70 |
+
|
| 71 |
+
sess_options = ort.SessionOptions()
|
| 72 |
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 73 |
+
return ort.InferenceSession(str(model_path), sess_options, providers=providers)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def preprocess_image(image: Image.Image) -> Tuple[np.ndarray, Tuple[int, int]]:
|
| 77 |
+
orig_w, orig_h = image.size
|
| 78 |
+
rgb_img = image.convert("RGB")
|
| 79 |
+
|
| 80 |
+
# Resize to model resolution
|
| 81 |
+
resized = rgb_img.resize((INPUT_SIZE, INPUT_SIZE), Image.Resampling.BILINEAR)
|
| 82 |
+
arr = np.array(resized, dtype=np.float32) / 255.0
|
| 83 |
+
|
| 84 |
+
# Apply ImageNet normalization: (x - mean) / std
|
| 85 |
+
norm = (arr - IMAGENET_MEAN) / IMAGENET_STD
|
| 86 |
+
|
| 87 |
+
# Transpose HWC -> CHW and add batch dimension -> NCHW
|
| 88 |
+
tensor = np.transpose(norm, (2, 0, 1))[np.newaxis, ...]
|
| 89 |
+
return tensor, (orig_w, orig_h)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def run_inference(
|
| 93 |
+
session: ort.InferenceSession,
|
| 94 |
+
tensor: np.ndarray,
|
| 95 |
+
orig_size: Tuple[int, int],
|
| 96 |
+
threshold: float = None,
|
| 97 |
+
) -> Image.Image:
|
| 98 |
+
input_name = session.get_inputs()[0].name
|
| 99 |
+
outputs = session.run(None, {input_name: tensor})
|
| 100 |
+
|
| 101 |
+
# Model output is alpha [1, 1, 1024, 1024]
|
| 102 |
+
alpha_map = outputs[0][0, 0]
|
| 103 |
+
alpha_map = np.clip(alpha_map, 0.0, 1.0)
|
| 104 |
+
|
| 105 |
+
if threshold is not None:
|
| 106 |
+
alpha_map = np.where(alpha_map >= threshold, 1.0, 0.0)
|
| 107 |
+
|
| 108 |
+
alpha_uint8 = (alpha_map * 255.0).astype(np.uint8)
|
| 109 |
+
orig_w, orig_h = orig_size
|
| 110 |
+
|
| 111 |
+
# Resize alpha mask back to original dimensions
|
| 112 |
+
alpha_img = Image.fromarray(alpha_uint8, mode="L").resize(
|
| 113 |
+
(orig_w, orig_h), Image.Resampling.BILINEAR
|
| 114 |
+
)
|
| 115 |
+
return alpha_img
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def process_file(
|
| 119 |
+
session: ort.InferenceSession,
|
| 120 |
+
image_path: Path,
|
| 121 |
+
output_path: Path,
|
| 122 |
+
mask_only: bool = False,
|
| 123 |
+
threshold: float = None,
|
| 124 |
+
):
|
| 125 |
+
t0 = time.perf_counter()
|
| 126 |
+
with Image.open(image_path) as img:
|
| 127 |
+
tensor, orig_size = preprocess_image(img)
|
| 128 |
+
alpha_mask = run_inference(session, tensor, orig_size, threshold=threshold)
|
| 129 |
+
|
| 130 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
if mask_only:
|
| 132 |
+
alpha_mask.save(output_path)
|
| 133 |
+
else:
|
| 134 |
+
rgba = img.convert("RGBA")
|
| 135 |
+
rgba.putalpha(alpha_mask)
|
| 136 |
+
rgba.save(output_path, format="PNG")
|
| 137 |
+
|
| 138 |
+
elapsed_ms = (time.perf_counter() - t0) * 1000
|
| 139 |
+
print(f"Processed {image_path.name} -> {output_path} ({elapsed_ms:.1f}ms)")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_image_files(directory: Path) -> List[Path]:
|
| 143 |
+
extensions = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff"}
|
| 144 |
+
return [p for p in directory.iterdir() if p.suffix.lower() in extensions and p.is_file()]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def main():
|
| 148 |
+
parser = argparse.ArgumentParser(
|
| 149 |
+
description="PinkPixel InSPyReNet ONNX Background Removal"
|
| 150 |
+
)
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"-i", "--image", type=str, help="Path to a single image file"
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument(
|
| 155 |
+
"-d", "--dir", type=str, help="Path to directory of images to process"
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"-o", "--output", type=str, help="Path for output file (single image)"
|
| 159 |
+
)
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--output-dir", type=str, help="Directory to save batch results"
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--model", type=str, default=None, help="Path to inspyrenet_swinb_1024.onnx"
|
| 165 |
+
)
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
"--provider",
|
| 168 |
+
type=str,
|
| 169 |
+
default="cpu",
|
| 170 |
+
choices=["cpu", "cuda", "coreml", "directml"],
|
| 171 |
+
help="ONNX execution provider (default: cpu)",
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"-m",
|
| 175 |
+
"--mask-only",
|
| 176 |
+
action="store_true",
|
| 177 |
+
help="Save grayscale alpha mask instead of transparent RGBA cutout",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"-t",
|
| 181 |
+
"--threshold",
|
| 182 |
+
type=float,
|
| 183 |
+
default=None,
|
| 184 |
+
help="Optional binarization threshold (e.g. 0.5) for a hard edge mask",
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
|
| 189 |
+
if not args.image and not args.dir:
|
| 190 |
+
parser.print_help()
|
| 191 |
+
sys.exit("\nError: Please specify either --image or --dir")
|
| 192 |
+
|
| 193 |
+
model_path = resolve_model_path(args.model)
|
| 194 |
+
print(f"Loading model: {model_path}")
|
| 195 |
+
session = create_session(model_path, provider=args.provider)
|
| 196 |
+
print(f"Session ready with providers: {session.get_providers()}")
|
| 197 |
+
|
| 198 |
+
if args.image:
|
| 199 |
+
img_path = Path(args.image)
|
| 200 |
+
if not img_path.exists():
|
| 201 |
+
sys.exit(f"Image not found: {img_path}")
|
| 202 |
+
|
| 203 |
+
if args.output:
|
| 204 |
+
out_path = Path(args.output)
|
| 205 |
+
else:
|
| 206 |
+
suffix = "_mask.png" if args.mask_only else "_cutout.png"
|
| 207 |
+
out_path = img_path.with_name(img_path.stem + suffix)
|
| 208 |
+
|
| 209 |
+
process_file(
|
| 210 |
+
session,
|
| 211 |
+
img_path,
|
| 212 |
+
out_path,
|
| 213 |
+
mask_only=args.mask_only,
|
| 214 |
+
threshold=args.threshold,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
elif args.dir:
|
| 218 |
+
in_dir = Path(args.dir)
|
| 219 |
+
if not in_dir.is_dir():
|
| 220 |
+
sys.exit(f"Directory not found: {in_dir}")
|
| 221 |
+
|
| 222 |
+
out_dir = Path(args.output_dir) if args.output_dir else in_dir / "cutouts"
|
| 223 |
+
files = get_image_files(in_dir)
|
| 224 |
+
if not files:
|
| 225 |
+
sys.exit(f"No valid image files found in {in_dir}")
|
| 226 |
+
|
| 227 |
+
print(f"Found {len(files)} images to process...")
|
| 228 |
+
for f in sorted(files):
|
| 229 |
+
suffix = "_mask.png" if args.mask_only else ".png"
|
| 230 |
+
out_path = out_dir / (f.stem + suffix)
|
| 231 |
+
process_file(
|
| 232 |
+
session,
|
| 233 |
+
f,
|
| 234 |
+
out_path,
|
| 235 |
+
mask_only=args.mask_only,
|
| 236 |
+
threshold=args.threshold,
|
| 237 |
+
)
|
| 238 |
+
print("Batch processing complete.")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
main()
|
inspyrenet_swinb_1024.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3f81b9ff32d84cfc7e577450b5d53ad8ddd0b9f12109747a1f2e6b984386aa97
|
| 3 |
+
size 374112036
|