test_pipelines_image_segmentation.py 27.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.

15
import tempfile
16
import unittest
17
from typing import Dict
18

19
import datasets
20
import numpy as np
21
import requests
22
from datasets import load_dataset
23
from huggingface_hub.utils import insecure_hashlib
24

25
26
from transformers import (
    MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
27
    MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
28
    MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
29
    AutoImageProcessor,
30
    AutoModelForImageSegmentation,
31
    AutoModelForInstanceSegmentation,
32
    DetrForSegmentation,
33
    ImageSegmentationPipeline,
34
    MaskFormerForInstanceSegmentation,
35
36
37
    is_vision_available,
    pipeline,
)
38
39
40
41
42
43
44
45
46
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)
47

48
from .test_pipelines_common import ANY
49
50
51
52
53
54
55
56
57
58
59
60


if is_vision_available():
    from PIL import Image
else:

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


61
def hashimage(image: Image) -> str:
62
    m = insecure_hashlib.md5(image.tobytes())
63
64
65
66
67
68
69
70
    return m.hexdigest()[:10]


def mask_to_test_readable(mask: Image) -> Dict:
    npimg = np.array(mask)
    white_pixels = (npimg == 255).sum()
    shape = npimg.shape
    return {"hash": hashimage(mask), "white_pixels": white_pixels, "shape": shape}
71
72


73
74
75
76
77
78
def mask_to_test_readable_only_shape(mask: Image) -> Dict:
    npimg = np.array(mask)
    shape = npimg.shape
    return {"shape": shape}


79
@is_pipeline_test
80
81
82
@require_vision
@require_timm
@require_torch
83
class ImageSegmentationPipelineTests(unittest.TestCase):
84
85
    model_mapping = dict(
        (list(MODEL_FOR_IMAGE_SEGMENTATION_MAPPING.items()) if MODEL_FOR_IMAGE_SEGMENTATION_MAPPING else [])
86
        + (MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING.items() if MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING else [])
87
88
        + (MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING.items() if MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING else [])
    )
89

90
91
    def get_test_pipeline(self, model, tokenizer, processor):
        image_segmenter = ImageSegmentationPipeline(model=model, image_processor=processor)
92
93
94
95
96
97
        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):
98
99
100
101
102
103
        outputs = image_segmenter(
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            threshold=0.0,
            mask_threshold=0,
            overlap_mask_area_threshold=0,
        )
104
105
        self.assertIsInstance(outputs, list)
        n = len(outputs)
106
107
        if isinstance(image_segmenter.model, (MaskFormerForInstanceSegmentation, DetrForSegmentation)):
            # Instance segmentation (maskformer, and detr) have a slot for null class
108
109
110
111
            # and can output nothing even with a low threshold
            self.assertGreaterEqual(n, 0)
        else:
            self.assertGreaterEqual(n, 1)
112
113
114
        # 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)
115

116
117
118
        # we use revision="refs/pr/1" until the PR is merged
        # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
        dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", split="test", revision="refs/pr/1")
119

120
        # RGBA
121
        outputs = image_segmenter(dataset[0]["image"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0)
122
123
124
        m = len(outputs)
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs)
        # LA
125
        outputs = image_segmenter(dataset[1]["image"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0)
126
127
128
        m = len(outputs)
        self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs)
        # L
