test_pipelines_image_segmentation.py 15.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import hashlib
import unittest

18
import datasets
19
from datasets import load_dataset
20

21
22
from transformers import (
    MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
23
    MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
24
    MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
25
26
    AutoFeatureExtractor,
    AutoModelForImageSegmentation,
27
    AutoModelForInstanceSegmentation,
28
    DetrForSegmentation,
29
    ImageSegmentationPipeline,
30
    MaskFormerForInstanceSegmentation,
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
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY, PipelineTestCaseMeta


if is_vision_available():
    from PIL import Image
else:

    class Image:
        @staticmethod
        def open(*args, **kwargs):
            pass


57
58
59
60
61
def hashimage(image: Image) -> str:
    m = hashlib.md5(image.tobytes())
    return m.hexdigest()


62
63
64
65
66
@require_vision
@require_timm
@require_torch
@is_pipeline_test
class ImageSegmentationPipelineTests(unittest.TestCase, metaclass=PipelineTestCaseMeta):
67
68
69
70
71
72
    model_mapping = {
        k: v
        for k, v in (
            list(MODEL_FOR_IMAGE_SEGMENTATION_MAPPING.items()) if MODEL_FOR_IMAGE_SEGMENTATION_MAPPING else []
        )
        + (MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING.items() if MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING else [])
73
        + (MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING.items() if MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING else [])
74
    }
75

76
    def get_test_pipeline(self, model, tokenizer, feature_extractor):
77
        image_segmenter = ImageSegmentationPipeline(model=model, feature_extractor=feature_extractor)
78
79
80
81
82
83
        return image_segmenter, [
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
        ]

    def run_pipeline_test(self, image_segmenter, examples):
84
        outputs = image_segmenter("./tests/fixtures/tests_samples/COCO/000000039769.png", threshold=0.0)
85
86
        self.assertIsInstance(outputs, list)
        n = len(outputs)
87
88
89
90
91
92
        if isinstance(image_segmenter.model, (MaskFormerForInstanceSegmentation)):
            # Instance segmentation (maskformer) have a slot for null class
            # and can output nothing even with a low threshold
            self.assertGreaterEqual(n, 0)
        else:
            self.assertGreaterEqual(n, 1)
93
94
95
        # XXX: PIL.Image implements __eq__ which bypasses ANY, so we inverse the comparison
        # to make it work
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, outputs)
96

97
        dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test")
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        # RGBA
        outputs = image_segmenter(dataset[0]["file"])
        m = len(outputs)
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs)
        # LA
        outputs = image_segmenter(dataset[1]["file"])
        m = len(outputs)
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs)
        # L
        outputs = image_segmenter(dataset[2]["file"])
        m = len(outputs)
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs)

        if isinstance(image_segmenter.model, DetrForSegmentation):
            # We need to test batch_size with images with the same size.
            # Detr doesn't normalize the size of the images, meaning we can have
            # 800x800 or 800x1200, meaning we cannot batch simply.
            # We simply bail on this
            batch_size = 1
        else:
            batch_size = 2

        # 5 times the same image so the output shape is predictable
122
        batch = [
123
124
125
126
127
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
128
        ]
129
        outputs = image_segmenter(batch, threshold=0.0, batch_size=batch_size)
130
        self.assertEqual(len(batch), len(outputs))
131
        self.assertEqual(len(outputs[0]), n)
132
133
        self.assertEqual(
            [
134
135
136
137
138
                [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n,
                [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n,
                [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n,
                [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n,
                [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n,
139
            ],
140
141
            outputs,
            f"Expected [{n}, {n}, {n}, {n}, {n}], got {[len(item) for item in outputs]}",
142
143
144
145
146
147
148
149
        )

    @require_tf
    @unittest.skip("Image segmentation not implemented in TF")
    def test_small_model_tf(self):
        pass

    @require_torch
150
    @unittest.skip("No weights found for hf-internal-testing/tiny-detr-mobilenetsv3-panoptic")
151
    def test_small_model_pt(self):
152
        model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic"
153
154
155
156
157

        model = AutoModelForImageSegmentation.from_pretrained(model_id)
        feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
        image_segmenter = ImageSegmentationPipeline(model=model, feature_extractor=feature_extractor)

158
159
160
161
162
163
164
165
        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg",
            task="panoptic",
            threshold=0.0,
            overlap_mask_area_threshold=0.0,
        )

        # Shortening by hashing
166
        for o in outputs:
167
            o["mask"] = hashimage(o["mask"])
168
169
170
171
172
173

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
                    "score": 0.004,
174
                    "label": "LABEL_215",
175
                    "mask": "34eecd16bbfb0f476083ef947d81bf66",
176
177
178
                },
                {
                    "score": 0.004,
179
                    "label": "LABEL_215",
180
                    "mask": "34eecd16bbfb0f476083ef947d81bf66",
181
182
183
184
185
186
187
188
189
190
191
192
193
                },
            ],
        )

        outputs = image_segmenter(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ],
            threshold=0.0,
        )
        for output in outputs:
            for o in output:
