Upload 6 files
Browse files- LICENSE +189 -0
- README.md +128 -3
- gitattributes +35 -0
- model.onnx +3 -0
- requirements.txt +7 -0
- utils.py +148 -0
LICENSE
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://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 granting the License.
|
13 |
+
|
14 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
15 |
+
other entities that control, are controlled by, or are under common
|
16 |
+
control with that entity. For the purposes of the definition of
|
17 |
+
"control", an entity controls another entity when such entity:
|
18 |
+
(i) has the power, direct or indirect, to cause the direction or
|
19 |
+
management of such other entity, whether by contract or otherwise,
|
20 |
+
(ii) owns fifty percent (50%) or more of the outstanding shares, or
|
21 |
+
(iii) has 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" 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" 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 |
+
(which shall not include communication that is conspicuously
|
39 |
+
marked or otherwise designated in writing by the copyright owner
|
40 |
+
as "Not a Contribution").
|
41 |
+
|
42 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
43 |
+
form, that is based upon (or derived from) the Work and for which the
|
44 |
+
editorial revisions, annotations, elaborations, or other modifications
|
45 |
+
represent, as a whole, an original work of authorship. For the purposes
|
46 |
+
of this License, Derivative Works shall not include works that remain
|
47 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
48 |
+
the Work and derivative works thereof.
|
49 |
+
|
50 |
+
"Contribution" shall mean any work of authorship, including
|
51 |
+
the original version of the Work and any modifications or additions
|
52 |
+
to that Work or Derivative Works thereof, that is intentionally
|
53 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
54 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
55 |
+
the copyright owner. For the purposes of the definition of "Contribution",
|
56 |
+
any such Contribution intentionally submitted for inclusion in the Work
|
57 |
+
by You to the Licensor shall be deemed to have been made under the
|
58 |
+
terms and conditions of this License, without any additional terms or
|
59 |
+
conditions. Notwithstanding the above, nothing herein shall supersede or
|
60 |
+
modify the terms of any separate license agreement you may have executed
|
61 |
+
with Licensor regarding such Contributions.
|
62 |
+
|
63 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
64 |
+
this License, each Contributor hereby grants to You a perpetual,
|
65 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
66 |
+
copyright license to use, reproduce, modify, merge, publish,
|
67 |
+
distribute, sublicense, and/or sell copies of the Work, and to
|
68 |
+
permit persons to whom the Work is furnished to do so, subject to
|
69 |
+
the following conditions:
|
70 |
+
|
71 |
+
The above copyright notice and this permission notice shall be
|
72 |
+
included in all copies or substantial portions of the Work.
|
73 |
+
|
74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77 |
+
(except as stated in this section) patent license to make, have made,
|
78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79 |
+
where such license applies only to those patent claims licensable
|
80 |
+
by such Contributor that are necessarily infringed by their
|
81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
83 |
+
institute patent litigation against any entity (including a
|
84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85 |
+
or a Contribution incorporated within the Work constitutes direct
|
86 |
+
or contributory patent infringement, then any patent licenses
|
87 |
+
granted to You under this License for that Work shall terminate
|
88 |
+
as of the date such litigation is filed.
|
89 |
+
|
90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
91 |
+
Work or Derivative Works thereof in any medium, with or without
|
92 |
+
modifications, and in Source or Object form, provided that You
|
93 |
+
meet the following conditions:
|
94 |
+
|
95 |
+
(a) You must give any other recipients of the Work or
|
96 |
+
Derivative Works a copy of this License; and
|
97 |
+
|
98 |
+
(b) You must cause any modified files to carry prominent notices
|
99 |
+
stating that You changed the files; and
|
100 |
+
|
101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
102 |
+
that You distribute, all copyright, trademark, patent,
|
103 |
+
and attribution notices from the Source form of the Work,
|
104 |
+
excluding those notices that do not pertain to any part of
|
105 |
+
the Derivative Works; and
|
106 |
+
|
107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108 |
+
distribution, then any Derivative Works that You distribute must
|
109 |
+
include a readable copy of the attribution notices contained
|
110 |
+
within such NOTICE file, excluding those notices that do not
|
111 |
+
pertain to any part of the Derivative Works, in at least one
|
112 |
+
of the following places: within a NOTICE text file distributed
|
113 |
+
as part of the Derivative Works; within the Source form or
|
114 |
+
documentation, if provided along with the Derivative Works; or,
|
115 |
+
within a display generated by the Derivative Works, if and
|
116 |
+
wherever such third-party notices normally appear. The contents
|
117 |
+
of the NOTICE file are for informational purposes only and
|
118 |
+
do not modify the License. You may add Your own attribution
|
119 |
+
notices within Derivative Works that You distribute, alongside
|
120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
121 |
+
that such additional attribution notices cannot be construed
|
122 |
+
as modifying the License.
|
123 |
+
|
124 |
+
You may add Your own copyright notice to Your modifications and
|
125 |
+
may provide additional or different license terms and conditions
|
126 |
+
for use, reproduction, or distribution of Your modifications, or
|
127 |
+
for any such Derivative Works as a whole, provided Your use,
|
128 |
+
reproduction, and distribution of the Work otherwise complies with
|
129 |
+
the conditions stated in this License.
|
130 |
+
|
131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
133 |
+
by You to the Licensor shall be under the terms and conditions of
|
134 |
+
this License, without any additional terms or conditions.
|
135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136 |
+
the terms of any separate license agreement you may have executed
|
137 |
+
with Licensor regarding such Contributions.
|
138 |
+
|
139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
141 |
+
except as required for reasonable and customary use in describing the
|
142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
143 |
+
|
144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145 |
+
agreed to in writing, Licensor provides the Work (and each
|
146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148 |
+
implied, including, without limitation, any warranties or conditions
|
149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151 |
+
appropriateness of using or redistributing the Work and assume any
|
152 |
+
risks associated with Your exercise of permissions under this License.
|
153 |
+
|
154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
155 |
+
whether in tort (including negligence), contract, or otherwise,
|
156 |
+
unless required by applicable law (such as deliberate and grossly
|
157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158 |
+
liable to You for damages, including any direct, indirect, special,
|
159 |
+
incidental, or consequential damages of any character arising as a
|
160 |
+
result of this License or out of the use or inability to use the
|
161 |
+
Work (including but not limited to damages for loss of goodwill,
|
162 |
+
work stoppage, computer failure or malfunction, or any and all
|
163 |
+
other commercial damages or losses), even if such Contributor
|
164 |
+
has been advised of the possibility of such damages.
|
165 |
+
|
166 |
+
9. Accepting Warranty or Support. You are not required to accept
|
167 |
+
warranty or support for the Work under this License. However, if You
|
168 |
+
choose to accept warranty or support, You may act only on Your own
|
169 |
+
behalf and on Your sole responsibility, not on behalf of any other
|
170 |
+
Contributor, and only if You agree to indemnify, defend, and hold each
|
171 |
+
Contributor harmless for any liability incurred by, or claims asserted
|
172 |
+
against, such Contributor by reason of your accepting any such warranty
|
173 |
+
or support.
|
174 |
+
|
175 |
+
END OF TERMS AND CONDITIONS
|
176 |
+
|
177 |
+
Copyright 2025 Trendyol
|
178 |
+
|
179 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
180 |
+
you may not use this file except in compliance with the License.
|
181 |
+
You may obtain a copy of the License at
|
182 |
+
|
183 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
184 |
+
|
185 |
+
Unless required by applicable law or agreed to in writing, software
|
186 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
187 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
188 |
+
See the License for the specific language governing permissions and
|
189 |
+
limitations under the License.
|
README.md
CHANGED
@@ -1,3 +1,128 @@
|
|
1 |
-
---
|
2 |
-
license:
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
pipeline_tag: image-segmentation
|
4 |
+
language: []
|
5 |
+
base_model: isnet-general-use.pth
|
6 |
+
model_type: ty_fashion_bg_remover
|
7 |
+
tags:
|
8 |
+
- computer-vision
|
9 |
+
- image-background-removal
|
10 |
+
- image-matting
|
11 |
+
- e-commerce
|
12 |
+
- is-net
|
13 |
+
---
|
14 |
+
|
15 |
+
# TY Fashion Background Remover
|
16 |
+
|
17 |
+
_TY Fashion Background Remover is an IS-Net–based human segmentation and background-removal model designed to automatically detect and isolate people in images. It produces high-quality binary/alpha masks and trimmed RGBA composites intended for downstream editing, compositing, and automated image pipelines. Although optimized for fashion photography, it is suitable for any application where the image contains human and the goal is to separate them cleanly from the background._
|
18 |
+
|
19 |
+
## Model Details
|
20 |
+
|
21 |
+
- **Architecture**: IS-Net
|
22 |
+
- **Objective**: Fine-tuning isnet-general-use model with TY fashion images to better performance of fashion images
|
23 |
+
- **Training Data**: Large-scale Trendyol fashion product image dataset containing human models
|
24 |
+
- **Hardware**: Multi-GPU training with PyTorch
|
25 |
+
- **Framework**: PyTorch
|
26 |
+
|
27 |
+
## Intended Use
|
28 |
+
|
29 |
+
- Automatically remove backgrounds from images containing human, isolating the subject for further editing, compositing, or analysis.
|
30 |
+
|
31 |
+
- Designed for use in applications such as e-commerce product photography, fashion catalogs, profile pictures, and creative media projects where the human subject needs to be cleanly separated from the background.
|
32 |
+
|
33 |
+
- Optimized for images with clear human presence; not intended for objects, animals, or scenes without people.
|
34 |
+
|
35 |
+
- Can be used as a preprocessing step for downstream tasks like virtual try-on, background replacement, and image-based content generation.
|
36 |
+
|
37 |
+
## Usage
|
38 |
+
|
39 |
+
Complete example to load the model, remove background of an image, and save the results:
|
40 |
+
|
41 |
+
```python
|
42 |
+
"""
|
43 |
+
ONNX inference script for image segmentation model.
|
44 |
+
|
45 |
+
This script loads an ONNX model and performs inference on an input image to generate
|
46 |
+
an alpha mask. The mask is combined with the RGB image and saved as output.
|
47 |
+
"""
|
48 |
+
|
49 |
+
import onnxruntime as ort
|
50 |
+
from utils import process_image
|
51 |
+
|
52 |
+
if __name__ == "__main__":
|
53 |
+
MODEL_PATH = "model.onnx"
|
54 |
+
SRC = "https://cdn.dsmcdn.com/ty184/product/media/images/20210924/23/136268224/224296134/1/1_org_zoom.jpg"
|
55 |
+
OUTPUT_FILE = "out.png"
|
56 |
+
|
57 |
+
# Initialize ONNX runtime session with CUDA and CPU providers
|
58 |
+
ort_session = ort.InferenceSession(
|
59 |
+
MODEL_PATH,
|
60 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
|
61 |
+
)
|
62 |
+
|
63 |
+
process_image(SRC, ort_session, MODEL_PATH, OUTPUT_FILE)
|
64 |
+
```
|
65 |
+
|
66 |
+
## Model Performance
|
67 |
+
|
68 |
+
- **Achieve high-accuracy image matting**: Especially for intricate details on human models, such as hair and clothing textures.
|
69 |
+
|
70 |
+
### Training Configuration
|
71 |
+
|
72 |
+
- **Backbone**: IS-Net general use model trained on DIS dataset V1.0: DIS5K
|
73 |
+
- **Model Input Size**: 1800x1200
|
74 |
+
- **Training Framework**: Torch 1.13.1
|
75 |
+
|
76 |
+
## Limitations
|
77 |
+
|
78 |
+
- **Domain Specificity**: Optimized for e-commerce fashion product images with human models included; may not generalize well to other image domains
|
79 |
+
- **Image Quality**: Performance may degrade on low-quality, heavily compressed, or significantly distorted images
|
80 |
+
- **Category Bias**: Performance may vary across different product categories based on training data distribution
|
81 |
+
|
82 |
+
## Ethical Considerations
|
83 |
+
|
84 |
+
- **Commercial Use**: Designed for e-commerce applications; consider potential impacts on market competition
|
85 |
+
- **Privacy**: Ensure compliance with data protection regulations when processing product images
|
86 |
+
- **Fairness**: Monitor for biased similarity judgments across different product categories or brands
|
87 |
+
|
88 |
+
## Citation
|
89 |
+
|
90 |
+
```bibtex
|
91 |
+
@misc{trendyol2025fashionbgremover,
|
92 |
+
title={TY Fashion Background Remover},
|
93 |
+
author={Trendyol Data Science Team},
|
94 |
+
year={2025},
|
95 |
+
howpublished={\url{https://huggingface.co/trendyol/ty-fashion-bg-remover}}
|
96 |
+
}
|
97 |
+
```
|
98 |
+
|
99 |
+
## Model Card Authors
|
100 |
+
|
101 |
+
- Trendyol Data Science Team
|
102 |
+
|
103 |
+
## License
|
104 |
+
|
105 |
+
This model is released by Trendyol as a source-available, non-open-source model.
|
106 |
+
|
107 |
+
### You are allowed to:
|
108 |
+
|
109 |
+
- View, download, and evaluate the model weights.
|
110 |
+
- Use the model for non-commercial research and internal testing.
|
111 |
+
- Use the model or its derivatives for commercial purposes, provided that:
|
112 |
+
- You cite Trendyol as the original model creator.
|
113 |
+
- You notify Trendyol in advance via [[email protected]] or other designated contact.
|
114 |
+
|
115 |
+
### You are not allowed to:
|
116 |
+
|
117 |
+
- Redistribute or host the model or its derivatives on third-party platforms without prior written consent from Trendyol.
|
118 |
+
- Use the model in applications violating ethical standards, including but not limited to surveillance, misinformation, or harm to individuals or groups.
|
119 |
+
|
120 |
+
By downloading or using this model, you agree to the terms above.
|
121 |
+
|
122 |
+
© 2025 Trendyol Teknoloji A.Ş. All rights reserved.
|
123 |
+
|
124 |
+
See the [LICENSE](LICENSE) file for more details.
|
125 |
+
|
126 |
+
---
|
127 |
+
|
128 |
+
_For technical support or questions about this model, please contact the Trendyol Data Science team._
|
gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
model.onnx
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b9ef43bab5c1a5538916d31066d5ae843a2200d1fd83ed5bac320643076332d0
|
3 |
+
size 176215273
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch==2.7.1
|
2 |
+
torchvision==0.22.1
|
3 |
+
opencv-python==4.12.0.88
|
4 |
+
numpy
|
5 |
+
requests
|
6 |
+
Pillow
|
7 |
+
onnxruntime==1.22.1
|
utils.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import requests
|
4 |
+
from PIL import Image
|
5 |
+
from io import BytesIO
|
6 |
+
import torch
|
7 |
+
from pathlib import Path
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from typing import Dict, Any, List, Union, Tuple
|
10 |
+
from torchvision.transforms.functional import normalize
|
11 |
+
|
12 |
+
INPUT_SIZE = [1200, 1800]
|
13 |
+
|
14 |
+
def keep_large_components(a: np.ndarray) -> np.ndarray:
|
15 |
+
"""Remove small connected components from a binary mask, keeping only large regions.
|
16 |
+
|
17 |
+
Args:
|
18 |
+
a: Input binary mask as numpy array of shape (H,W) or (H,W,1)
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
Processed mask with only large connected components remaining, shape (H,W,1)
|
22 |
+
"""
|
23 |
+
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(9, 9))
|
24 |
+
a_mask = (a > 25).astype(np.uint8) * 255
|
25 |
+
|
26 |
+
# Apply the Component analysis function
|
27 |
+
analysis = cv2.connectedComponentsWithStats(a_mask, 4, cv2.CV_32S)
|
28 |
+
(totalLabels, label_ids, values, centroid) = analysis
|
29 |
+
|
30 |
+
# Find the components to be kept
|
31 |
+
h, w = a.shape[:2]
|
32 |
+
area_limit = 50000 * (h * w) / (INPUT_SIZE[1] * INPUT_SIZE[0])
|
33 |
+
i_to_keep = []
|
34 |
+
for i in range(1, totalLabels):
|
35 |
+
area = values[i, cv2.CC_STAT_AREA]
|
36 |
+
if area > area_limit:
|
37 |
+
i_to_keep.append(i)
|
38 |
+
|
39 |
+
if len(i_to_keep) > 0:
|
40 |
+
# Or masks to be kept
|
41 |
+
final_mask = np.zeros_like(a, dtype=np.uint8)
|
42 |
+
for i in i_to_keep:
|
43 |
+
componentMask = (label_ids == i).astype("uint8") * 255
|
44 |
+
final_mask = cv2.bitwise_or(final_mask, componentMask)
|
45 |
+
|
46 |
+
# Remove other components
|
47 |
+
# Keep edges
|
48 |
+
final_mask = cv2.dilate(final_mask, dilate_kernel, iterations = 2)
|
49 |
+
a = cv2.bitwise_and(a, final_mask)
|
50 |
+
a = a.reshape((a.shape[0], a.shape[1], 1))
|
51 |
+
|
52 |
+
return a
|
53 |
+
|
54 |
+
def read_img(img: Union[str, Path]) -> np.ndarray:
|
55 |
+
"""Read an image from a URL or local path.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
img: URL or file path to image
|
59 |
+
|
60 |
+
Returns:
|
61 |
+
Image as numpy array in RGB format with shape (H,W,3)
|
62 |
+
"""
|
63 |
+
if img[0: 4] == 'http':
|
64 |
+
response = requests.get(img)
|
65 |
+
im = np.asarray(Image.open(BytesIO(response.content)))
|
66 |
+
|
67 |
+
else:
|
68 |
+
im = cv2.imread(str(img))
|
69 |
+
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
|
70 |
+
|
71 |
+
return im
|
72 |
+
|
73 |
+
def preprocess_input(im: np.ndarray) -> torch.Tensor:
|
74 |
+
"""Preprocess image for model input.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
im: Input image as numpy array of shape (H,W,C)
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
Preprocessed image as normalized torch tensor of shape (1,3,H,W)
|
81 |
+
"""
|
82 |
+
if len(im.shape) < 3:
|
83 |
+
im = im[:, :, np.newaxis]
|
84 |
+
|
85 |
+
if im.shape[2] == 4: # if image has alpha channel, remove it
|
86 |
+
im = im[:,:,:3]
|
87 |
+
|
88 |
+
im_tensor = torch.tensor(im, dtype=torch.float32).permute(2,0,1)
|
89 |
+
im_tensor = F.upsample(torch.unsqueeze(im_tensor,0), INPUT_SIZE, mode="bilinear").type(torch.uint8)
|
90 |
+
image = torch.divide(im_tensor,255.0)
|
91 |
+
image = normalize(image,[0.5,0.5,0.5],[1.0,1.0,1.0])
|
92 |
+
|
93 |
+
if torch.cuda.is_available():
|
94 |
+
image=image.cuda()
|
95 |
+
|
96 |
+
return image
|
97 |
+
|
98 |
+
def postprocess_output(result: np.ndarray, orig_im_shape: Tuple[int, int]) -> np.ndarray:
|
99 |
+
"""Postprocess ONNX model output.
|
100 |
+
|
101 |
+
Args:
|
102 |
+
result: Model output as numpy array of shape (1,1,H,W)
|
103 |
+
orig_im_shape: Original image dimensions (height, width)
|
104 |
+
|
105 |
+
Returns:
|
106 |
+
Processed binary mask as numpy array of shape (H,W,1)
|
107 |
+
"""
|
108 |
+
result = torch.squeeze(F.upsample(
|
109 |
+
torch.from_numpy(result).unsqueeze(0), (orig_im_shape), mode='bilinear'), 0)
|
110 |
+
ma = torch.max(result)
|
111 |
+
mi = torch.min(result)
|
112 |
+
result = (result-mi)/(ma-mi)
|
113 |
+
|
114 |
+
# a is alpha channel. 255 means foreground, 0 means background.
|
115 |
+
a = (result*255).permute(1,2,0).cpu().data.numpy().astype(np.uint8)
|
116 |
+
|
117 |
+
# postprocessing
|
118 |
+
a = keep_large_components(a)
|
119 |
+
|
120 |
+
return a
|
121 |
+
|
122 |
+
def process_image(src: Union[str, Path], ort_session: Any, model_path: Union[str, Path], outname: str) -> None:
|
123 |
+
"""Process an image through ONNX model to generate alpha mask and save result.
|
124 |
+
|
125 |
+
Args:
|
126 |
+
src: Source image URL or path
|
127 |
+
ort_session: ONNX runtime inference session
|
128 |
+
model_path: Path to ONNX model file
|
129 |
+
outname: Output filename for saving result
|
130 |
+
|
131 |
+
Returns:
|
132 |
+
None
|
133 |
+
"""
|
134 |
+
# Load and preprocess image
|
135 |
+
image_orig = read_img(src)
|
136 |
+
image = preprocess_input(image_orig)
|
137 |
+
|
138 |
+
# Prepare ONNX input
|
139 |
+
inputs: Dict[str, Any] = {ort_session.get_inputs()[0].name: image.numpy()}
|
140 |
+
|
141 |
+
# Get ONNX output and post-process
|
142 |
+
result = ort_session.run(None, inputs)[0][0]
|
143 |
+
alpha = postprocess_output(result, (image_orig.shape[0], image_orig.shape[1]))
|
144 |
+
|
145 |
+
# Combine RGB image with alpha mask and save
|
146 |
+
img_w_alpha = np.dstack((cv2.cvtColor(image_orig, cv2.COLOR_BGR2RGB), alpha))
|
147 |
+
cv2.imwrite(outname, img_w_alpha)
|
148 |
+
print(f"Saved: {outname}")
|