129
        outputs = image_segmenter(dataset[2]["image"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0)
130
131
132
133
134
135
136
137
138
139
140
141
142
        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
143
        batch = [
144
145
146
147
148
            "./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",
149
        ]
150
        outputs = image_segmenter(
151
152
153
154
155
            batch,
            threshold=0.0,
            mask_threshold=0,
            overlap_mask_area_threshold=0,
            batch_size=batch_size,
156
        )
157
        self.assertEqual(len(batch), len(outputs))
158
        self.assertEqual(len(outputs[0]), n)
159
160
        self.assertEqual(
            [
161
162
163
164
165
                [{"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,
166
            ],
167
168
            outputs,
            f"Expected [{n}, {n}, {n}, {n}, {n}], got {[len(item) for item in outputs]}",
169
170
171
172
173
174
175
        )

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

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    @require_torch
    def test_small_model_pt_no_panoptic(self):
        model_id = "hf-internal-testing/tiny-random-mobilevit"
        # The default task is `image-classification` we need to override
        pipe = pipeline(task="image-segmentation", model=model_id)

        # This model does NOT support neither `instance` nor  `panoptic`
        # We should error out
        with self.assertRaises(ValueError) as e:
            pipe("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="panoptic")
        self.assertEqual(
            str(e.exception),
            "Subtask panoptic is not supported for model <class"
            " 'transformers.models.mobilevit.modeling_mobilevit.MobileViTForSemanticSegmentation'>",
        )
        with self.assertRaises(ValueError) as e:
            pipe("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="instance")
        self.assertEqual(
            str(e.exception),
            "Subtask instance is not supported for model <class"
            " 'transformers.models.mobilevit.modeling_mobilevit.MobileViTForSemanticSegmentation'>",
        )

199
200
    @require_torch
    def test_small_model_pt(self):
201
        model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic"
202
203

        model = AutoModelForImageSegmentation.from_pretrained(model_id)
204
        image_processor = AutoImageProcessor.from_pretrained(model_id)
205
206
        image_segmenter = ImageSegmentationPipeline(
            model=model,
207
            image_processor=image_processor,
208
209
210
211
            subtask="panoptic",
            threshold=0.0,
            mask_threshold=0.0,
            overlap_mask_area_threshold=0.0,
212
213
        )

214
215
216
217
        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg",
        )

218
        # Shortening by hashing
219
        for o in outputs:
220
            o["mask"] = mask_to_test_readable(o["mask"])
221

222
        # This is extremely brittle, and those values are made specific for the CI.
223
224
225
226
        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
227
                    "score": 0.004,
228
                    "label": "LABEL_215",
229
                    "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200},
230
                },
231
            ],
232
233
234
235
236
237
238
239
240
241
        )

        outputs = image_segmenter(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ],
        )
        for output in outputs:
            for o in output:
242
                o["mask"] = mask_to_test_readable(o["mask"])
243
244
245
246
247
248

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                [
                    {
249
                        "score": 0.004,
250
                        "label": "LABEL_215",
251
                        "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200},
252
253
254
255
                    },
                ],
                [
                    {
256
                        "score": 0.004,
257
                        "label": "LABEL_215",
258
                        "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200},
259
                    },
260
                ],
261
262
263
            ],
        )

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
        output = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="instance")
        for o in output:
            o["mask"] = mask_to_test_readable(o["mask"])
        self.assertEqual(
            nested_simplify(output, decimals=4),
            [
                {
                    "score": 0.004,
                    "label": "LABEL_215",
                    "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200},
                },
            ],
        )

        # This must be surprising to the reader.
        # The `panoptic` returns only LABEL_215, and this returns 3 labels.
        #
        output = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="semantic")
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

        output_masks = [o["mask"] for o in output]

        # page links (to visualize)
        expected_masks = [
            "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_0.png",
            "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_1.png",
            "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_2.png",
        ]
        # actual links to get files
        expected_masks = [x.replace("/blob/", "/resolve/") for x in expected_masks]
        expected_masks = [Image.open(requests.get(image, stream=True).raw) for image in expected_masks]

        # Convert masks to numpy array
        output_masks = [np.array(x) for x in output_masks]
        expected_masks = [np.array(x) for x in expected_masks]

        self.assertEqual(output_masks[0].shape, expected_masks[0].shape)
        self.assertEqual(output_masks[1].shape, expected_masks[1].shape)
        self.assertEqual(output_masks[2].shape, expected_masks[2].shape)

        # With un-trained tiny random models, the output `logits` tensor is very likely to contain many values
        # close to each other, which cause `argmax` to give quite different results when running the test on 2
        # environments. We use a lower threshold `0.9` here to avoid flakiness.
        self.assertGreaterEqual(np.mean(output_masks[0] == expected_masks[0]), 0.9)
        self.assertGreaterEqual(np.mean(output_masks[1] == expected_masks[1]), 0.9)
        self.assertGreaterEqual(np.mean(output_masks[2] == expected_masks[2]), 0.9)

310
        for o in output:
311
            o["mask"] = mask_to_test_readable_only_shape(o["mask"])
312
313
314
315
316
317
        self.maxDiff = None
        self.assertEqual(
            nested_simplify(output, decimals=4),
            [
                {
                    "label": "LABEL_88",
318
                    "mask": {"shape": (480, 640)},
319
320
321
322
                    "score": None,
                },
                {
                    "label": "LABEL_101",
323
                    "mask": {"shape": (480, 640)},
324
325
326
327
                    "score": None,
                },
                {
                    "label": "LABEL_215",
328
                    "mask": {"shape": (480, 640)},
329
330
331
332
333
                    "score": None,
                },
            ],
        )

334
335
336
337
338
339
340
    @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
341
            o["mask"] = mask_to_test_readable(o["mask"])
342
343
344
345

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
346
347
348
349
350
                {
                    "score": None,
                    "label": "LABEL_0",
                    "mask": {"hash": "42d0907228", "shape": (480, 640), "white_pixels": 10714},
                },
