Background removal; fallback to CPU if GPU fails. Returns RGBA PIL.
(self, image: Image.Image)
| 158 | return alpha_resized |
| 159 | |
| 160 | def predict(self, image: Image.Image) -> Image.Image: |
| 161 | """Background removal; fallback to CPU if GPU fails. Returns RGBA PIL.""" |
| 162 | if not self._is_loaded: |
| 163 | self.load() |
| 164 | |
| 165 | # Model not loaded: return fallback |
| 166 | if self._session is None: |
| 167 | return image.convert("RGBA") |
| 168 | |
| 169 | # To numpy |
| 170 | img = np.array(image) |
| 171 | |
| 172 | # Preprocess |
| 173 | img_input, original_size = self._preprocess(img) |
| 174 | |
| 175 | try: |
| 176 | pred = self._session.run([self._output_name], {self._input_name: img_input})[0] |
| 177 | except Exception as e: |
| 178 | # GPU failed, try CPU |
| 179 | if hasattr(self, '_providers') and 'CUDAExecutionProvider' in self._providers: |
| 180 | print(f"[RMBGModel] GPU inference failed (OOM), switching to CPU...") |
| 181 | |
| 182 | try: |
| 183 | # Release session |
| 184 | self._session = None |
| 185 | |
| 186 | # New CPU session |
| 187 | session_options = ort.SessionOptions() |
| 188 | session_options.log_severity_level = 3 |
| 189 | |
| 190 | self._session = ort.InferenceSession( |
| 191 | self.model_path, |
| 192 | providers=['CPUExecutionProvider'], |
| 193 | sess_options=session_options |
| 194 | ) |
| 195 | self._providers = ['CPUExecutionProvider'] |
| 196 | |
| 197 | # Retry |
| 198 | pred = self._session.run([self._output_name], {self._input_name: img_input})[0] |
| 199 | print("[RMBGModel] CPU inference successful") |
| 200 | |
| 201 | except Exception as e2: |
| 202 | print(f"[RMBGModel] CPU inference also failed: {e2}") |
| 203 | print("[RMBGModel] Falling back to no background removal") |
| 204 | return image.convert("RGBA") |
| 205 | else: |
| 206 | print(f"[RMBGModel] Inference failed: {e}, using fallback (no background removal)") |
| 207 | return image.convert("RGBA") |
| 208 | |
| 209 | # Postprocess alpha |
| 210 | alpha = self._postprocess(pred, original_size) |
| 211 | |
| 212 | # Merge alpha -> RGBA |
| 213 | img_rgba = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA) |
| 214 | img_rgba[:, :, 3] = alpha |
| 215 | |
| 216 | # To PIL |
| 217 | return Image.fromarray(img_rgba) |
no test coverage detected