194
                o["mask"] = hashimage(o["mask"])
195
196
197
198
199
200
201

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                [
                    {
                        "score": 0.004,
202
                        "label": "LABEL_215",
203
                        "mask": "34eecd16bbfb0f476083ef947d81bf66",
204
205
206
                    },
                    {
                        "score": 0.004,
207
                        "label": "LABEL_215",
208
                        "mask": "34eecd16bbfb0f476083ef947d81bf66",
209
210
211
212
213
                    },
                ],
                [
                    {
                        "score": 0.004,
214
                        "label": "LABEL_215",
215
                        "mask": "34eecd16bbfb0f476083ef947d81bf66",
216
217
218
                    },
                    {
                        "score": 0.004,
219
                        "label": "LABEL_215",
220
                        "mask": "34eecd16bbfb0f476083ef947d81bf66",
221
222
223
224
225
                    },
                ],
            ],
        )

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    @require_torch
    def test_small_model_pt_semantic(self):
        model_id = "hf-internal-testing/tiny-random-beit-pipeline"
        image_segmenter = pipeline(model=model_id)
        outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg")
        for o in outputs:
            # shortening by hashing
            o["mask"] = hashimage(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
                    "score": None,
                    "label": "LABEL_0",
241
                    "mask": "775518a7ed09eea888752176c6ba8f38",
242
243
244
245
                },
                {
                    "score": None,
                    "label": "LABEL_1",
246
                    "mask": "a12da23a46848128af68c63aa8ba7a02",
247
248
249
250
                },
            ],
        )

251
252
253
254
255
256
    @require_torch
    @slow
    def test_integration_torch_image_segmentation(self):
        model_id = "facebook/detr-resnet-50-panoptic"
        image_segmenter = pipeline("image-segmentation", model=model_id)

257
258
259
260
261
262
263
264
        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg",
            task="panoptic",
            threshold=0,
            overlap_mask_area_threshold=0.0,
        )

        # Shortening by hashing
265
        for o in outputs:
266
            o["mask"] = hashimage(o["mask"])
267
268
269
270

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
271
272
273
274
275
276
                {"score": 0.9094, "label": "blanket", "mask": "dcff19a97abd8bd555e21186ae7c066a"},
                {"score": 0.9941, "label": "cat", "mask": "9c0af87bd00f9d3a4e0c8888e34e70e2"},
                {"score": 0.9987, "label": "remote", "mask": "c7870600d6c02a1f6d96470fc7220e8e"},
                {"score": 0.9995, "label": "remote", "mask": "ef899a25fd44ec056c653f0ca2954fdd"},
                {"score": 0.9722, "label": "couch", "mask": "37b8446ac578a17108aa2b7fccc33114"},
                {"score": 0.9994, "label": "cat", "mask": "6a09d3655efd8a388ab4511e4cbbb797"},
277
278
279
280
281
282
283
284
            ],
        )

        outputs = image_segmenter(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ],
285
            task="panoptic",
286
            threshold=0.0,
287
            overlap_mask_area_threshold=0.0,
288
        )
289
290

        # Shortening by hashing
291
292
        for output in outputs:
            for o in output:
293
                o["mask"] = hashimage(o["mask"])