351
352
353
                {
                    "score": None,
                    "label": "LABEL_1",
354
                    "mask": {"hash": "46b8cc3976", "shape": (480, 640), "white_pixels": 296486},
355
356
357
358
                },
            ],
        )

359
360
361
362
    @require_torch
    @slow
    def test_integration_torch_image_segmentation(self):
        model_id = "facebook/detr-resnet-50-panoptic"
363
364
365
366
367
368
        image_segmenter = pipeline(
            "image-segmentation",
            model=model_id,
            threshold=0.0,
            overlap_mask_area_threshold=0.0,
        )
369

370
371
372
373
374
        outputs = image_segmenter(
            "http://images.cocodataset.org/val2017/000000039769.jpg",
        )

        # Shortening by hashing
375
        for o in outputs:
376
            o["mask"] = mask_to_test_readable(o["mask"])
377
378
379
380

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
                {
                    "score": 0.9094,
                    "label": "blanket",
                    "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617},
                },
                {
                    "score": 0.9941,
                    "label": "cat",
                    "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185},
                },
                {
                    "score": 0.9987,
                    "label": "remote",
                    "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182},
                },
                {
                    "score": 0.9995,
                    "label": "remote",
                    "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275},
                },
                {
                    "score": 0.9722,
                    "label": "couch",
                    "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380},
                },
                {
                    "score": 0.9994,
                    "label": "cat",
                    "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561},
                },
411
412
413
414
415
416
417
418
419
            ],
        )

        outputs = image_segmenter(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ],
        )
420
421

        # Shortening by hashing
422
423
        for output in outputs:
            for o in output:
424
                o["mask"] = mask_to_test_readable(o["mask"])
425
426
427
428
429

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                [
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
                    {
                        "score": 0.9094,
                        "label": "blanket",
                        "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617},
                    },
                    {
                        "score": 0.9941,
                        "label": "cat",
                        "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185},
                    },
                    {
                        "score": 0.9987,
                        "label": "remote",
                        "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182},
                    },
                    {
                        "score": 0.9995,
                        "label": "remote",
                        "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275},
                    },
                    {
                        "score": 0.9722,
                        "label": "couch",
                        "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380},
                    },
                    {
                        "score": 0.9994,
                        "label": "cat",
                        "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561},
                    },
460
461
                ],
                [
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
                    {
                        "score": 0.9094,
                        "label": "blanket",
                        "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617},
                    },
                    {
                        "score": 0.9941,
                        "label": "cat",
                        "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185},
                    },
                    {
                        "score": 0.9987,
                        "label": "remote",
                        "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182},
                    },
                    {
                        "score": 0.9995,
                        "label": "remote",
                        "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275},
                    },
                    {
                        "score": 0.9722,
                        "label": "couch",
                        "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380},
                    },
                    {
                        "score": 0.9994,
                        "label": "cat",
                        "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561},
                    },
492
493
494
495
496
497
498
499
500
501
                ],
            ],
        )

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

502
        outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=0.999)
503
504
        # Shortening by hashing
        for o in outputs:
505
            o["mask"] = mask_to_test_readable(o["mask"])
506
507
508
509

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
510
511
512
513
514
515
516
517
518
519
                {
                    "score": 0.9995,
                    "label": "remote",
                    "mask": {"hash": "d02404f578", "shape": (480, 640), "white_pixels": 2789},
                },
                {
                    "score": 0.9994,
                    "label": "cat",
                    "mask": {"hash": "eaa115b40c", "shape": (480, 640), "white_pixels": 304411},
                },
520
521
522
            ],
        )

523
        outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=0.5)
524
525

        for o in outputs:
526
            o["mask"] = mask_to_test_readable(o["mask"])
527
528
529
530

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
                {
                    "score": 0.9941,
                    "label": "cat",
                    "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185},
                },
                {
                    "score": 0.9987,
                    "label": "remote",
                    "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182},
                },
                {
                    "score": 0.9995,
                    "label": "remote",
                    "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275},
                },
                {
                    "score": 0.9722,
                    "label": "couch",
                    "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380},
                },
                {
                    "score": 0.9994,
                    "label": "cat",
                    "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561},
                },
556
557
            ],
        )
558
559
560
561

    @require_torch
    @slow
    def test_maskformer(self):
562
        threshold = 0.8
563
564
        model_id = "facebook/maskformer-swin-base-ade"

565
        model = AutoModelForInstanceSegmentation.from_pretrained(model_id)
Yih-Dar's avatar
Yih-Dar committed
566
        image_processor = AutoImageProcessor.from_pretrained(model_id)
567

