Skip to content

armgit / rembg

Public Imported from GitHub
0

Rembg is a tool to remove images background

Resize the u2net_cloth_seg label map with nearest neighbour (#865)

3475017203-hue2fa27e870b1f
diff --git a/rembg/sessions/u2net_cloth_seg.py b/rembg/sessions/u2net_cloth_seg.py
index e5e1329..58baf18 100644
--- a/rembg/sessions/u2net_cloth_seg.py
+++ b/rembg/sessions/u2net_cloth_seg.py
@@ -99,7 +99,9 @@ class Unet2ClothSession(BaseSession):
pred = np.squeeze(pred, 0)
mask = Image.fromarray(pred.astype("uint8"), mode="L")
- mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+ # The mask holds class labels, so it must not be interpolated: LANCZOS
+ # turns a boundary between classes 1 and 3 into a line of class 2.
+ mask = mask.resize(img.size, Image.Resampling.NEAREST)
masks = []
diff --git a/tests/test_cloth_seg_resize.py b/tests/test_cloth_seg_resize.py
new file mode 100644
index 0000000..6c53866
--- /dev/null
+++ b/tests/test_cloth_seg_resize.py
@@ -0,0 +1,36 @@
+import numpy as np
+import pytest
+from PIL import Image
+
+from rembg.sessions.u2net_cloth_seg import Unet2ClothSession
+
+
+class FakeInput:
+ name = "input"
+
+
+class FakeInferenceSession:
+ """Predicts upper cloth (1) on the left and full cloth (3) on the right."""
+
+ def get_inputs(self):
+ return [FakeInput()]
+
+ def run(self, output_names, feeds):
+ logits = np.zeros((1, 4, 768, 768), dtype=np.float32)
+ logits[0, 1, :, :383] = 10
+ logits[0, 3, :, 383:] = 10
+ return [logits]
+
+
[email protected]("size", [(1234, 900), (500, 400), (3000, 2000)])
+def test_cloth_seg_does_not_mix_labels_when_resizing(size):
+ session = Unet2ClothSession.__new__(Unet2ClothSession)
+ session.inner_session = FakeInferenceSession()
+
+ upper, lower, full = session.predict(Image.new("RGB", size))
+
+ # No lower cloth was predicted, so its mask must stay empty instead of
+ # picking up the interpolated boundary between classes 1 and 3.
+ assert not np.asarray(lower).any()
+ assert np.asarray(upper).any()
+ assert np.asarray(full).any()