294
295
296
297
298

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                [
299
300
301
302
303
304
                    {"score": 0.9094, "label": "blanket", "mask": "dcff19a97abd8bd555e21186ae7c066a"},
                    {"score": 0.9941, "label": "cat", "mask": "9c0af87bd00f9d3a4e0c8888e34e70e2"},
                    {"score": 0.9987, "label": "remote", "mask": "c7870600d6c02a1f6d96470fc7220e8e"},
                    {"score": 0.9995, "label": "remote", "mask": "ef899a25fd44ec056c653f0ca2954fdd"},
                    {"score": 0.9722, "label": "couch", "mask": "37b8446ac578a17108aa2b7fccc33114"},
                    {"score": 0.9994, "label": "cat", "mask": "6a09d3655efd8a388ab4511e4cbbb797"},
305
306
                ],
                [
307
308
309
310
311
312
                    {"score": 0.9094, "label": "blanket", "mask": "dcff19a97abd8bd555e21186ae7c066a"},
                    {"score": 0.9941, "label": "cat", "mask": "9c0af87bd00f9d3a4e0c8888e34e70e2"},
                    {"score": 0.9987, "label": "remote", "mask": "c7870600d6c02a1f6d96470fc7220e8e"},
                    {"score": 0.9995, "label": "remote", "mask": "ef899a25fd44ec056c653f0ca2954fdd"},
                    {"score": 0.9722, "label": "couch", "mask": "37b8446ac578a17108aa2b7fccc33114"},
                    {"score": 0.9994, "label": "cat", "mask": "6a09d3655efd8a388ab4511e4cbbb797"},
313
314
315
316
317
318
319
320
321
322
                ],
            ],
        )

    @require_torch
    @slow
    def test_threshold(self):
        model_id = "facebook/detr-resnet-50-panoptic"
        image_segmenter = pipeline("image-segmentation", model=model_id)

323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg", task="panoptic", threshold=0.999
        )
        # Shortening by hashing
        for o in outputs:
            o["mask"] = hashimage(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {"score": 0.9995, "label": "remote", "mask": "d02404f5789f075e3b3174adbc3fd5b8"},
                {"score": 0.9994, "label": "cat", "mask": "eaa115b40c96d3a6f4fe498963a7e470"},
            ],
        )

        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg", task="panoptic", threshold=0.5
        )
341
342

        for o in outputs:
343
            o["mask"] = hashimage(o["mask"])
344
345
346
347

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
348
349
350
351
352
                {"score": 0.9941, "label": "cat", "mask": "9c0af87bd00f9d3a4e0c8888e34e70e2"},
                {"score": 0.9987, "label": "remote", "mask": "c7870600d6c02a1f6d96470fc7220e8e"},
                {"score": 0.9995, "label": "remote", "mask": "ef899a25fd44ec056c653f0ca2954fdd"},
                {"score": 0.9722, "label": "couch", "mask": "37b8446ac578a17108aa2b7fccc33114"},
                {"score": 0.9994, "label": "cat", "mask": "6a09d3655efd8a388ab4511e4cbbb797"},
353
354
            ],
        )
355
356
357
358

    @require_torch
    @slow
    def test_maskformer(self):
359
        threshold = 0.8
360
361
        model_id = "facebook/maskformer-swin-base-ade"

362
363
        model = AutoModelForInstanceSegmentation.from_pretrained(model_id)
        feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
364
365
366
367

        image_segmenter = pipeline("image-segmentation", model=model, feature_extractor=feature_extractor)

        image = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
368
        file = image[0]["file"]
369
        outputs = image_segmenter(file, task="panoptic", threshold=threshold)
370

371
        # Shortening by hashing
372
373
374
375
376
377
        for o in outputs:
            o["mask"] = hashimage(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
378
379
380
381
382
383
384
                {"score": 0.9974, "label": "wall", "mask": "a547b7c062917f4f3e36501827ad3cd6"},
                {"score": 0.949, "label": "house", "mask": "0da9b7b38feac47bd2528a63e5ea7b19"},
                {"score": 0.9995, "label": "grass", "mask": "1d07ea0a263dcf38ca8ae1a15fdceda1"},
                {"score": 0.9976, "label": "tree", "mask": "6cdc97c7daf1dc596fa181f461ddd2ba"},
                {"score": 0.8239, "label": "plant", "mask": "1ab4ce378f6ceff57d428055cfbd742f"},
                {"score": 0.9942, "label": "road, route", "mask": "39c5d17be53b2d1b0f46aad8ebb15813"},
                {"score": 1.0, "label": "sky", "mask": "a3756324a692981510c39b1a59510a36"},
385
386
            ],
        )