Yih-Dar's avatar
Yih-Dar committed
568
        image_segmenter = pipeline("image-segmentation", model=model, image_processor=image_processor)
569
570

        image = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
571
        file = image[0]["file"]
572
        outputs = image_segmenter(file, threshold=threshold)
573

574
        # Shortening by hashing
575
        for o in outputs:
576
            o["mask"] = mask_to_test_readable(o["mask"])
577
578
579
580

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
                {
                    "score": 0.9974,
                    "label": "wall",
                    "mask": {"hash": "a547b7c062", "shape": (512, 683), "white_pixels": 14252},
                },
                {
                    "score": 0.949,
                    "label": "house",
                    "mask": {"hash": "0da9b7b38f", "shape": (512, 683), "white_pixels": 132177},
                },
                {
                    "score": 0.9995,
                    "label": "grass",
                    "mask": {"hash": "1d07ea0a26", "shape": (512, 683), "white_pixels": 53444},
                },
                {
                    "score": 0.9976,
                    "label": "tree",
                    "mask": {"hash": "6cdc97c7da", "shape": (512, 683), "white_pixels": 7944},
                },
                {
                    "score": 0.8239,
                    "label": "plant",
                    "mask": {"hash": "1ab4ce378f", "shape": (512, 683), "white_pixels": 4136},
                },
                {
                    "score": 0.9942,
                    "label": "road, route",
                    "mask": {"hash": "39c5d17be5", "shape": (512, 683), "white_pixels": 1941},
                },
                {
                    "score": 1.0,
                    "label": "sky",
                    "mask": {"hash": "a3756324a6", "shape": (512, 683), "white_pixels": 135802},
                },
616
617
            ],
        )
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

    @require_torch
    @slow
    def test_oneformer(self):
        image_segmenter = pipeline(model="shi-labs/oneformer_ade20k_swin_tiny")

        image = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
        file = image[0]["file"]
        outputs = image_segmenter(file, threshold=0.99)
        # Shortening by hashing
        for o in outputs:
            o["mask"] = mask_to_test_readable(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
                    "score": 0.9981,
                    "label": "grass",
                    "mask": {"hash": "3a92904d4c", "white_pixels": 118131, "shape": (512, 683)},
                },
                {
                    "score": 0.9992,
                    "label": "sky",
                    "mask": {"hash": "fa2300cc9a", "white_pixels": 231565, "shape": (512, 683)},
                },
            ],
        )

        # Different task
        outputs = image_segmenter(file, threshold=0.99, subtask="instance")
        # Shortening by hashing
        for o in outputs:
            o["mask"] = mask_to_test_readable(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
                    "score": 0.9991,
                    "label": "sky",
                    "mask": {"hash": "8b1ffad016", "white_pixels": 230566, "shape": (512, 683)},
                },
                {
                    "score": 0.9981,
                    "label": "grass",
                    "mask": {"hash": "9bbdf83d3d", "white_pixels": 119130, "shape": (512, 683)},
                },
            ],
        )

        # Different task
        outputs = image_segmenter(file, subtask="semantic")
        # Shortening by hashing
        for o in outputs:
            o["mask"] = mask_to_test_readable(o["mask"])

        self.assertEqual(
            nested_simplify(outputs, decimals=4),
            [
                {
                    "score": None,
                    "label": "wall",
                    "mask": {"hash": "897fb20b7f", "white_pixels": 14506, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "building",
                    "mask": {"hash": "f2a68c63e4", "white_pixels": 125019, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "sky",
                    "mask": {"hash": "e0ca3a548e", "white_pixels": 135330, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "tree",
                    "mask": {"hash": "7c9544bcac", "white_pixels": 16263, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "road, route",
                    "mask": {"hash": "2c7704e491", "white_pixels": 2143, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "grass",
                    "mask": {"hash": "bf6c2867e0", "white_pixels": 53040, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "plant",
                    "mask": {"hash": "93c4b7199e", "white_pixels": 3335, "shape": (512, 683)},
                },
                {
                    "score": None,
                    "label": "house",
                    "mask": {"hash": "93ec419ad5", "white_pixels": 60, "shape": (512, 683)},
                },
            ],
        )
720
721
722
723
724
725
726
727
728
729
730
731
732
733

    def test_save_load(self):
        model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic"

        model = AutoModelForImageSegmentation.from_pretrained(model_id)
        image_processor = AutoImageProcessor.from_pretrained(model_id)
        image_segmenter = pipeline(
            task="image-segmentation",
            model=model,
            image_processor=image_processor,
        )
        with tempfile.TemporaryDirectory() as tmpdirname:
            image_segmenter.save_pretrained(tmpdirname)
            pipeline(task="image-segmentation", model=tmpdirname)