Upload folder using huggingface_hub (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_lraspp_head.py +68 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_nl_head.py +16 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_ocr_head.py +19 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_point_head.py +61 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psa_head.py +122 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psp_head.py +36 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segformer_head.py +40 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segmenter_mask_head.py +24 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_mla_head.py +63 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_up_head.py +56 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_stdc_head.py +31 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_uper_head.py +35 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/utils.py +22 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/__init__.py +1 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_ce_loss.py +294 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_dice_loss.py +78 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_focal_loss.py +216 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_lovasz_loss.py +118 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_utils.py +129 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/__init__.py +1 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_feature2pyramid.py +38 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_fpn.py +30 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_ic_neck.py +53 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_jpu.py +46 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_mla_neck.py +16 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_multilevel_neck.py +32 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/__init__.py +1 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py +57 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_encoder_decoder.py +47 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/utils.py +140 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/__init__.py +1 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_embed.py +461 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_shape_convert.py +89 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_sampler.py +78 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_misc.py +40 -0
- EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_set_env.py +85 -0
- EgoHOS/raw/script/mmsegmentation/tools/analyze_logs.py +128 -0
- EgoHOS/raw/script/mmsegmentation/tools/benchmark.py +120 -0
- EgoHOS/raw/script/mmsegmentation/tools/browse_dataset.py +182 -0
- EgoHOS/raw/script/mmsegmentation/tools/confusion_matrix.py +184 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/chase_db1.py +88 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/cityscapes.py +56 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff10k.py +307 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff164k.py +264 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/drive.py +113 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/hrf.py +111 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/isaid.py +245 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/loveda.py +73 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/pascal_context.py +87 -0
- EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/potsdam.py +157 -0
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_lraspp_head.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import LRASPPHead
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_lraspp_head():
|
| 9 |
+
with pytest.raises(ValueError):
|
| 10 |
+
# check invalid input_transform
|
| 11 |
+
LRASPPHead(
|
| 12 |
+
in_channels=(4, 4, 123),
|
| 13 |
+
in_index=(0, 1, 2),
|
| 14 |
+
channels=32,
|
| 15 |
+
input_transform='resize_concat',
|
| 16 |
+
dropout_ratio=0.1,
|
| 17 |
+
num_classes=19,
|
| 18 |
+
norm_cfg=dict(type='BN'),
|
| 19 |
+
act_cfg=dict(type='ReLU'),
|
| 20 |
+
align_corners=False,
|
| 21 |
+
loss_decode=dict(
|
| 22 |
+
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
|
| 23 |
+
|
| 24 |
+
with pytest.raises(AssertionError):
|
| 25 |
+
# check invalid branch_channels
|
| 26 |
+
LRASPPHead(
|
| 27 |
+
in_channels=(4, 4, 123),
|
| 28 |
+
in_index=(0, 1, 2),
|
| 29 |
+
channels=32,
|
| 30 |
+
branch_channels=64,
|
| 31 |
+
input_transform='multiple_select',
|
| 32 |
+
dropout_ratio=0.1,
|
| 33 |
+
num_classes=19,
|
| 34 |
+
norm_cfg=dict(type='BN'),
|
| 35 |
+
act_cfg=dict(type='ReLU'),
|
| 36 |
+
align_corners=False,
|
| 37 |
+
loss_decode=dict(
|
| 38 |
+
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
|
| 39 |
+
|
| 40 |
+
# test with default settings
|
| 41 |
+
lraspp_head = LRASPPHead(
|
| 42 |
+
in_channels=(4, 4, 123),
|
| 43 |
+
in_index=(0, 1, 2),
|
| 44 |
+
channels=32,
|
| 45 |
+
input_transform='multiple_select',
|
| 46 |
+
dropout_ratio=0.1,
|
| 47 |
+
num_classes=19,
|
| 48 |
+
norm_cfg=dict(type='BN'),
|
| 49 |
+
act_cfg=dict(type='ReLU'),
|
| 50 |
+
align_corners=False,
|
| 51 |
+
loss_decode=dict(
|
| 52 |
+
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
|
| 53 |
+
inputs = [
|
| 54 |
+
torch.randn(2, 4, 45, 45),
|
| 55 |
+
torch.randn(2, 4, 28, 28),
|
| 56 |
+
torch.randn(2, 123, 14, 14)
|
| 57 |
+
]
|
| 58 |
+
with pytest.raises(RuntimeError):
|
| 59 |
+
# check invalid inputs
|
| 60 |
+
output = lraspp_head(inputs)
|
| 61 |
+
|
| 62 |
+
inputs = [
|
| 63 |
+
torch.randn(2, 4, 111, 111),
|
| 64 |
+
torch.randn(2, 4, 77, 77),
|
| 65 |
+
torch.randn(2, 123, 55, 55)
|
| 66 |
+
]
|
| 67 |
+
output = lraspp_head(inputs)
|
| 68 |
+
assert output.shape == (2, 19, 111, 111)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_nl_head.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models.decode_heads import NLHead
|
| 5 |
+
from .utils import to_cuda
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_nl_head():
|
| 9 |
+
head = NLHead(in_channels=8, channels=4, num_classes=19)
|
| 10 |
+
assert len(head.convs) == 2
|
| 11 |
+
assert hasattr(head, 'nl_block')
|
| 12 |
+
inputs = [torch.randn(1, 8, 23, 23)]
|
| 13 |
+
if torch.cuda.is_available():
|
| 14 |
+
head, inputs = to_cuda(head, inputs)
|
| 15 |
+
outputs = head(inputs)
|
| 16 |
+
assert outputs.shape == (1, head.num_classes, 23, 23)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_ocr_head.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models.decode_heads import FCNHead, OCRHead
|
| 5 |
+
from .utils import to_cuda
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_ocr_head():
|
| 9 |
+
|
| 10 |
+
inputs = [torch.randn(1, 8, 23, 23)]
|
| 11 |
+
ocr_head = OCRHead(
|
| 12 |
+
in_channels=8, channels=4, num_classes=19, ocr_channels=8)
|
| 13 |
+
fcn_head = FCNHead(in_channels=8, channels=4, num_classes=19)
|
| 14 |
+
if torch.cuda.is_available():
|
| 15 |
+
head, inputs = to_cuda(ocr_head, inputs)
|
| 16 |
+
head, inputs = to_cuda(fcn_head, inputs)
|
| 17 |
+
prev_output = fcn_head(inputs)
|
| 18 |
+
output = ocr_head(inputs, prev_output)
|
| 19 |
+
assert output.shape == (1, ocr_head.num_classes, 23, 23)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_point_head.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
from mmcv.utils import ConfigDict
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import FCNHead, PointHead
|
| 6 |
+
from .utils import to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_point_head():
|
| 10 |
+
|
| 11 |
+
inputs = [torch.randn(1, 32, 45, 45)]
|
| 12 |
+
point_head = PointHead(
|
| 13 |
+
in_channels=[32], in_index=[0], channels=16, num_classes=19)
|
| 14 |
+
assert len(point_head.fcs) == 3
|
| 15 |
+
fcn_head = FCNHead(in_channels=32, channels=16, num_classes=19)
|
| 16 |
+
if torch.cuda.is_available():
|
| 17 |
+
head, inputs = to_cuda(point_head, inputs)
|
| 18 |
+
head, inputs = to_cuda(fcn_head, inputs)
|
| 19 |
+
prev_output = fcn_head(inputs)
|
| 20 |
+
test_cfg = ConfigDict(
|
| 21 |
+
subdivision_steps=2, subdivision_num_points=8196, scale_factor=2)
|
| 22 |
+
output = point_head.forward_test(inputs, prev_output, None, test_cfg)
|
| 23 |
+
assert output.shape == (1, point_head.num_classes, 180, 180)
|
| 24 |
+
|
| 25 |
+
# test multiple losses case
|
| 26 |
+
inputs = [torch.randn(1, 32, 45, 45)]
|
| 27 |
+
point_head_multiple_losses = PointHead(
|
| 28 |
+
in_channels=[32],
|
| 29 |
+
in_index=[0],
|
| 30 |
+
channels=16,
|
| 31 |
+
num_classes=19,
|
| 32 |
+
loss_decode=[
|
| 33 |
+
dict(type='CrossEntropyLoss', loss_name='loss_1'),
|
| 34 |
+
dict(type='CrossEntropyLoss', loss_name='loss_2')
|
| 35 |
+
])
|
| 36 |
+
assert len(point_head_multiple_losses.fcs) == 3
|
| 37 |
+
fcn_head_multiple_losses = FCNHead(
|
| 38 |
+
in_channels=32,
|
| 39 |
+
channels=16,
|
| 40 |
+
num_classes=19,
|
| 41 |
+
loss_decode=[
|
| 42 |
+
dict(type='CrossEntropyLoss', loss_name='loss_1'),
|
| 43 |
+
dict(type='CrossEntropyLoss', loss_name='loss_2')
|
| 44 |
+
])
|
| 45 |
+
if torch.cuda.is_available():
|
| 46 |
+
head, inputs = to_cuda(point_head_multiple_losses, inputs)
|
| 47 |
+
head, inputs = to_cuda(fcn_head_multiple_losses, inputs)
|
| 48 |
+
prev_output = fcn_head_multiple_losses(inputs)
|
| 49 |
+
test_cfg = ConfigDict(
|
| 50 |
+
subdivision_steps=2, subdivision_num_points=8196, scale_factor=2)
|
| 51 |
+
output = point_head_multiple_losses.forward_test(inputs, prev_output, None,
|
| 52 |
+
test_cfg)
|
| 53 |
+
assert output.shape == (1, point_head.num_classes, 180, 180)
|
| 54 |
+
|
| 55 |
+
fake_label = torch.ones([1, 180, 180], dtype=torch.long)
|
| 56 |
+
|
| 57 |
+
if torch.cuda.is_available():
|
| 58 |
+
fake_label = fake_label.cuda()
|
| 59 |
+
loss = point_head_multiple_losses.losses(output, fake_label)
|
| 60 |
+
assert 'pointloss_1' in loss
|
| 61 |
+
assert 'pointloss_2' in loss
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psa_head.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import PSAHead
|
| 6 |
+
from .utils import _conv_has_norm, to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_psa_head():
|
| 10 |
+
|
| 11 |
+
with pytest.raises(AssertionError):
|
| 12 |
+
# psa_type must be in 'bi-direction', 'collect', 'distribute'
|
| 13 |
+
PSAHead(
|
| 14 |
+
in_channels=4,
|
| 15 |
+
channels=2,
|
| 16 |
+
num_classes=19,
|
| 17 |
+
mask_size=(13, 13),
|
| 18 |
+
psa_type='gather')
|
| 19 |
+
|
| 20 |
+
# test no norm_cfg
|
| 21 |
+
head = PSAHead(
|
| 22 |
+
in_channels=4, channels=2, num_classes=19, mask_size=(13, 13))
|
| 23 |
+
assert not _conv_has_norm(head, sync_bn=False)
|
| 24 |
+
|
| 25 |
+
# test with norm_cfg
|
| 26 |
+
head = PSAHead(
|
| 27 |
+
in_channels=4,
|
| 28 |
+
channels=2,
|
| 29 |
+
num_classes=19,
|
| 30 |
+
mask_size=(13, 13),
|
| 31 |
+
norm_cfg=dict(type='SyncBN'))
|
| 32 |
+
assert _conv_has_norm(head, sync_bn=True)
|
| 33 |
+
|
| 34 |
+
# test 'bi-direction' psa_type
|
| 35 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 36 |
+
head = PSAHead(
|
| 37 |
+
in_channels=4, channels=2, num_classes=19, mask_size=(13, 13))
|
| 38 |
+
if torch.cuda.is_available():
|
| 39 |
+
head, inputs = to_cuda(head, inputs)
|
| 40 |
+
outputs = head(inputs)
|
| 41 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 42 |
+
|
| 43 |
+
# test 'bi-direction' psa_type, shrink_factor=1
|
| 44 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 45 |
+
head = PSAHead(
|
| 46 |
+
in_channels=4,
|
| 47 |
+
channels=2,
|
| 48 |
+
num_classes=19,
|
| 49 |
+
mask_size=(13, 13),
|
| 50 |
+
shrink_factor=1)
|
| 51 |
+
if torch.cuda.is_available():
|
| 52 |
+
head, inputs = to_cuda(head, inputs)
|
| 53 |
+
outputs = head(inputs)
|
| 54 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 55 |
+
|
| 56 |
+
# test 'bi-direction' psa_type with soft_max
|
| 57 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 58 |
+
head = PSAHead(
|
| 59 |
+
in_channels=4,
|
| 60 |
+
channels=2,
|
| 61 |
+
num_classes=19,
|
| 62 |
+
mask_size=(13, 13),
|
| 63 |
+
psa_softmax=True)
|
| 64 |
+
if torch.cuda.is_available():
|
| 65 |
+
head, inputs = to_cuda(head, inputs)
|
| 66 |
+
outputs = head(inputs)
|
| 67 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 68 |
+
|
| 69 |
+
# test 'collect' psa_type
|
| 70 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 71 |
+
head = PSAHead(
|
| 72 |
+
in_channels=4,
|
| 73 |
+
channels=2,
|
| 74 |
+
num_classes=19,
|
| 75 |
+
mask_size=(13, 13),
|
| 76 |
+
psa_type='collect')
|
| 77 |
+
if torch.cuda.is_available():
|
| 78 |
+
head, inputs = to_cuda(head, inputs)
|
| 79 |
+
outputs = head(inputs)
|
| 80 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 81 |
+
|
| 82 |
+
# test 'collect' psa_type, shrink_factor=1
|
| 83 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 84 |
+
head = PSAHead(
|
| 85 |
+
in_channels=4,
|
| 86 |
+
channels=2,
|
| 87 |
+
num_classes=19,
|
| 88 |
+
mask_size=(13, 13),
|
| 89 |
+
shrink_factor=1,
|
| 90 |
+
psa_type='collect')
|
| 91 |
+
if torch.cuda.is_available():
|
| 92 |
+
head, inputs = to_cuda(head, inputs)
|
| 93 |
+
outputs = head(inputs)
|
| 94 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 95 |
+
|
| 96 |
+
# test 'collect' psa_type, shrink_factor=1, compact=True
|
| 97 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 98 |
+
head = PSAHead(
|
| 99 |
+
in_channels=4,
|
| 100 |
+
channels=2,
|
| 101 |
+
num_classes=19,
|
| 102 |
+
mask_size=(13, 13),
|
| 103 |
+
psa_type='collect',
|
| 104 |
+
shrink_factor=1,
|
| 105 |
+
compact=True)
|
| 106 |
+
if torch.cuda.is_available():
|
| 107 |
+
head, inputs = to_cuda(head, inputs)
|
| 108 |
+
outputs = head(inputs)
|
| 109 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
| 110 |
+
|
| 111 |
+
# test 'distribute' psa_type
|
| 112 |
+
inputs = [torch.randn(1, 4, 13, 13)]
|
| 113 |
+
head = PSAHead(
|
| 114 |
+
in_channels=4,
|
| 115 |
+
channels=2,
|
| 116 |
+
num_classes=19,
|
| 117 |
+
mask_size=(13, 13),
|
| 118 |
+
psa_type='distribute')
|
| 119 |
+
if torch.cuda.is_available():
|
| 120 |
+
head, inputs = to_cuda(head, inputs)
|
| 121 |
+
outputs = head(inputs)
|
| 122 |
+
assert outputs.shape == (1, head.num_classes, 13, 13)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psp_head.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import PSPHead
|
| 6 |
+
from .utils import _conv_has_norm, to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_psp_head():
|
| 10 |
+
|
| 11 |
+
with pytest.raises(AssertionError):
|
| 12 |
+
# pool_scales must be list|tuple
|
| 13 |
+
PSPHead(in_channels=4, channels=2, num_classes=19, pool_scales=1)
|
| 14 |
+
|
| 15 |
+
# test no norm_cfg
|
| 16 |
+
head = PSPHead(in_channels=4, channels=2, num_classes=19)
|
| 17 |
+
assert not _conv_has_norm(head, sync_bn=False)
|
| 18 |
+
|
| 19 |
+
# test with norm_cfg
|
| 20 |
+
head = PSPHead(
|
| 21 |
+
in_channels=4,
|
| 22 |
+
channels=2,
|
| 23 |
+
num_classes=19,
|
| 24 |
+
norm_cfg=dict(type='SyncBN'))
|
| 25 |
+
assert _conv_has_norm(head, sync_bn=True)
|
| 26 |
+
|
| 27 |
+
inputs = [torch.randn(1, 4, 23, 23)]
|
| 28 |
+
head = PSPHead(
|
| 29 |
+
in_channels=4, channels=2, num_classes=19, pool_scales=(1, 2, 3))
|
| 30 |
+
if torch.cuda.is_available():
|
| 31 |
+
head, inputs = to_cuda(head, inputs)
|
| 32 |
+
assert head.psp_modules[0][0].output_size == 1
|
| 33 |
+
assert head.psp_modules[1][0].output_size == 2
|
| 34 |
+
assert head.psp_modules[2][0].output_size == 3
|
| 35 |
+
outputs = head(inputs)
|
| 36 |
+
assert outputs.shape == (1, head.num_classes, 23, 23)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segformer_head.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import SegformerHead
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_segformer_head():
|
| 9 |
+
with pytest.raises(AssertionError):
|
| 10 |
+
# `in_channels` must have same length as `in_index`
|
| 11 |
+
SegformerHead(
|
| 12 |
+
in_channels=(1, 2, 3), in_index=(0, 1), channels=5, num_classes=2)
|
| 13 |
+
|
| 14 |
+
H, W = (64, 64)
|
| 15 |
+
in_channels = (32, 64, 160, 256)
|
| 16 |
+
shapes = [(H // 2**(i + 2), W // 2**(i + 2))
|
| 17 |
+
for i in range(len(in_channels))]
|
| 18 |
+
model = SegformerHead(
|
| 19 |
+
in_channels=in_channels,
|
| 20 |
+
in_index=[0, 1, 2, 3],
|
| 21 |
+
channels=256,
|
| 22 |
+
num_classes=19)
|
| 23 |
+
|
| 24 |
+
with pytest.raises(IndexError):
|
| 25 |
+
# in_index must match the input feature maps.
|
| 26 |
+
inputs = [
|
| 27 |
+
torch.randn((1, in_channel, *shape))
|
| 28 |
+
for in_channel, shape in zip(in_channels, shapes)
|
| 29 |
+
][:3]
|
| 30 |
+
temp = model(inputs)
|
| 31 |
+
|
| 32 |
+
# Normal Input
|
| 33 |
+
# ((1, 32, 16, 16), (1, 64, 8, 8), (1, 160, 4, 4), (1, 256, 2, 2)
|
| 34 |
+
inputs = [
|
| 35 |
+
torch.randn((1, in_channel, *shape))
|
| 36 |
+
for in_channel, shape in zip(in_channels, shapes)
|
| 37 |
+
]
|
| 38 |
+
temp = model(inputs)
|
| 39 |
+
|
| 40 |
+
assert temp.shape == (1, 19, H // 4, W // 4)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segmenter_mask_head.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models.decode_heads import SegmenterMaskTransformerHead
|
| 5 |
+
from .utils import _conv_has_norm, to_cuda
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_segmenter_mask_transformer_head():
|
| 9 |
+
head = SegmenterMaskTransformerHead(
|
| 10 |
+
in_channels=2,
|
| 11 |
+
channels=2,
|
| 12 |
+
num_classes=150,
|
| 13 |
+
num_layers=2,
|
| 14 |
+
num_heads=3,
|
| 15 |
+
embed_dims=192,
|
| 16 |
+
dropout_ratio=0.0)
|
| 17 |
+
assert _conv_has_norm(head, sync_bn=True)
|
| 18 |
+
head.init_weights()
|
| 19 |
+
|
| 20 |
+
inputs = [torch.randn(1, 2, 32, 32)]
|
| 21 |
+
if torch.cuda.is_available():
|
| 22 |
+
head, inputs = to_cuda(head, inputs)
|
| 23 |
+
outputs = head(inputs)
|
| 24 |
+
assert outputs.shape == (1, head.num_classes, 32, 32)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_mla_head.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import SETRMLAHead
|
| 6 |
+
from .utils import to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_setr_mla_head(capsys):
|
| 10 |
+
|
| 11 |
+
with pytest.raises(AssertionError):
|
| 12 |
+
# MLA requires input multiple stage feature information.
|
| 13 |
+
SETRMLAHead(in_channels=8, channels=4, num_classes=19, in_index=1)
|
| 14 |
+
|
| 15 |
+
with pytest.raises(AssertionError):
|
| 16 |
+
# multiple in_indexs requires multiple in_channels.
|
| 17 |
+
SETRMLAHead(
|
| 18 |
+
in_channels=8, channels=4, num_classes=19, in_index=(0, 1, 2, 3))
|
| 19 |
+
|
| 20 |
+
with pytest.raises(AssertionError):
|
| 21 |
+
# channels should be len(in_channels) * mla_channels
|
| 22 |
+
SETRMLAHead(
|
| 23 |
+
in_channels=(8, 8, 8, 8),
|
| 24 |
+
channels=8,
|
| 25 |
+
mla_channels=4,
|
| 26 |
+
in_index=(0, 1, 2, 3),
|
| 27 |
+
num_classes=19)
|
| 28 |
+
|
| 29 |
+
# test inference of MLA head
|
| 30 |
+
img_size = (8, 8)
|
| 31 |
+
patch_size = 4
|
| 32 |
+
head = SETRMLAHead(
|
| 33 |
+
in_channels=(8, 8, 8, 8),
|
| 34 |
+
channels=16,
|
| 35 |
+
mla_channels=4,
|
| 36 |
+
in_index=(0, 1, 2, 3),
|
| 37 |
+
num_classes=19,
|
| 38 |
+
norm_cfg=dict(type='BN'))
|
| 39 |
+
|
| 40 |
+
h, w = img_size[0] // patch_size, img_size[1] // patch_size
|
| 41 |
+
# Input square NCHW format feature information
|
| 42 |
+
x = [
|
| 43 |
+
torch.randn(1, 8, h, w),
|
| 44 |
+
torch.randn(1, 8, h, w),
|
| 45 |
+
torch.randn(1, 8, h, w),
|
| 46 |
+
torch.randn(1, 8, h, w)
|
| 47 |
+
]
|
| 48 |
+
if torch.cuda.is_available():
|
| 49 |
+
head, x = to_cuda(head, x)
|
| 50 |
+
out = head(x)
|
| 51 |
+
assert out.shape == (1, head.num_classes, h * 4, w * 4)
|
| 52 |
+
|
| 53 |
+
# Input non-square NCHW format feature information
|
| 54 |
+
x = [
|
| 55 |
+
torch.randn(1, 8, h, w * 2),
|
| 56 |
+
torch.randn(1, 8, h, w * 2),
|
| 57 |
+
torch.randn(1, 8, h, w * 2),
|
| 58 |
+
torch.randn(1, 8, h, w * 2)
|
| 59 |
+
]
|
| 60 |
+
if torch.cuda.is_available():
|
| 61 |
+
head, x = to_cuda(head, x)
|
| 62 |
+
out = head(x)
|
| 63 |
+
assert out.shape == (1, head.num_classes, h * 4, w * 8)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_up_head.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import SETRUPHead
|
| 6 |
+
from .utils import to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_setr_up_head(capsys):
|
| 10 |
+
|
| 11 |
+
with pytest.raises(AssertionError):
|
| 12 |
+
# kernel_size must be [1/3]
|
| 13 |
+
SETRUPHead(num_classes=19, kernel_size=2)
|
| 14 |
+
|
| 15 |
+
with pytest.raises(AssertionError):
|
| 16 |
+
# in_channels must be int type and in_channels must be same
|
| 17 |
+
# as embed_dim.
|
| 18 |
+
SETRUPHead(in_channels=(4, 4), channels=2, num_classes=19)
|
| 19 |
+
|
| 20 |
+
# test init_cfg of head
|
| 21 |
+
head = SETRUPHead(
|
| 22 |
+
in_channels=4,
|
| 23 |
+
channels=2,
|
| 24 |
+
norm_cfg=dict(type='SyncBN'),
|
| 25 |
+
num_classes=19,
|
| 26 |
+
init_cfg=dict(type='Kaiming'))
|
| 27 |
+
super(SETRUPHead, head).init_weights()
|
| 28 |
+
|
| 29 |
+
# test inference of Naive head
|
| 30 |
+
# the auxiliary head of Naive head is same as Naive head
|
| 31 |
+
img_size = (4, 4)
|
| 32 |
+
patch_size = 2
|
| 33 |
+
head = SETRUPHead(
|
| 34 |
+
in_channels=4,
|
| 35 |
+
channels=2,
|
| 36 |
+
num_classes=19,
|
| 37 |
+
num_convs=1,
|
| 38 |
+
up_scale=4,
|
| 39 |
+
kernel_size=1,
|
| 40 |
+
norm_cfg=dict(type='BN'))
|
| 41 |
+
|
| 42 |
+
h, w = img_size[0] // patch_size, img_size[1] // patch_size
|
| 43 |
+
|
| 44 |
+
# Input square NCHW format feature information
|
| 45 |
+
x = [torch.randn(1, 4, h, w)]
|
| 46 |
+
if torch.cuda.is_available():
|
| 47 |
+
head, x = to_cuda(head, x)
|
| 48 |
+
out = head(x)
|
| 49 |
+
assert out.shape == (1, head.num_classes, h * 4, w * 4)
|
| 50 |
+
|
| 51 |
+
# Input non-square NCHW format feature information
|
| 52 |
+
x = [torch.randn(1, 4, h, w * 2)]
|
| 53 |
+
if torch.cuda.is_available():
|
| 54 |
+
head, x = to_cuda(head, x)
|
| 55 |
+
out = head(x)
|
| 56 |
+
assert out.shape == (1, head.num_classes, h * 4, w * 8)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_stdc_head.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models.decode_heads import STDCHead
|
| 5 |
+
from .utils import to_cuda
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_stdc_head():
|
| 9 |
+
inputs = [torch.randn(1, 32, 21, 21)]
|
| 10 |
+
head = STDCHead(
|
| 11 |
+
in_channels=32,
|
| 12 |
+
channels=8,
|
| 13 |
+
num_convs=1,
|
| 14 |
+
num_classes=2,
|
| 15 |
+
in_index=-1,
|
| 16 |
+
loss_decode=[
|
| 17 |
+
dict(
|
| 18 |
+
type='CrossEntropyLoss', loss_name='loss_ce', loss_weight=1.0),
|
| 19 |
+
dict(type='DiceLoss', loss_name='loss_dice', loss_weight=1.0)
|
| 20 |
+
])
|
| 21 |
+
if torch.cuda.is_available():
|
| 22 |
+
head, inputs = to_cuda(head, inputs)
|
| 23 |
+
outputs = head(inputs)
|
| 24 |
+
assert isinstance(outputs, torch.Tensor) and len(outputs) == 1
|
| 25 |
+
assert outputs.shape == torch.Size([1, head.num_classes, 21, 21])
|
| 26 |
+
|
| 27 |
+
fake_label = torch.ones_like(
|
| 28 |
+
outputs[:, 0:1, :, :], dtype=torch.int16).long()
|
| 29 |
+
loss = head.losses(seg_logit=outputs, seg_label=fake_label)
|
| 30 |
+
assert loss['loss_ce'] != torch.zeros_like(loss['loss_ce'])
|
| 31 |
+
assert loss['loss_dice'] != torch.zeros_like(loss['loss_dice'])
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_uper_head.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.decode_heads import UPerHead
|
| 6 |
+
from .utils import _conv_has_norm, to_cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_uper_head():
|
| 10 |
+
|
| 11 |
+
with pytest.raises(AssertionError):
|
| 12 |
+
# fpn_in_channels must be list|tuple
|
| 13 |
+
UPerHead(in_channels=4, channels=2, num_classes=19)
|
| 14 |
+
|
| 15 |
+
# test no norm_cfg
|
| 16 |
+
head = UPerHead(
|
| 17 |
+
in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1])
|
| 18 |
+
assert not _conv_has_norm(head, sync_bn=False)
|
| 19 |
+
|
| 20 |
+
# test with norm_cfg
|
| 21 |
+
head = UPerHead(
|
| 22 |
+
in_channels=[4, 2],
|
| 23 |
+
channels=2,
|
| 24 |
+
num_classes=19,
|
| 25 |
+
norm_cfg=dict(type='SyncBN'),
|
| 26 |
+
in_index=[-2, -1])
|
| 27 |
+
assert _conv_has_norm(head, sync_bn=True)
|
| 28 |
+
|
| 29 |
+
inputs = [torch.randn(1, 4, 45, 45), torch.randn(1, 2, 21, 21)]
|
| 30 |
+
head = UPerHead(
|
| 31 |
+
in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1])
|
| 32 |
+
if torch.cuda.is_available():
|
| 33 |
+
head, inputs = to_cuda(head, inputs)
|
| 34 |
+
outputs = head(inputs)
|
| 35 |
+
assert outputs.shape == (1, head.num_classes, 45, 45)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/utils.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from mmcv.cnn import ConvModule
|
| 3 |
+
from mmcv.utils.parrots_wrapper import SyncBatchNorm
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _conv_has_norm(module, sync_bn):
|
| 7 |
+
for m in module.modules():
|
| 8 |
+
if isinstance(m, ConvModule):
|
| 9 |
+
if not m.with_norm:
|
| 10 |
+
return False
|
| 11 |
+
if sync_bn:
|
| 12 |
+
if not isinstance(m.bn, SyncBatchNorm):
|
| 13 |
+
return False
|
| 14 |
+
return True
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def to_cuda(module, data):
|
| 18 |
+
module = module.cuda()
|
| 19 |
+
if isinstance(data, list):
|
| 20 |
+
for i in range(len(data)):
|
| 21 |
+
data[i] = data[i].cuda()
|
| 22 |
+
return module, data
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_ce_loss.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.losses.cross_entropy_loss import _expand_onehot_labels
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize('use_sigmoid', [True, False])
|
| 9 |
+
@pytest.mark.parametrize('reduction', ('mean', 'sum', 'none'))
|
| 10 |
+
@pytest.mark.parametrize('avg_non_ignore', [True, False])
|
| 11 |
+
@pytest.mark.parametrize('bce_input_same_dim', [True, False])
|
| 12 |
+
def test_ce_loss(use_sigmoid, reduction, avg_non_ignore, bce_input_same_dim):
|
| 13 |
+
from mmseg.models import build_loss
|
| 14 |
+
|
| 15 |
+
# use_mask and use_sigmoid cannot be true at the same time
|
| 16 |
+
with pytest.raises(AssertionError):
|
| 17 |
+
loss_cfg = dict(
|
| 18 |
+
type='CrossEntropyLoss',
|
| 19 |
+
use_mask=True,
|
| 20 |
+
use_sigmoid=True,
|
| 21 |
+
loss_weight=1.0)
|
| 22 |
+
build_loss(loss_cfg)
|
| 23 |
+
|
| 24 |
+
# test loss with simple case for ce/bce
|
| 25 |
+
fake_pred = torch.Tensor([[100, -100]])
|
| 26 |
+
fake_label = torch.Tensor([1]).long()
|
| 27 |
+
loss_cls_cfg = dict(
|
| 28 |
+
type='CrossEntropyLoss',
|
| 29 |
+
use_sigmoid=use_sigmoid,
|
| 30 |
+
loss_weight=1.0,
|
| 31 |
+
avg_non_ignore=avg_non_ignore,
|
| 32 |
+
loss_name='loss_ce')
|
| 33 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 34 |
+
if use_sigmoid:
|
| 35 |
+
assert torch.allclose(
|
| 36 |
+
loss_cls(fake_pred, fake_label), torch.tensor(100.))
|
| 37 |
+
else:
|
| 38 |
+
assert torch.allclose(
|
| 39 |
+
loss_cls(fake_pred, fake_label), torch.tensor(200.))
|
| 40 |
+
|
| 41 |
+
# test loss with complicated case for ce/bce
|
| 42 |
+
# when avg_non_ignore is False, `avg_factor` would not be calculated
|
| 43 |
+
fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5)
|
| 44 |
+
fake_label = torch.ones(2, 8, 8).long()
|
| 45 |
+
fake_label[:, 0, 0] = 255
|
| 46 |
+
fake_weight = None
|
| 47 |
+
# extra test bce loss when pred.shape == label.shape
|
| 48 |
+
if use_sigmoid and bce_input_same_dim:
|
| 49 |
+
fake_pred = torch.randn(2, 10).float()
|
| 50 |
+
fake_label = torch.rand(2, 10).float()
|
| 51 |
+
fake_weight = torch.rand(2, 10) # set weight in forward function
|
| 52 |
+
fake_label[0, [1, 2, 5, 7]] = 255 # set ignore_index
|
| 53 |
+
fake_label[1, [0, 5, 8, 9]] = 255
|
| 54 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 55 |
+
loss = loss_cls(
|
| 56 |
+
fake_pred, fake_label, weight=fake_weight, ignore_index=255)
|
| 57 |
+
if use_sigmoid:
|
| 58 |
+
if fake_pred.dim() != fake_label.dim():
|
| 59 |
+
fake_label, weight, valid_mask = _expand_onehot_labels(
|
| 60 |
+
labels=fake_label,
|
| 61 |
+
label_weights=None,
|
| 62 |
+
target_shape=fake_pred.shape,
|
| 63 |
+
ignore_index=255)
|
| 64 |
+
else:
|
| 65 |
+
# should mask out the ignored elements
|
| 66 |
+
valid_mask = ((fake_label >= 0) & (fake_label != 255)).float()
|
| 67 |
+
weight = valid_mask
|
| 68 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 69 |
+
fake_pred,
|
| 70 |
+
fake_label.float(),
|
| 71 |
+
reduction='none',
|
| 72 |
+
weight=fake_weight)
|
| 73 |
+
if avg_non_ignore:
|
| 74 |
+
avg_factor = valid_mask.sum().item()
|
| 75 |
+
torch_loss = (torch_loss * weight).sum() / avg_factor
|
| 76 |
+
else:
|
| 77 |
+
torch_loss = (torch_loss * weight).mean()
|
| 78 |
+
else:
|
| 79 |
+
if avg_non_ignore:
|
| 80 |
+
torch_loss = torch.nn.functional.cross_entropy(
|
| 81 |
+
fake_pred, fake_label, reduction='mean', ignore_index=255)
|
| 82 |
+
else:
|
| 83 |
+
torch_loss = torch.nn.functional.cross_entropy(
|
| 84 |
+
fake_pred, fake_label, reduction='sum',
|
| 85 |
+
ignore_index=255) / fake_label.numel()
|
| 86 |
+
assert torch.allclose(loss, torch_loss)
|
| 87 |
+
|
| 88 |
+
if use_sigmoid:
|
| 89 |
+
# test loss with complicated case for ce/bce
|
| 90 |
+
# when avg_non_ignore is False, `avg_factor` would not be calculated
|
| 91 |
+
fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5)
|
| 92 |
+
fake_label = torch.ones(2, 8, 8).long()
|
| 93 |
+
fake_label[:, 0, 0] = 255
|
| 94 |
+
fake_weight = torch.rand(2, 8, 8)
|
| 95 |
+
|
| 96 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 97 |
+
loss = loss_cls(
|
| 98 |
+
fake_pred, fake_label, weight=fake_weight, ignore_index=255)
|
| 99 |
+
if use_sigmoid:
|
| 100 |
+
fake_label, weight, valid_mask = _expand_onehot_labels(
|
| 101 |
+
labels=fake_label,
|
| 102 |
+
label_weights=None,
|
| 103 |
+
target_shape=fake_pred.shape,
|
| 104 |
+
ignore_index=255)
|
| 105 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 106 |
+
fake_pred,
|
| 107 |
+
fake_label.float(),
|
| 108 |
+
reduction='none',
|
| 109 |
+
weight=fake_weight.unsqueeze(1).expand(fake_pred.shape))
|
| 110 |
+
if avg_non_ignore:
|
| 111 |
+
avg_factor = valid_mask.sum().item()
|
| 112 |
+
torch_loss = (torch_loss * weight).sum() / avg_factor
|
| 113 |
+
else:
|
| 114 |
+
torch_loss = (torch_loss * weight).mean()
|
| 115 |
+
assert torch.allclose(loss, torch_loss)
|
| 116 |
+
|
| 117 |
+
# test loss with class weights from file
|
| 118 |
+
fake_pred = torch.Tensor([[100, -100]])
|
| 119 |
+
fake_label = torch.Tensor([1]).long()
|
| 120 |
+
import os
|
| 121 |
+
import tempfile
|
| 122 |
+
|
| 123 |
+
import mmcv
|
| 124 |
+
import numpy as np
|
| 125 |
+
tmp_file = tempfile.NamedTemporaryFile()
|
| 126 |
+
|
| 127 |
+
mmcv.dump([0.8, 0.2], f'{tmp_file.name}.pkl', 'pkl') # from pkl file
|
| 128 |
+
loss_cls_cfg = dict(
|
| 129 |
+
type='CrossEntropyLoss',
|
| 130 |
+
use_sigmoid=False,
|
| 131 |
+
class_weight=f'{tmp_file.name}.pkl',
|
| 132 |
+
loss_weight=1.0,
|
| 133 |
+
loss_name='loss_ce')
|
| 134 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 135 |
+
assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(40.))
|
| 136 |
+
|
| 137 |
+
np.save(f'{tmp_file.name}.npy', np.array([0.8, 0.2])) # from npy file
|
| 138 |
+
loss_cls_cfg = dict(
|
| 139 |
+
type='CrossEntropyLoss',
|
| 140 |
+
use_sigmoid=False,
|
| 141 |
+
class_weight=f'{tmp_file.name}.npy',
|
| 142 |
+
loss_weight=1.0,
|
| 143 |
+
loss_name='loss_ce')
|
| 144 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 145 |
+
assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(40.))
|
| 146 |
+
tmp_file.close()
|
| 147 |
+
os.remove(f'{tmp_file.name}.pkl')
|
| 148 |
+
os.remove(f'{tmp_file.name}.npy')
|
| 149 |
+
|
| 150 |
+
loss_cls_cfg = dict(
|
| 151 |
+
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)
|
| 152 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 153 |
+
assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(200.))
|
| 154 |
+
|
| 155 |
+
# test `avg_non_ignore` without ignore index would not affect ce/bce loss
|
| 156 |
+
# when reduction='sum'/'none'/'mean'
|
| 157 |
+
loss_cls_cfg1 = dict(
|
| 158 |
+
type='CrossEntropyLoss',
|
| 159 |
+
use_sigmoid=use_sigmoid,
|
| 160 |
+
reduction=reduction,
|
| 161 |
+
loss_weight=1.0,
|
| 162 |
+
avg_non_ignore=True)
|
| 163 |
+
loss_cls1 = build_loss(loss_cls_cfg1)
|
| 164 |
+
loss_cls_cfg2 = dict(
|
| 165 |
+
type='CrossEntropyLoss',
|
| 166 |
+
use_sigmoid=use_sigmoid,
|
| 167 |
+
reduction=reduction,
|
| 168 |
+
loss_weight=1.0,
|
| 169 |
+
avg_non_ignore=False)
|
| 170 |
+
loss_cls2 = build_loss(loss_cls_cfg2)
|
| 171 |
+
assert torch.allclose(
|
| 172 |
+
loss_cls1(fake_pred, fake_label, ignore_index=255) / fake_pred.numel(),
|
| 173 |
+
loss_cls2(fake_pred, fake_label, ignore_index=255) / fake_pred.numel(),
|
| 174 |
+
atol=1e-4)
|
| 175 |
+
|
| 176 |
+
# test ce/bce loss with ignore index and class weight
|
| 177 |
+
# in 5-way classification
|
| 178 |
+
if use_sigmoid:
|
| 179 |
+
# test bce loss when pred.shape == or != label.shape
|
| 180 |
+
if bce_input_same_dim:
|
| 181 |
+
fake_pred = torch.randn(2, 10).float()
|
| 182 |
+
fake_label = torch.rand(2, 10).float()
|
| 183 |
+
class_weight = torch.rand(2, 10)
|
| 184 |
+
else:
|
| 185 |
+
fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5)
|
| 186 |
+
fake_label = torch.ones(2, 8, 8).long()
|
| 187 |
+
class_weight = torch.randn(2, 21, 8, 8)
|
| 188 |
+
fake_label, weight, valid_mask = _expand_onehot_labels(
|
| 189 |
+
labels=fake_label,
|
| 190 |
+
label_weights=None,
|
| 191 |
+
target_shape=fake_pred.shape,
|
| 192 |
+
ignore_index=-100)
|
| 193 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 194 |
+
fake_pred,
|
| 195 |
+
fake_label.float(),
|
| 196 |
+
reduction='mean',
|
| 197 |
+
pos_weight=class_weight)
|
| 198 |
+
else:
|
| 199 |
+
fake_pred = torch.randn(2, 5, 10).float() # 5-way classification
|
| 200 |
+
fake_label = torch.randint(0, 5, (2, 10)).long()
|
| 201 |
+
class_weight = torch.rand(5)
|
| 202 |
+
class_weight /= class_weight.sum()
|
| 203 |
+
torch_loss = torch.nn.functional.cross_entropy(
|
| 204 |
+
fake_pred, fake_label, reduction='sum',
|
| 205 |
+
weight=class_weight) / fake_label.numel()
|
| 206 |
+
loss_cls_cfg = dict(
|
| 207 |
+
type='CrossEntropyLoss',
|
| 208 |
+
use_sigmoid=use_sigmoid,
|
| 209 |
+
reduction='mean',
|
| 210 |
+
class_weight=class_weight,
|
| 211 |
+
loss_weight=1.0,
|
| 212 |
+
avg_non_ignore=avg_non_ignore)
|
| 213 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 214 |
+
|
| 215 |
+
# test cross entropy loss has name `loss_ce`
|
| 216 |
+
assert loss_cls.loss_name == 'loss_ce'
|
| 217 |
+
# test avg_non_ignore is in extra_repr
|
| 218 |
+
assert loss_cls.extra_repr() == f'avg_non_ignore={avg_non_ignore}'
|
| 219 |
+
|
| 220 |
+
loss = loss_cls(fake_pred, fake_label)
|
| 221 |
+
assert torch.allclose(loss, torch_loss)
|
| 222 |
+
|
| 223 |
+
fake_label[0, [1, 2, 5, 7]] = 10 # set ignore_index
|
| 224 |
+
fake_label[1, [0, 5, 8, 9]] = 10
|
| 225 |
+
loss = loss_cls(fake_pred, fake_label, ignore_index=10)
|
| 226 |
+
if use_sigmoid:
|
| 227 |
+
if avg_non_ignore:
|
| 228 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 229 |
+
fake_pred[fake_label != 10],
|
| 230 |
+
fake_label[fake_label != 10].float(),
|
| 231 |
+
pos_weight=class_weight[fake_label != 10],
|
| 232 |
+
reduction='mean')
|
| 233 |
+
else:
|
| 234 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 235 |
+
fake_pred[fake_label != 10],
|
| 236 |
+
fake_label[fake_label != 10].float(),
|
| 237 |
+
pos_weight=class_weight[fake_label != 10],
|
| 238 |
+
reduction='sum') / fake_label.numel()
|
| 239 |
+
else:
|
| 240 |
+
if avg_non_ignore:
|
| 241 |
+
torch_loss = torch.nn.functional.cross_entropy(
|
| 242 |
+
fake_pred,
|
| 243 |
+
fake_label,
|
| 244 |
+
ignore_index=10,
|
| 245 |
+
reduction='sum',
|
| 246 |
+
weight=class_weight) / fake_label[fake_label != 10].numel()
|
| 247 |
+
else:
|
| 248 |
+
torch_loss = torch.nn.functional.cross_entropy(
|
| 249 |
+
fake_pred,
|
| 250 |
+
fake_label,
|
| 251 |
+
ignore_index=10,
|
| 252 |
+
reduction='sum',
|
| 253 |
+
weight=class_weight) / fake_label.numel()
|
| 254 |
+
assert torch.allclose(loss, torch_loss)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@pytest.mark.parametrize('avg_non_ignore', [True, False])
|
| 258 |
+
@pytest.mark.parametrize('with_weight', [True, False])
|
| 259 |
+
def test_binary_class_ce_loss(avg_non_ignore, with_weight):
|
| 260 |
+
from mmseg.models import build_loss
|
| 261 |
+
|
| 262 |
+
fake_pred = torch.rand(3, 1, 10, 10)
|
| 263 |
+
fake_label = torch.randint(0, 2, (3, 10, 10))
|
| 264 |
+
fake_weight = torch.rand(3, 10, 10)
|
| 265 |
+
valid_mask = ((fake_label >= 0) & (fake_label != 255)).float()
|
| 266 |
+
weight = valid_mask
|
| 267 |
+
|
| 268 |
+
torch_loss = torch.nn.functional.binary_cross_entropy_with_logits(
|
| 269 |
+
fake_pred,
|
| 270 |
+
fake_label.unsqueeze(1).float(),
|
| 271 |
+
reduction='none',
|
| 272 |
+
weight=fake_weight.unsqueeze(1).float() if with_weight else None)
|
| 273 |
+
if avg_non_ignore:
|
| 274 |
+
eps = torch.finfo(torch.float32).eps
|
| 275 |
+
avg_factor = valid_mask.sum().item()
|
| 276 |
+
torch_loss = (torch_loss * weight.unsqueeze(1)).sum() / (
|
| 277 |
+
avg_factor + eps)
|
| 278 |
+
else:
|
| 279 |
+
torch_loss = (torch_loss * weight.unsqueeze(1)).mean()
|
| 280 |
+
|
| 281 |
+
loss_cls_cfg = dict(
|
| 282 |
+
type='CrossEntropyLoss',
|
| 283 |
+
use_sigmoid=True,
|
| 284 |
+
loss_weight=1.0,
|
| 285 |
+
avg_non_ignore=avg_non_ignore,
|
| 286 |
+
reduction='mean',
|
| 287 |
+
loss_name='loss_ce')
|
| 288 |
+
loss_cls = build_loss(loss_cls_cfg)
|
| 289 |
+
loss = loss_cls(
|
| 290 |
+
fake_pred,
|
| 291 |
+
fake_label,
|
| 292 |
+
weight=fake_weight if with_weight else None,
|
| 293 |
+
ignore_index=255)
|
| 294 |
+
assert torch.allclose(loss, torch_loss)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_dice_loss.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_dice_lose():
|
| 6 |
+
from mmseg.models import build_loss
|
| 7 |
+
|
| 8 |
+
# test dice loss with loss_type = 'multi_class'
|
| 9 |
+
loss_cfg = dict(
|
| 10 |
+
type='DiceLoss',
|
| 11 |
+
reduction='none',
|
| 12 |
+
class_weight=[1.0, 2.0, 3.0],
|
| 13 |
+
loss_weight=1.0,
|
| 14 |
+
ignore_index=1,
|
| 15 |
+
loss_name='loss_dice')
|
| 16 |
+
dice_loss = build_loss(loss_cfg)
|
| 17 |
+
logits = torch.rand(8, 3, 4, 4)
|
| 18 |
+
labels = (torch.rand(8, 4, 4) * 3).long()
|
| 19 |
+
dice_loss(logits, labels)
|
| 20 |
+
|
| 21 |
+
# test loss with class weights from file
|
| 22 |
+
import os
|
| 23 |
+
import tempfile
|
| 24 |
+
|
| 25 |
+
import mmcv
|
| 26 |
+
import numpy as np
|
| 27 |
+
tmp_file = tempfile.NamedTemporaryFile()
|
| 28 |
+
|
| 29 |
+
mmcv.dump([1.0, 2.0, 3.0], f'{tmp_file.name}.pkl', 'pkl') # from pkl file
|
| 30 |
+
loss_cfg = dict(
|
| 31 |
+
type='DiceLoss',
|
| 32 |
+
reduction='none',
|
| 33 |
+
class_weight=f'{tmp_file.name}.pkl',
|
| 34 |
+
loss_weight=1.0,
|
| 35 |
+
ignore_index=1,
|
| 36 |
+
loss_name='loss_dice')
|
| 37 |
+
dice_loss = build_loss(loss_cfg)
|
| 38 |
+
dice_loss(logits, labels, ignore_index=None)
|
| 39 |
+
|
| 40 |
+
np.save(f'{tmp_file.name}.npy', np.array([1.0, 2.0, 3.0])) # from npy file
|
| 41 |
+
loss_cfg = dict(
|
| 42 |
+
type='DiceLoss',
|
| 43 |
+
reduction='none',
|
| 44 |
+
class_weight=f'{tmp_file.name}.pkl',
|
| 45 |
+
loss_weight=1.0,
|
| 46 |
+
ignore_index=1,
|
| 47 |
+
loss_name='loss_dice')
|
| 48 |
+
dice_loss = build_loss(loss_cfg)
|
| 49 |
+
dice_loss(logits, labels, ignore_index=None)
|
| 50 |
+
tmp_file.close()
|
| 51 |
+
os.remove(f'{tmp_file.name}.pkl')
|
| 52 |
+
os.remove(f'{tmp_file.name}.npy')
|
| 53 |
+
|
| 54 |
+
# test dice loss with loss_type = 'binary'
|
| 55 |
+
loss_cfg = dict(
|
| 56 |
+
type='DiceLoss',
|
| 57 |
+
smooth=2,
|
| 58 |
+
exponent=3,
|
| 59 |
+
reduction='sum',
|
| 60 |
+
loss_weight=1.0,
|
| 61 |
+
ignore_index=0,
|
| 62 |
+
loss_name='loss_dice')
|
| 63 |
+
dice_loss = build_loss(loss_cfg)
|
| 64 |
+
logits = torch.rand(8, 2, 4, 4)
|
| 65 |
+
labels = (torch.rand(8, 4, 4) * 2).long()
|
| 66 |
+
dice_loss(logits, labels)
|
| 67 |
+
|
| 68 |
+
# test dice loss has name `loss_dice`
|
| 69 |
+
loss_cfg = dict(
|
| 70 |
+
type='DiceLoss',
|
| 71 |
+
smooth=2,
|
| 72 |
+
exponent=3,
|
| 73 |
+
reduction='sum',
|
| 74 |
+
loss_weight=1.0,
|
| 75 |
+
ignore_index=0,
|
| 76 |
+
loss_name='loss_dice')
|
| 77 |
+
dice_loss = build_loss(loss_cfg)
|
| 78 |
+
assert dice_loss.loss_name == 'loss_dice'
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_focal_loss.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
from mmseg.models import build_loss
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# test focal loss with use_sigmoid=False
|
| 10 |
+
def test_use_sigmoid():
|
| 11 |
+
# can't init with use_sigmoid=True
|
| 12 |
+
with pytest.raises(AssertionError):
|
| 13 |
+
loss_cfg = dict(type='FocalLoss', use_sigmoid=False)
|
| 14 |
+
build_loss(loss_cfg)
|
| 15 |
+
|
| 16 |
+
# can't forward with use_sigmoid=True
|
| 17 |
+
with pytest.raises(NotImplementedError):
|
| 18 |
+
loss_cfg = dict(type='FocalLoss', use_sigmoid=True)
|
| 19 |
+
focal_loss = build_loss(loss_cfg)
|
| 20 |
+
focal_loss.use_sigmoid = False
|
| 21 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 22 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 23 |
+
focal_loss(fake_pred, fake_target)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# reduction type must be 'none', 'mean' or 'sum'
|
| 27 |
+
def test_wrong_reduction_type():
|
| 28 |
+
# can't init with wrong reduction
|
| 29 |
+
with pytest.raises(AssertionError):
|
| 30 |
+
loss_cfg = dict(type='FocalLoss', reduction='test')
|
| 31 |
+
build_loss(loss_cfg)
|
| 32 |
+
|
| 33 |
+
# can't forward with wrong reduction override
|
| 34 |
+
with pytest.raises(AssertionError):
|
| 35 |
+
loss_cfg = dict(type='FocalLoss')
|
| 36 |
+
focal_loss = build_loss(loss_cfg)
|
| 37 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 38 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 39 |
+
focal_loss(fake_pred, fake_target, reduction_override='test')
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# test focal loss can handle input parameters with
|
| 43 |
+
# unacceptable types
|
| 44 |
+
def test_unacceptable_parameters():
|
| 45 |
+
with pytest.raises(AssertionError):
|
| 46 |
+
loss_cfg = dict(type='FocalLoss', gamma='test')
|
| 47 |
+
build_loss(loss_cfg)
|
| 48 |
+
with pytest.raises(AssertionError):
|
| 49 |
+
loss_cfg = dict(type='FocalLoss', alpha='test')
|
| 50 |
+
build_loss(loss_cfg)
|
| 51 |
+
with pytest.raises(AssertionError):
|
| 52 |
+
loss_cfg = dict(type='FocalLoss', class_weight='test')
|
| 53 |
+
build_loss(loss_cfg)
|
| 54 |
+
with pytest.raises(AssertionError):
|
| 55 |
+
loss_cfg = dict(type='FocalLoss', loss_weight='test')
|
| 56 |
+
build_loss(loss_cfg)
|
| 57 |
+
with pytest.raises(AssertionError):
|
| 58 |
+
loss_cfg = dict(type='FocalLoss', loss_name=123)
|
| 59 |
+
build_loss(loss_cfg)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# test if focal loss can be correctly initialize
|
| 63 |
+
def test_init_focal_loss():
|
| 64 |
+
loss_cfg = dict(
|
| 65 |
+
type='FocalLoss',
|
| 66 |
+
use_sigmoid=True,
|
| 67 |
+
gamma=3.0,
|
| 68 |
+
alpha=3.0,
|
| 69 |
+
class_weight=[1, 2, 3, 4],
|
| 70 |
+
reduction='sum')
|
| 71 |
+
focal_loss = build_loss(loss_cfg)
|
| 72 |
+
assert focal_loss.use_sigmoid is True
|
| 73 |
+
assert focal_loss.gamma == 3.0
|
| 74 |
+
assert focal_loss.alpha == 3.0
|
| 75 |
+
assert focal_loss.reduction == 'sum'
|
| 76 |
+
assert focal_loss.class_weight == [1, 2, 3, 4]
|
| 77 |
+
assert focal_loss.loss_weight == 1.0
|
| 78 |
+
assert focal_loss.loss_name == 'loss_focal'
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# test reduction override
|
| 82 |
+
def test_reduction_override():
|
| 83 |
+
loss_cfg = dict(type='FocalLoss', reduction='mean')
|
| 84 |
+
focal_loss = build_loss(loss_cfg)
|
| 85 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 86 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 87 |
+
loss = focal_loss(fake_pred, fake_target, reduction_override='none')
|
| 88 |
+
assert loss.shape == fake_pred.shape
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# test wrong pred and target shape
|
| 92 |
+
def test_wrong_pred_and_target_shape():
|
| 93 |
+
loss_cfg = dict(type='FocalLoss')
|
| 94 |
+
focal_loss = build_loss(loss_cfg)
|
| 95 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 96 |
+
fake_target = torch.randint(0, 4, (3, 2, 2))
|
| 97 |
+
fake_target = F.one_hot(fake_target, num_classes=4)
|
| 98 |
+
fake_target = fake_target.permute(0, 3, 1, 2)
|
| 99 |
+
with pytest.raises(AssertionError):
|
| 100 |
+
focal_loss(fake_pred, fake_target)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# test forward with different shape of target
|
| 104 |
+
def test_forward_with_different_shape_of_target():
|
| 105 |
+
loss_cfg = dict(type='FocalLoss')
|
| 106 |
+
focal_loss = build_loss(loss_cfg)
|
| 107 |
+
|
| 108 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 109 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 110 |
+
loss1 = focal_loss(fake_pred, fake_target)
|
| 111 |
+
|
| 112 |
+
fake_target = F.one_hot(fake_target, num_classes=4)
|
| 113 |
+
fake_target = fake_target.permute(0, 3, 1, 2)
|
| 114 |
+
loss2 = focal_loss(fake_pred, fake_target)
|
| 115 |
+
assert loss1 == loss2
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# test forward with weight
|
| 119 |
+
def test_forward_with_weight():
|
| 120 |
+
loss_cfg = dict(type='FocalLoss')
|
| 121 |
+
focal_loss = build_loss(loss_cfg)
|
| 122 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 123 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 124 |
+
weight = torch.rand(3 * 5 * 6, 1)
|
| 125 |
+
loss1 = focal_loss(fake_pred, fake_target, weight=weight)
|
| 126 |
+
|
| 127 |
+
weight2 = weight.view(-1)
|
| 128 |
+
loss2 = focal_loss(fake_pred, fake_target, weight=weight2)
|
| 129 |
+
|
| 130 |
+
weight3 = weight.expand(3 * 5 * 6, 4)
|
| 131 |
+
loss3 = focal_loss(fake_pred, fake_target, weight=weight3)
|
| 132 |
+
assert loss1 == loss2 == loss3
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# test none reduction type
|
| 136 |
+
def test_none_reduction_type():
|
| 137 |
+
loss_cfg = dict(type='FocalLoss', reduction='none')
|
| 138 |
+
focal_loss = build_loss(loss_cfg)
|
| 139 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 140 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 141 |
+
loss = focal_loss(fake_pred, fake_target)
|
| 142 |
+
assert loss.shape == fake_pred.shape
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# test the usage of class weight
|
| 146 |
+
def test_class_weight():
|
| 147 |
+
loss_cfg_cw = dict(
|
| 148 |
+
type='FocalLoss', reduction='none', class_weight=[1.0, 2.0, 3.0, 4.0])
|
| 149 |
+
loss_cfg = dict(type='FocalLoss', reduction='none')
|
| 150 |
+
focal_loss_cw = build_loss(loss_cfg_cw)
|
| 151 |
+
focal_loss = build_loss(loss_cfg)
|
| 152 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 153 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 154 |
+
loss_cw = focal_loss_cw(fake_pred, fake_target)
|
| 155 |
+
loss = focal_loss(fake_pred, fake_target)
|
| 156 |
+
weight = torch.tensor([1, 2, 3, 4]).view(1, 4, 1, 1)
|
| 157 |
+
assert (loss * weight == loss_cw).all()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# test ignore index
|
| 161 |
+
def test_ignore_index():
|
| 162 |
+
loss_cfg = dict(type='FocalLoss', reduction='none')
|
| 163 |
+
# ignore_index within C classes
|
| 164 |
+
focal_loss = build_loss(loss_cfg)
|
| 165 |
+
fake_pred = torch.rand(3, 5, 5, 6)
|
| 166 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 167 |
+
dim1 = torch.randint(0, 3, (4, ))
|
| 168 |
+
dim2 = torch.randint(0, 5, (4, ))
|
| 169 |
+
dim3 = torch.randint(0, 6, (4, ))
|
| 170 |
+
fake_target[dim1, dim2, dim3] = 4
|
| 171 |
+
loss1 = focal_loss(fake_pred, fake_target, ignore_index=4)
|
| 172 |
+
one_hot_target = F.one_hot(fake_target, num_classes=5)
|
| 173 |
+
one_hot_target = one_hot_target.permute(0, 3, 1, 2)
|
| 174 |
+
loss2 = focal_loss(fake_pred, one_hot_target, ignore_index=4)
|
| 175 |
+
assert (loss1 == loss2).all()
|
| 176 |
+
assert (loss1[dim1, :, dim2, dim3] == 0).all()
|
| 177 |
+
assert (loss2[dim1, :, dim2, dim3] == 0).all()
|
| 178 |
+
|
| 179 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 180 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 181 |
+
loss1 = focal_loss(fake_pred, fake_target, ignore_index=2)
|
| 182 |
+
one_hot_target = F.one_hot(fake_target, num_classes=4)
|
| 183 |
+
one_hot_target = one_hot_target.permute(0, 3, 1, 2)
|
| 184 |
+
loss2 = focal_loss(fake_pred, one_hot_target, ignore_index=2)
|
| 185 |
+
ignore_mask = one_hot_target == 2
|
| 186 |
+
assert (loss1 == loss2).all()
|
| 187 |
+
assert torch.sum(loss1 * ignore_mask) == 0
|
| 188 |
+
assert torch.sum(loss2 * ignore_mask) == 0
|
| 189 |
+
|
| 190 |
+
# ignore index is not in prediction's classes
|
| 191 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 192 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 193 |
+
dim1 = torch.randint(0, 3, (4, ))
|
| 194 |
+
dim2 = torch.randint(0, 5, (4, ))
|
| 195 |
+
dim3 = torch.randint(0, 6, (4, ))
|
| 196 |
+
fake_target[dim1, dim2, dim3] = 255
|
| 197 |
+
loss1 = focal_loss(fake_pred, fake_target, ignore_index=255)
|
| 198 |
+
assert (loss1[dim1, :, dim2, dim3] == 0).all()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# test list alpha
|
| 202 |
+
def test_alpha():
|
| 203 |
+
loss_cfg = dict(type='FocalLoss')
|
| 204 |
+
focal_loss = build_loss(loss_cfg)
|
| 205 |
+
alpha_float = 0.4
|
| 206 |
+
alpha = [0.4, 0.4, 0.4, 0.4]
|
| 207 |
+
alpha2 = [0.1, 0.3, 0.2, 0.1]
|
| 208 |
+
fake_pred = torch.rand(3, 4, 5, 6)
|
| 209 |
+
fake_target = torch.randint(0, 4, (3, 5, 6))
|
| 210 |
+
focal_loss.alpha = alpha_float
|
| 211 |
+
loss1 = focal_loss(fake_pred, fake_target)
|
| 212 |
+
focal_loss.alpha = alpha
|
| 213 |
+
loss2 = focal_loss(fake_pred, fake_target)
|
| 214 |
+
assert loss1 == loss2
|
| 215 |
+
focal_loss.alpha = alpha2
|
| 216 |
+
focal_loss(fake_pred, fake_target)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_lovasz_loss.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_lovasz_loss():
|
| 7 |
+
from mmseg.models import build_loss
|
| 8 |
+
|
| 9 |
+
# loss_type should be 'binary' or 'multi_class'
|
| 10 |
+
with pytest.raises(AssertionError):
|
| 11 |
+
loss_cfg = dict(
|
| 12 |
+
type='LovaszLoss',
|
| 13 |
+
loss_type='Binary',
|
| 14 |
+
reduction='none',
|
| 15 |
+
loss_weight=1.0,
|
| 16 |
+
loss_name='loss_lovasz')
|
| 17 |
+
build_loss(loss_cfg)
|
| 18 |
+
|
| 19 |
+
# reduction should be 'none' when per_image is False.
|
| 20 |
+
with pytest.raises(AssertionError):
|
| 21 |
+
loss_cfg = dict(
|
| 22 |
+
type='LovaszLoss',
|
| 23 |
+
loss_type='multi_class',
|
| 24 |
+
loss_name='loss_lovasz')
|
| 25 |
+
build_loss(loss_cfg)
|
| 26 |
+
|
| 27 |
+
# test lovasz loss with loss_type = 'multi_class' and per_image = False
|
| 28 |
+
loss_cfg = dict(
|
| 29 |
+
type='LovaszLoss',
|
| 30 |
+
reduction='none',
|
| 31 |
+
loss_weight=1.0,
|
| 32 |
+
loss_name='loss_lovasz')
|
| 33 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 34 |
+
logits = torch.rand(1, 3, 4, 4)
|
| 35 |
+
labels = (torch.rand(1, 4, 4) * 2).long()
|
| 36 |
+
lovasz_loss(logits, labels)
|
| 37 |
+
|
| 38 |
+
# test lovasz loss with loss_type = 'multi_class' and per_image = True
|
| 39 |
+
loss_cfg = dict(
|
| 40 |
+
type='LovaszLoss',
|
| 41 |
+
per_image=True,
|
| 42 |
+
reduction='mean',
|
| 43 |
+
class_weight=[1.0, 2.0, 3.0],
|
| 44 |
+
loss_weight=1.0,
|
| 45 |
+
loss_name='loss_lovasz')
|
| 46 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 47 |
+
logits = torch.rand(1, 3, 4, 4)
|
| 48 |
+
labels = (torch.rand(1, 4, 4) * 2).long()
|
| 49 |
+
lovasz_loss(logits, labels, ignore_index=None)
|
| 50 |
+
|
| 51 |
+
# test loss with class weights from file
|
| 52 |
+
import os
|
| 53 |
+
import tempfile
|
| 54 |
+
|
| 55 |
+
import mmcv
|
| 56 |
+
import numpy as np
|
| 57 |
+
tmp_file = tempfile.NamedTemporaryFile()
|
| 58 |
+
|
| 59 |
+
mmcv.dump([1.0, 2.0, 3.0], f'{tmp_file.name}.pkl', 'pkl') # from pkl file
|
| 60 |
+
loss_cfg = dict(
|
| 61 |
+
type='LovaszLoss',
|
| 62 |
+
per_image=True,
|
| 63 |
+
reduction='mean',
|
| 64 |
+
class_weight=f'{tmp_file.name}.pkl',
|
| 65 |
+
loss_weight=1.0,
|
| 66 |
+
loss_name='loss_lovasz')
|
| 67 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 68 |
+
lovasz_loss(logits, labels, ignore_index=None)
|
| 69 |
+
|
| 70 |
+
np.save(f'{tmp_file.name}.npy', np.array([1.0, 2.0, 3.0])) # from npy file
|
| 71 |
+
loss_cfg = dict(
|
| 72 |
+
type='LovaszLoss',
|
| 73 |
+
per_image=True,
|
| 74 |
+
reduction='mean',
|
| 75 |
+
class_weight=f'{tmp_file.name}.npy',
|
| 76 |
+
loss_weight=1.0,
|
| 77 |
+
loss_name='loss_lovasz')
|
| 78 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 79 |
+
lovasz_loss(logits, labels, ignore_index=None)
|
| 80 |
+
tmp_file.close()
|
| 81 |
+
os.remove(f'{tmp_file.name}.pkl')
|
| 82 |
+
os.remove(f'{tmp_file.name}.npy')
|
| 83 |
+
|
| 84 |
+
# test lovasz loss with loss_type = 'binary' and per_image = False
|
| 85 |
+
loss_cfg = dict(
|
| 86 |
+
type='LovaszLoss',
|
| 87 |
+
loss_type='binary',
|
| 88 |
+
reduction='none',
|
| 89 |
+
loss_weight=1.0,
|
| 90 |
+
loss_name='loss_lovasz')
|
| 91 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 92 |
+
logits = torch.rand(2, 4, 4)
|
| 93 |
+
labels = (torch.rand(2, 4, 4)).long()
|
| 94 |
+
lovasz_loss(logits, labels)
|
| 95 |
+
|
| 96 |
+
# test lovasz loss with loss_type = 'binary' and per_image = True
|
| 97 |
+
loss_cfg = dict(
|
| 98 |
+
type='LovaszLoss',
|
| 99 |
+
loss_type='binary',
|
| 100 |
+
per_image=True,
|
| 101 |
+
reduction='mean',
|
| 102 |
+
loss_weight=1.0,
|
| 103 |
+
loss_name='loss_lovasz')
|
| 104 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 105 |
+
logits = torch.rand(2, 4, 4)
|
| 106 |
+
labels = (torch.rand(2, 4, 4)).long()
|
| 107 |
+
lovasz_loss(logits, labels, ignore_index=None)
|
| 108 |
+
|
| 109 |
+
# test lovasz loss has name `loss_lovasz`
|
| 110 |
+
loss_cfg = dict(
|
| 111 |
+
type='LovaszLoss',
|
| 112 |
+
loss_type='binary',
|
| 113 |
+
per_image=True,
|
| 114 |
+
reduction='mean',
|
| 115 |
+
loss_weight=1.0,
|
| 116 |
+
loss_name='loss_lovasz')
|
| 117 |
+
lovasz_loss = build_loss(loss_cfg)
|
| 118 |
+
assert lovasz_loss.loss_name == 'loss_lovasz'
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_utils.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from mmseg.models.losses import Accuracy, reduce_loss, weight_reduce_loss
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_weight_reduce_loss():
|
| 10 |
+
loss = torch.rand(1, 3, 4, 4)
|
| 11 |
+
weight = torch.zeros(1, 3, 4, 4)
|
| 12 |
+
weight[:, :, :2, :2] = 1
|
| 13 |
+
|
| 14 |
+
# test reduce_loss()
|
| 15 |
+
reduced = reduce_loss(loss, 'none')
|
| 16 |
+
assert reduced is loss
|
| 17 |
+
|
| 18 |
+
reduced = reduce_loss(loss, 'mean')
|
| 19 |
+
np.testing.assert_almost_equal(reduced.numpy(), loss.mean())
|
| 20 |
+
|
| 21 |
+
reduced = reduce_loss(loss, 'sum')
|
| 22 |
+
np.testing.assert_almost_equal(reduced.numpy(), loss.sum())
|
| 23 |
+
|
| 24 |
+
# test weight_reduce_loss()
|
| 25 |
+
reduced = weight_reduce_loss(loss, weight=None, reduction='none')
|
| 26 |
+
assert reduced is loss
|
| 27 |
+
|
| 28 |
+
reduced = weight_reduce_loss(loss, weight=weight, reduction='mean')
|
| 29 |
+
target = (loss * weight).mean()
|
| 30 |
+
np.testing.assert_almost_equal(reduced.numpy(), target)
|
| 31 |
+
|
| 32 |
+
reduced = weight_reduce_loss(loss, weight=weight, reduction='sum')
|
| 33 |
+
np.testing.assert_almost_equal(reduced.numpy(), (loss * weight).sum())
|
| 34 |
+
|
| 35 |
+
with pytest.raises(AssertionError):
|
| 36 |
+
weight_wrong = weight[0, 0, ...]
|
| 37 |
+
weight_reduce_loss(loss, weight=weight_wrong, reduction='mean')
|
| 38 |
+
|
| 39 |
+
with pytest.raises(AssertionError):
|
| 40 |
+
weight_wrong = weight[:, 0:2, ...]
|
| 41 |
+
weight_reduce_loss(loss, weight=weight_wrong, reduction='mean')
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_accuracy():
|
| 45 |
+
# test for empty pred
|
| 46 |
+
pred = torch.empty(0, 4)
|
| 47 |
+
label = torch.empty(0)
|
| 48 |
+
accuracy = Accuracy(topk=1)
|
| 49 |
+
acc = accuracy(pred, label)
|
| 50 |
+
assert acc.item() == 0
|
| 51 |
+
|
| 52 |
+
pred = torch.Tensor([[0.2, 0.3, 0.6, 0.5], [0.1, 0.1, 0.2, 0.6],
|
| 53 |
+
[0.9, 0.0, 0.0, 0.1], [0.4, 0.7, 0.1, 0.1],
|
| 54 |
+
[0.0, 0.0, 0.99, 0]])
|
| 55 |
+
# test for ignore_index
|
| 56 |
+
true_label = torch.Tensor([2, 3, 0, 1, 2]).long()
|
| 57 |
+
accuracy = Accuracy(topk=1, ignore_index=None)
|
| 58 |
+
acc = accuracy(pred, true_label)
|
| 59 |
+
assert torch.allclose(acc, torch.tensor(100.0))
|
| 60 |
+
|
| 61 |
+
# test for ignore_index with a wrong prediction of that index
|
| 62 |
+
true_label = torch.Tensor([2, 3, 1, 1, 2]).long()
|
| 63 |
+
accuracy = Accuracy(topk=1, ignore_index=1)
|
| 64 |
+
acc = accuracy(pred, true_label)
|
| 65 |
+
assert torch.allclose(acc, torch.tensor(100.0))
|
| 66 |
+
|
| 67 |
+
# test for ignore_index 1 with a wrong prediction of other index
|
| 68 |
+
true_label = torch.Tensor([2, 0, 0, 1, 2]).long()
|
| 69 |
+
accuracy = Accuracy(topk=1, ignore_index=1)
|
| 70 |
+
acc = accuracy(pred, true_label)
|
| 71 |
+
assert torch.allclose(acc, torch.tensor(75.0))
|
| 72 |
+
|
| 73 |
+
# test for ignore_index 4 with a wrong prediction of other index
|
| 74 |
+
true_label = torch.Tensor([2, 0, 0, 1, 2]).long()
|
| 75 |
+
accuracy = Accuracy(topk=1, ignore_index=4)
|
| 76 |
+
acc = accuracy(pred, true_label)
|
| 77 |
+
assert torch.allclose(acc, torch.tensor(80.0))
|
| 78 |
+
|
| 79 |
+
# test for ignoring all the pixels
|
| 80 |
+
true_label = torch.Tensor([2, 2, 2, 2, 2]).long()
|
| 81 |
+
accuracy = Accuracy(topk=1, ignore_index=2)
|
| 82 |
+
acc = accuracy(pred, true_label)
|
| 83 |
+
assert torch.allclose(acc, torch.tensor(100.0))
|
| 84 |
+
|
| 85 |
+
# test for top1
|
| 86 |
+
true_label = torch.Tensor([2, 3, 0, 1, 2]).long()
|
| 87 |
+
accuracy = Accuracy(topk=1)
|
| 88 |
+
acc = accuracy(pred, true_label)
|
| 89 |
+
assert torch.allclose(acc, torch.tensor(100.0))
|
| 90 |
+
|
| 91 |
+
# test for top1 with score thresh=0.8
|
| 92 |
+
true_label = torch.Tensor([2, 3, 0, 1, 2]).long()
|
| 93 |
+
accuracy = Accuracy(topk=1, thresh=0.8)
|
| 94 |
+
acc = accuracy(pred, true_label)
|
| 95 |
+
assert torch.allclose(acc, torch.tensor(40.0))
|
| 96 |
+
|
| 97 |
+
# test for top2
|
| 98 |
+
accuracy = Accuracy(topk=2)
|
| 99 |
+
label = torch.Tensor([3, 2, 0, 0, 2]).long()
|
| 100 |
+
acc = accuracy(pred, label)
|
| 101 |
+
assert torch.allclose(acc, torch.tensor(100.0))
|
| 102 |
+
|
| 103 |
+
# test for both top1 and top2
|
| 104 |
+
accuracy = Accuracy(topk=(1, 2))
|
| 105 |
+
true_label = torch.Tensor([2, 3, 0, 1, 2]).long()
|
| 106 |
+
acc = accuracy(pred, true_label)
|
| 107 |
+
for a in acc:
|
| 108 |
+
assert torch.allclose(a, torch.tensor(100.0))
|
| 109 |
+
|
| 110 |
+
# topk is larger than pred class number
|
| 111 |
+
with pytest.raises(AssertionError):
|
| 112 |
+
accuracy = Accuracy(topk=5)
|
| 113 |
+
accuracy(pred, true_label)
|
| 114 |
+
|
| 115 |
+
# wrong topk type
|
| 116 |
+
with pytest.raises(AssertionError):
|
| 117 |
+
accuracy = Accuracy(topk='wrong type')
|
| 118 |
+
accuracy(pred, true_label)
|
| 119 |
+
|
| 120 |
+
# label size is larger than required
|
| 121 |
+
with pytest.raises(AssertionError):
|
| 122 |
+
label = torch.Tensor([2, 3, 0, 1, 2, 0]).long() # size mismatch
|
| 123 |
+
accuracy = Accuracy()
|
| 124 |
+
accuracy(pred, label)
|
| 125 |
+
|
| 126 |
+
# wrong pred dimension
|
| 127 |
+
with pytest.raises(AssertionError):
|
| 128 |
+
accuracy = Accuracy()
|
| 129 |
+
accuracy(pred[:, :, None], true_label)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_feature2pyramid.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models import Feature2Pyramid
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_feature2pyramid():
|
| 9 |
+
# test
|
| 10 |
+
rescales = [4, 2, 1, 0.5]
|
| 11 |
+
embed_dim = 64
|
| 12 |
+
inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))]
|
| 13 |
+
|
| 14 |
+
fpn = Feature2Pyramid(
|
| 15 |
+
embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True))
|
| 16 |
+
outputs = fpn(inputs)
|
| 17 |
+
assert outputs[0].shape == torch.Size([1, 64, 128, 128])
|
| 18 |
+
assert outputs[1].shape == torch.Size([1, 64, 64, 64])
|
| 19 |
+
assert outputs[2].shape == torch.Size([1, 64, 32, 32])
|
| 20 |
+
assert outputs[3].shape == torch.Size([1, 64, 16, 16])
|
| 21 |
+
|
| 22 |
+
# test rescales = [2, 1, 0.5, 0.25]
|
| 23 |
+
rescales = [2, 1, 0.5, 0.25]
|
| 24 |
+
inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))]
|
| 25 |
+
|
| 26 |
+
fpn = Feature2Pyramid(
|
| 27 |
+
embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True))
|
| 28 |
+
outputs = fpn(inputs)
|
| 29 |
+
assert outputs[0].shape == torch.Size([1, 64, 64, 64])
|
| 30 |
+
assert outputs[1].shape == torch.Size([1, 64, 32, 32])
|
| 31 |
+
assert outputs[2].shape == torch.Size([1, 64, 16, 16])
|
| 32 |
+
assert outputs[3].shape == torch.Size([1, 64, 8, 8])
|
| 33 |
+
|
| 34 |
+
# test rescales = [4, 2, 0.25, 0]
|
| 35 |
+
rescales = [4, 2, 0.25, 0]
|
| 36 |
+
with pytest.raises(KeyError):
|
| 37 |
+
fpn = Feature2Pyramid(
|
| 38 |
+
embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True))
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_fpn.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models import FPN
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_fpn():
|
| 8 |
+
in_channels = [64, 128, 256, 512]
|
| 9 |
+
inputs = [
|
| 10 |
+
torch.randn(1, c, 56 // 2**i, 56 // 2**i)
|
| 11 |
+
for i, c in enumerate(in_channels)
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
fpn = FPN(in_channels, 64, len(in_channels))
|
| 15 |
+
outputs = fpn(inputs)
|
| 16 |
+
assert outputs[0].shape == torch.Size([1, 64, 56, 56])
|
| 17 |
+
assert outputs[1].shape == torch.Size([1, 64, 28, 28])
|
| 18 |
+
assert outputs[2].shape == torch.Size([1, 64, 14, 14])
|
| 19 |
+
assert outputs[3].shape == torch.Size([1, 64, 7, 7])
|
| 20 |
+
|
| 21 |
+
fpn = FPN(
|
| 22 |
+
in_channels,
|
| 23 |
+
64,
|
| 24 |
+
len(in_channels),
|
| 25 |
+
upsample_cfg=dict(mode='nearest', scale_factor=2.0))
|
| 26 |
+
outputs = fpn(inputs)
|
| 27 |
+
assert outputs[0].shape == torch.Size([1, 64, 56, 56])
|
| 28 |
+
assert outputs[1].shape == torch.Size([1, 64, 28, 28])
|
| 29 |
+
assert outputs[2].shape == torch.Size([1, 64, 14, 14])
|
| 30 |
+
assert outputs[3].shape == torch.Size([1, 64, 7, 7])
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_ic_neck.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.necks import ICNeck
|
| 6 |
+
from mmseg.models.necks.ic_neck import CascadeFeatureFusion
|
| 7 |
+
from ..test_heads.utils import _conv_has_norm, to_cuda
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_ic_neck():
|
| 11 |
+
# test with norm_cfg
|
| 12 |
+
neck = ICNeck(
|
| 13 |
+
in_channels=(4, 16, 16),
|
| 14 |
+
out_channels=8,
|
| 15 |
+
norm_cfg=dict(type='SyncBN'),
|
| 16 |
+
align_corners=False)
|
| 17 |
+
assert _conv_has_norm(neck, sync_bn=True)
|
| 18 |
+
|
| 19 |
+
inputs = [
|
| 20 |
+
torch.randn(1, 4, 32, 64),
|
| 21 |
+
torch.randn(1, 16, 16, 32),
|
| 22 |
+
torch.randn(1, 16, 8, 16)
|
| 23 |
+
]
|
| 24 |
+
neck = ICNeck(
|
| 25 |
+
in_channels=(4, 16, 16),
|
| 26 |
+
out_channels=4,
|
| 27 |
+
norm_cfg=dict(type='BN', requires_grad=True),
|
| 28 |
+
align_corners=False)
|
| 29 |
+
if torch.cuda.is_available():
|
| 30 |
+
neck, inputs = to_cuda(neck, inputs)
|
| 31 |
+
|
| 32 |
+
outputs = neck(inputs)
|
| 33 |
+
assert outputs[0].shape == (1, 4, 16, 32)
|
| 34 |
+
assert outputs[1].shape == (1, 4, 32, 64)
|
| 35 |
+
assert outputs[1].shape == (1, 4, 32, 64)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_ic_neck_cascade_feature_fusion():
|
| 39 |
+
cff = CascadeFeatureFusion(64, 64, 32)
|
| 40 |
+
assert cff.conv_low.in_channels == 64
|
| 41 |
+
assert cff.conv_low.out_channels == 32
|
| 42 |
+
assert cff.conv_high.in_channels == 64
|
| 43 |
+
assert cff.conv_high.out_channels == 32
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_ic_neck_input_channels():
|
| 47 |
+
with pytest.raises(AssertionError):
|
| 48 |
+
# ICNet Neck input channel constraints.
|
| 49 |
+
ICNeck(
|
| 50 |
+
in_channels=(16, 64, 64, 64),
|
| 51 |
+
out_channels=32,
|
| 52 |
+
norm_cfg=dict(type='BN', requires_grad=True),
|
| 53 |
+
align_corners=False)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_jpu.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.necks import JPU
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_fastfcn_neck():
|
| 9 |
+
# Test FastFCN Standard Forward
|
| 10 |
+
model = JPU(
|
| 11 |
+
in_channels=(64, 128, 256),
|
| 12 |
+
mid_channels=64,
|
| 13 |
+
start_level=0,
|
| 14 |
+
end_level=-1,
|
| 15 |
+
dilations=(1, 2, 4, 8),
|
| 16 |
+
)
|
| 17 |
+
model.init_weights()
|
| 18 |
+
model.train()
|
| 19 |
+
batch_size = 1
|
| 20 |
+
input = [
|
| 21 |
+
torch.randn(batch_size, 64, 64, 128),
|
| 22 |
+
torch.randn(batch_size, 128, 32, 64),
|
| 23 |
+
torch.randn(batch_size, 256, 16, 32)
|
| 24 |
+
]
|
| 25 |
+
feat = model(input)
|
| 26 |
+
|
| 27 |
+
assert len(feat) == 3
|
| 28 |
+
assert feat[0].shape == torch.Size([batch_size, 64, 64, 128])
|
| 29 |
+
assert feat[1].shape == torch.Size([batch_size, 128, 32, 64])
|
| 30 |
+
assert feat[2].shape == torch.Size([batch_size, 256, 64, 128])
|
| 31 |
+
|
| 32 |
+
with pytest.raises(AssertionError):
|
| 33 |
+
# FastFCN input and in_channels constraints.
|
| 34 |
+
JPU(in_channels=(256, 64, 128), start_level=0, end_level=5)
|
| 35 |
+
|
| 36 |
+
# Test not default start_level
|
| 37 |
+
model = JPU(in_channels=(64, 128, 256), start_level=1, end_level=-1)
|
| 38 |
+
input = [
|
| 39 |
+
torch.randn(batch_size, 64, 64, 128),
|
| 40 |
+
torch.randn(batch_size, 128, 32, 64),
|
| 41 |
+
torch.randn(batch_size, 256, 16, 32)
|
| 42 |
+
]
|
| 43 |
+
feat = model(input)
|
| 44 |
+
assert len(feat) == 2
|
| 45 |
+
assert feat[0].shape == torch.Size([batch_size, 128, 32, 64])
|
| 46 |
+
assert feat[1].shape == torch.Size([batch_size, 2048, 32, 64])
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_mla_neck.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models import MLANeck
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_mla():
|
| 8 |
+
in_channels = [4, 4, 4, 4]
|
| 9 |
+
mla = MLANeck(in_channels, 32)
|
| 10 |
+
|
| 11 |
+
inputs = [torch.randn(1, c, 12, 12) for i, c in enumerate(in_channels)]
|
| 12 |
+
outputs = mla(inputs)
|
| 13 |
+
assert outputs[0].shape == torch.Size([1, 32, 12, 12])
|
| 14 |
+
assert outputs[1].shape == torch.Size([1, 32, 12, 12])
|
| 15 |
+
assert outputs[2].shape == torch.Size([1, 32, 12, 12])
|
| 16 |
+
assert outputs[3].shape == torch.Size([1, 32, 12, 12])
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_multilevel_neck.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models import MultiLevelNeck
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_multilevel_neck():
|
| 8 |
+
|
| 9 |
+
# Test init_weights
|
| 10 |
+
MultiLevelNeck([266], 32).init_weights()
|
| 11 |
+
|
| 12 |
+
# Test multi feature maps
|
| 13 |
+
in_channels = [32, 64, 128, 256]
|
| 14 |
+
inputs = [torch.randn(1, c, 14, 14) for i, c in enumerate(in_channels)]
|
| 15 |
+
|
| 16 |
+
neck = MultiLevelNeck(in_channels, 32)
|
| 17 |
+
outputs = neck(inputs)
|
| 18 |
+
assert outputs[0].shape == torch.Size([1, 32, 7, 7])
|
| 19 |
+
assert outputs[1].shape == torch.Size([1, 32, 14, 14])
|
| 20 |
+
assert outputs[2].shape == torch.Size([1, 32, 28, 28])
|
| 21 |
+
assert outputs[3].shape == torch.Size([1, 32, 56, 56])
|
| 22 |
+
|
| 23 |
+
# Test one feature map
|
| 24 |
+
in_channels = [768]
|
| 25 |
+
inputs = [torch.randn(1, 768, 14, 14)]
|
| 26 |
+
|
| 27 |
+
neck = MultiLevelNeck(in_channels, 32)
|
| 28 |
+
outputs = neck(inputs)
|
| 29 |
+
assert outputs[0].shape == torch.Size([1, 32, 7, 7])
|
| 30 |
+
assert outputs[1].shape == torch.Size([1, 32, 14, 14])
|
| 31 |
+
assert outputs[2].shape == torch.Size([1, 32, 28, 28])
|
| 32 |
+
assert outputs[3].shape == torch.Size([1, 32, 56, 56])
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from mmcv import ConfigDict
|
| 3 |
+
|
| 4 |
+
from mmseg.models import build_segmentor
|
| 5 |
+
from .utils import _segmentor_forward_train_test
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_cascade_encoder_decoder():
|
| 9 |
+
|
| 10 |
+
# test 1 decode head, w.o. aux head
|
| 11 |
+
cfg = ConfigDict(
|
| 12 |
+
type='CascadeEncoderDecoder',
|
| 13 |
+
num_stages=2,
|
| 14 |
+
backbone=dict(type='ExampleBackbone'),
|
| 15 |
+
decode_head=[
|
| 16 |
+
dict(type='ExampleDecodeHead'),
|
| 17 |
+
dict(type='ExampleCascadeDecodeHead')
|
| 18 |
+
])
|
| 19 |
+
cfg.test_cfg = ConfigDict(mode='whole')
|
| 20 |
+
segmentor = build_segmentor(cfg)
|
| 21 |
+
_segmentor_forward_train_test(segmentor)
|
| 22 |
+
|
| 23 |
+
# test slide mode
|
| 24 |
+
cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2))
|
| 25 |
+
segmentor = build_segmentor(cfg)
|
| 26 |
+
_segmentor_forward_train_test(segmentor)
|
| 27 |
+
|
| 28 |
+
# test 1 decode head, 1 aux head
|
| 29 |
+
cfg = ConfigDict(
|
| 30 |
+
type='CascadeEncoderDecoder',
|
| 31 |
+
num_stages=2,
|
| 32 |
+
backbone=dict(type='ExampleBackbone'),
|
| 33 |
+
decode_head=[
|
| 34 |
+
dict(type='ExampleDecodeHead'),
|
| 35 |
+
dict(type='ExampleCascadeDecodeHead')
|
| 36 |
+
],
|
| 37 |
+
auxiliary_head=dict(type='ExampleDecodeHead'))
|
| 38 |
+
cfg.test_cfg = ConfigDict(mode='whole')
|
| 39 |
+
segmentor = build_segmentor(cfg)
|
| 40 |
+
_segmentor_forward_train_test(segmentor)
|
| 41 |
+
|
| 42 |
+
# test 1 decode head, 2 aux head
|
| 43 |
+
cfg = ConfigDict(
|
| 44 |
+
type='CascadeEncoderDecoder',
|
| 45 |
+
num_stages=2,
|
| 46 |
+
backbone=dict(type='ExampleBackbone'),
|
| 47 |
+
decode_head=[
|
| 48 |
+
dict(type='ExampleDecodeHead'),
|
| 49 |
+
dict(type='ExampleCascadeDecodeHead')
|
| 50 |
+
],
|
| 51 |
+
auxiliary_head=[
|
| 52 |
+
dict(type='ExampleDecodeHead'),
|
| 53 |
+
dict(type='ExampleDecodeHead')
|
| 54 |
+
])
|
| 55 |
+
cfg.test_cfg = ConfigDict(mode='whole')
|
| 56 |
+
segmentor = build_segmentor(cfg)
|
| 57 |
+
_segmentor_forward_train_test(segmentor)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_encoder_decoder.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from mmcv import ConfigDict
|
| 3 |
+
|
| 4 |
+
from mmseg.models import build_segmentor
|
| 5 |
+
from .utils import _segmentor_forward_train_test
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_encoder_decoder():
|
| 9 |
+
|
| 10 |
+
# test 1 decode head, w.o. aux head
|
| 11 |
+
|
| 12 |
+
cfg = ConfigDict(
|
| 13 |
+
type='EncoderDecoder',
|
| 14 |
+
backbone=dict(type='ExampleBackbone'),
|
| 15 |
+
decode_head=dict(type='ExampleDecodeHead'),
|
| 16 |
+
train_cfg=None,
|
| 17 |
+
test_cfg=dict(mode='whole'))
|
| 18 |
+
segmentor = build_segmentor(cfg)
|
| 19 |
+
_segmentor_forward_train_test(segmentor)
|
| 20 |
+
|
| 21 |
+
# test slide mode
|
| 22 |
+
cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2))
|
| 23 |
+
segmentor = build_segmentor(cfg)
|
| 24 |
+
_segmentor_forward_train_test(segmentor)
|
| 25 |
+
|
| 26 |
+
# test 1 decode head, 1 aux head
|
| 27 |
+
cfg = ConfigDict(
|
| 28 |
+
type='EncoderDecoder',
|
| 29 |
+
backbone=dict(type='ExampleBackbone'),
|
| 30 |
+
decode_head=dict(type='ExampleDecodeHead'),
|
| 31 |
+
auxiliary_head=dict(type='ExampleDecodeHead'))
|
| 32 |
+
cfg.test_cfg = ConfigDict(mode='whole')
|
| 33 |
+
segmentor = build_segmentor(cfg)
|
| 34 |
+
_segmentor_forward_train_test(segmentor)
|
| 35 |
+
|
| 36 |
+
# test 1 decode head, 2 aux head
|
| 37 |
+
cfg = ConfigDict(
|
| 38 |
+
type='EncoderDecoder',
|
| 39 |
+
backbone=dict(type='ExampleBackbone'),
|
| 40 |
+
decode_head=dict(type='ExampleDecodeHead'),
|
| 41 |
+
auxiliary_head=[
|
| 42 |
+
dict(type='ExampleDecodeHead'),
|
| 43 |
+
dict(type='ExampleDecodeHead')
|
| 44 |
+
])
|
| 45 |
+
cfg.test_cfg = ConfigDict(mode='whole')
|
| 46 |
+
segmentor = build_segmentor(cfg)
|
| 47 |
+
_segmentor_forward_train_test(segmentor)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/utils.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from mmseg.models import BACKBONES, HEADS
|
| 7 |
+
from mmseg.models.decode_heads.cascade_decode_head import BaseCascadeDecodeHead
|
| 8 |
+
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _demo_mm_inputs(input_shape=(1, 3, 8, 16), num_classes=10):
|
| 12 |
+
"""Create a superset of inputs needed to run test or train batches.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
input_shape (tuple):
|
| 16 |
+
input batch dimensions
|
| 17 |
+
|
| 18 |
+
num_classes (int):
|
| 19 |
+
number of semantic classes
|
| 20 |
+
"""
|
| 21 |
+
(N, C, H, W) = input_shape
|
| 22 |
+
|
| 23 |
+
rng = np.random.RandomState(0)
|
| 24 |
+
|
| 25 |
+
imgs = rng.rand(*input_shape)
|
| 26 |
+
segs = rng.randint(
|
| 27 |
+
low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8)
|
| 28 |
+
|
| 29 |
+
img_metas = [{
|
| 30 |
+
'img_shape': (H, W, C),
|
| 31 |
+
'ori_shape': (H, W, C),
|
| 32 |
+
'pad_shape': (H, W, C),
|
| 33 |
+
'filename': '<demo>.png',
|
| 34 |
+
'scale_factor': 1.0,
|
| 35 |
+
'flip': False,
|
| 36 |
+
'flip_direction': 'horizontal'
|
| 37 |
+
} for _ in range(N)]
|
| 38 |
+
|
| 39 |
+
mm_inputs = {
|
| 40 |
+
'imgs': torch.FloatTensor(imgs),
|
| 41 |
+
'img_metas': img_metas,
|
| 42 |
+
'gt_semantic_seg': torch.LongTensor(segs)
|
| 43 |
+
}
|
| 44 |
+
return mm_inputs
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@BACKBONES.register_module()
|
| 48 |
+
class ExampleBackbone(nn.Module):
|
| 49 |
+
|
| 50 |
+
def __init__(self):
|
| 51 |
+
super(ExampleBackbone, self).__init__()
|
| 52 |
+
self.conv = nn.Conv2d(3, 3, 3)
|
| 53 |
+
|
| 54 |
+
def init_weights(self, pretrained=None):
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
return [self.conv(x)]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@HEADS.register_module()
|
| 62 |
+
class ExampleDecodeHead(BaseDecodeHead):
|
| 63 |
+
|
| 64 |
+
def __init__(self):
|
| 65 |
+
super(ExampleDecodeHead, self).__init__(3, 3, num_classes=19)
|
| 66 |
+
|
| 67 |
+
def forward(self, inputs):
|
| 68 |
+
return self.cls_seg(inputs[0])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@HEADS.register_module()
|
| 72 |
+
class ExampleCascadeDecodeHead(BaseCascadeDecodeHead):
|
| 73 |
+
|
| 74 |
+
def __init__(self):
|
| 75 |
+
super(ExampleCascadeDecodeHead, self).__init__(3, 3, num_classes=19)
|
| 76 |
+
|
| 77 |
+
def forward(self, inputs, prev_out):
|
| 78 |
+
return self.cls_seg(inputs[0])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _segmentor_forward_train_test(segmentor):
|
| 82 |
+
if isinstance(segmentor.decode_head, nn.ModuleList):
|
| 83 |
+
num_classes = segmentor.decode_head[-1].num_classes
|
| 84 |
+
else:
|
| 85 |
+
num_classes = segmentor.decode_head.num_classes
|
| 86 |
+
# batch_size=2 for BatchNorm
|
| 87 |
+
mm_inputs = _demo_mm_inputs(num_classes=num_classes)
|
| 88 |
+
|
| 89 |
+
imgs = mm_inputs.pop('imgs')
|
| 90 |
+
img_metas = mm_inputs.pop('img_metas')
|
| 91 |
+
gt_semantic_seg = mm_inputs['gt_semantic_seg']
|
| 92 |
+
|
| 93 |
+
# convert to cuda Tensor if applicable
|
| 94 |
+
if torch.cuda.is_available():
|
| 95 |
+
segmentor = segmentor.cuda()
|
| 96 |
+
imgs = imgs.cuda()
|
| 97 |
+
gt_semantic_seg = gt_semantic_seg.cuda()
|
| 98 |
+
|
| 99 |
+
# Test forward train
|
| 100 |
+
losses = segmentor.forward(
|
| 101 |
+
imgs, img_metas, gt_semantic_seg=gt_semantic_seg, return_loss=True)
|
| 102 |
+
assert isinstance(losses, dict)
|
| 103 |
+
|
| 104 |
+
# Test train_step
|
| 105 |
+
data_batch = dict(
|
| 106 |
+
img=imgs, img_metas=img_metas, gt_semantic_seg=gt_semantic_seg)
|
| 107 |
+
outputs = segmentor.train_step(data_batch, None)
|
| 108 |
+
assert isinstance(outputs, dict)
|
| 109 |
+
assert 'loss' in outputs
|
| 110 |
+
assert 'log_vars' in outputs
|
| 111 |
+
assert 'num_samples' in outputs
|
| 112 |
+
|
| 113 |
+
# Test val_step
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
segmentor.eval()
|
| 116 |
+
data_batch = dict(
|
| 117 |
+
img=imgs, img_metas=img_metas, gt_semantic_seg=gt_semantic_seg)
|
| 118 |
+
outputs = segmentor.val_step(data_batch, None)
|
| 119 |
+
assert isinstance(outputs, dict)
|
| 120 |
+
assert 'loss' in outputs
|
| 121 |
+
assert 'log_vars' in outputs
|
| 122 |
+
assert 'num_samples' in outputs
|
| 123 |
+
|
| 124 |
+
# Test forward simple test
|
| 125 |
+
with torch.no_grad():
|
| 126 |
+
segmentor.eval()
|
| 127 |
+
# pack into lists
|
| 128 |
+
img_list = [img[None, :] for img in imgs]
|
| 129 |
+
img_meta_list = [[img_meta] for img_meta in img_metas]
|
| 130 |
+
segmentor.forward(img_list, img_meta_list, return_loss=False)
|
| 131 |
+
|
| 132 |
+
# Test forward aug test
|
| 133 |
+
with torch.no_grad():
|
| 134 |
+
segmentor.eval()
|
| 135 |
+
# pack into lists
|
| 136 |
+
img_list = [img[None, :] for img in imgs]
|
| 137 |
+
img_list = img_list + img_list
|
| 138 |
+
img_meta_list = [[img_meta] for img_meta in img_metas]
|
| 139 |
+
img_meta_list = img_meta_list + img_meta_list
|
| 140 |
+
segmentor.forward(img_list, img_meta_list, return_loss=False)
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_embed.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.models.utils.embed import AdaptivePadding, PatchEmbed, PatchMerging
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_adaptive_padding():
|
| 9 |
+
|
| 10 |
+
for padding in ('same', 'corner'):
|
| 11 |
+
kernel_size = 16
|
| 12 |
+
stride = 16
|
| 13 |
+
dilation = 1
|
| 14 |
+
input = torch.rand(1, 1, 15, 17)
|
| 15 |
+
adap_pool = AdaptivePadding(
|
| 16 |
+
kernel_size=kernel_size,
|
| 17 |
+
stride=stride,
|
| 18 |
+
dilation=dilation,
|
| 19 |
+
padding=padding)
|
| 20 |
+
out = adap_pool(input)
|
| 21 |
+
# padding to divisible by 16
|
| 22 |
+
assert (out.shape[2], out.shape[3]) == (16, 32)
|
| 23 |
+
input = torch.rand(1, 1, 16, 17)
|
| 24 |
+
out = adap_pool(input)
|
| 25 |
+
# padding to divisible by 16
|
| 26 |
+
assert (out.shape[2], out.shape[3]) == (16, 32)
|
| 27 |
+
|
| 28 |
+
kernel_size = (2, 2)
|
| 29 |
+
stride = (2, 2)
|
| 30 |
+
dilation = (1, 1)
|
| 31 |
+
|
| 32 |
+
adap_pad = AdaptivePadding(
|
| 33 |
+
kernel_size=kernel_size,
|
| 34 |
+
stride=stride,
|
| 35 |
+
dilation=dilation,
|
| 36 |
+
padding=padding)
|
| 37 |
+
input = torch.rand(1, 1, 11, 13)
|
| 38 |
+
out = adap_pad(input)
|
| 39 |
+
# padding to divisible by 2
|
| 40 |
+
assert (out.shape[2], out.shape[3]) == (12, 14)
|
| 41 |
+
|
| 42 |
+
kernel_size = (2, 2)
|
| 43 |
+
stride = (10, 10)
|
| 44 |
+
dilation = (1, 1)
|
| 45 |
+
|
| 46 |
+
adap_pad = AdaptivePadding(
|
| 47 |
+
kernel_size=kernel_size,
|
| 48 |
+
stride=stride,
|
| 49 |
+
dilation=dilation,
|
| 50 |
+
padding=padding)
|
| 51 |
+
input = torch.rand(1, 1, 10, 13)
|
| 52 |
+
out = adap_pad(input)
|
| 53 |
+
# no padding
|
| 54 |
+
assert (out.shape[2], out.shape[3]) == (10, 13)
|
| 55 |
+
|
| 56 |
+
kernel_size = (11, 11)
|
| 57 |
+
adap_pad = AdaptivePadding(
|
| 58 |
+
kernel_size=kernel_size,
|
| 59 |
+
stride=stride,
|
| 60 |
+
dilation=dilation,
|
| 61 |
+
padding=padding)
|
| 62 |
+
input = torch.rand(1, 1, 11, 13)
|
| 63 |
+
out = adap_pad(input)
|
| 64 |
+
# all padding
|
| 65 |
+
assert (out.shape[2], out.shape[3]) == (21, 21)
|
| 66 |
+
|
| 67 |
+
# test padding as kernel is (7,9)
|
| 68 |
+
input = torch.rand(1, 1, 11, 13)
|
| 69 |
+
stride = (3, 4)
|
| 70 |
+
kernel_size = (4, 5)
|
| 71 |
+
dilation = (2, 2)
|
| 72 |
+
# actually (7, 9)
|
| 73 |
+
adap_pad = AdaptivePadding(
|
| 74 |
+
kernel_size=kernel_size,
|
| 75 |
+
stride=stride,
|
| 76 |
+
dilation=dilation,
|
| 77 |
+
padding=padding)
|
| 78 |
+
dilation_out = adap_pad(input)
|
| 79 |
+
assert (dilation_out.shape[2], dilation_out.shape[3]) == (16, 21)
|
| 80 |
+
kernel_size = (7, 9)
|
| 81 |
+
dilation = (1, 1)
|
| 82 |
+
adap_pad = AdaptivePadding(
|
| 83 |
+
kernel_size=kernel_size,
|
| 84 |
+
stride=stride,
|
| 85 |
+
dilation=dilation,
|
| 86 |
+
padding=padding)
|
| 87 |
+
kernel79_out = adap_pad(input)
|
| 88 |
+
assert (kernel79_out.shape[2], kernel79_out.shape[3]) == (16, 21)
|
| 89 |
+
assert kernel79_out.shape == dilation_out.shape
|
| 90 |
+
|
| 91 |
+
# assert only support "same" "corner"
|
| 92 |
+
with pytest.raises(AssertionError):
|
| 93 |
+
AdaptivePadding(
|
| 94 |
+
kernel_size=kernel_size,
|
| 95 |
+
stride=stride,
|
| 96 |
+
dilation=dilation,
|
| 97 |
+
padding=1)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_patch_embed():
|
| 101 |
+
B = 2
|
| 102 |
+
H = 3
|
| 103 |
+
W = 4
|
| 104 |
+
C = 3
|
| 105 |
+
embed_dims = 10
|
| 106 |
+
kernel_size = 3
|
| 107 |
+
stride = 1
|
| 108 |
+
dummy_input = torch.rand(B, C, H, W)
|
| 109 |
+
patch_merge_1 = PatchEmbed(
|
| 110 |
+
in_channels=C,
|
| 111 |
+
embed_dims=embed_dims,
|
| 112 |
+
kernel_size=kernel_size,
|
| 113 |
+
stride=stride,
|
| 114 |
+
padding=0,
|
| 115 |
+
dilation=1,
|
| 116 |
+
norm_cfg=None)
|
| 117 |
+
|
| 118 |
+
x1, shape = patch_merge_1(dummy_input)
|
| 119 |
+
# test out shape
|
| 120 |
+
assert x1.shape == (2, 2, 10)
|
| 121 |
+
# test outsize is correct
|
| 122 |
+
assert shape == (1, 2)
|
| 123 |
+
# test L = out_h * out_w
|
| 124 |
+
assert shape[0] * shape[1] == x1.shape[1]
|
| 125 |
+
|
| 126 |
+
B = 2
|
| 127 |
+
H = 10
|
| 128 |
+
W = 10
|
| 129 |
+
C = 3
|
| 130 |
+
embed_dims = 10
|
| 131 |
+
kernel_size = 5
|
| 132 |
+
stride = 2
|
| 133 |
+
dummy_input = torch.rand(B, C, H, W)
|
| 134 |
+
# test dilation
|
| 135 |
+
patch_merge_2 = PatchEmbed(
|
| 136 |
+
in_channels=C,
|
| 137 |
+
embed_dims=embed_dims,
|
| 138 |
+
kernel_size=kernel_size,
|
| 139 |
+
stride=stride,
|
| 140 |
+
padding=0,
|
| 141 |
+
dilation=2,
|
| 142 |
+
norm_cfg=None,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
x2, shape = patch_merge_2(dummy_input)
|
| 146 |
+
# test out shape
|
| 147 |
+
assert x2.shape == (2, 1, 10)
|
| 148 |
+
# test outsize is correct
|
| 149 |
+
assert shape == (1, 1)
|
| 150 |
+
# test L = out_h * out_w
|
| 151 |
+
assert shape[0] * shape[1] == x2.shape[1]
|
| 152 |
+
|
| 153 |
+
stride = 2
|
| 154 |
+
input_size = (10, 10)
|
| 155 |
+
|
| 156 |
+
dummy_input = torch.rand(B, C, H, W)
|
| 157 |
+
# test stride and norm
|
| 158 |
+
patch_merge_3 = PatchEmbed(
|
| 159 |
+
in_channels=C,
|
| 160 |
+
embed_dims=embed_dims,
|
| 161 |
+
kernel_size=kernel_size,
|
| 162 |
+
stride=stride,
|
| 163 |
+
padding=0,
|
| 164 |
+
dilation=2,
|
| 165 |
+
norm_cfg=dict(type='LN'),
|
| 166 |
+
input_size=input_size)
|
| 167 |
+
|
| 168 |
+
x3, shape = patch_merge_3(dummy_input)
|
| 169 |
+
# test out shape
|
| 170 |
+
assert x3.shape == (2, 1, 10)
|
| 171 |
+
# test outsize is correct
|
| 172 |
+
assert shape == (1, 1)
|
| 173 |
+
# test L = out_h * out_w
|
| 174 |
+
assert shape[0] * shape[1] == x3.shape[1]
|
| 175 |
+
|
| 176 |
+
# test the init_out_size with nn.Unfold
|
| 177 |
+
assert patch_merge_3.init_out_size[1] == (input_size[0] - 2 * 4 -
|
| 178 |
+
1) // 2 + 1
|
| 179 |
+
assert patch_merge_3.init_out_size[0] == (input_size[0] - 2 * 4 -
|
| 180 |
+
1) // 2 + 1
|
| 181 |
+
H = 11
|
| 182 |
+
W = 12
|
| 183 |
+
input_size = (H, W)
|
| 184 |
+
dummy_input = torch.rand(B, C, H, W)
|
| 185 |
+
# test stride and norm
|
| 186 |
+
patch_merge_3 = PatchEmbed(
|
| 187 |
+
in_channels=C,
|
| 188 |
+
embed_dims=embed_dims,
|
| 189 |
+
kernel_size=kernel_size,
|
| 190 |
+
stride=stride,
|
| 191 |
+
padding=0,
|
| 192 |
+
dilation=2,
|
| 193 |
+
norm_cfg=dict(type='LN'),
|
| 194 |
+
input_size=input_size)
|
| 195 |
+
|
| 196 |
+
_, shape = patch_merge_3(dummy_input)
|
| 197 |
+
# when input_size equal to real input
|
| 198 |
+
# the out_size should be equal to `init_out_size`
|
| 199 |
+
assert shape == patch_merge_3.init_out_size
|
| 200 |
+
|
| 201 |
+
input_size = (H, W)
|
| 202 |
+
dummy_input = torch.rand(B, C, H, W)
|
| 203 |
+
# test stride and norm
|
| 204 |
+
patch_merge_3 = PatchEmbed(
|
| 205 |
+
in_channels=C,
|
| 206 |
+
embed_dims=embed_dims,
|
| 207 |
+
kernel_size=kernel_size,
|
| 208 |
+
stride=stride,
|
| 209 |
+
padding=0,
|
| 210 |
+
dilation=2,
|
| 211 |
+
norm_cfg=dict(type='LN'),
|
| 212 |
+
input_size=input_size)
|
| 213 |
+
|
| 214 |
+
_, shape = patch_merge_3(dummy_input)
|
| 215 |
+
# when input_size equal to real input
|
| 216 |
+
# the out_size should be equal to `init_out_size`
|
| 217 |
+
assert shape == patch_merge_3.init_out_size
|
| 218 |
+
|
| 219 |
+
# test adap padding
|
| 220 |
+
for padding in ('same', 'corner'):
|
| 221 |
+
in_c = 2
|
| 222 |
+
embed_dims = 3
|
| 223 |
+
B = 2
|
| 224 |
+
|
| 225 |
+
# test stride is 1
|
| 226 |
+
input_size = (5, 5)
|
| 227 |
+
kernel_size = (5, 5)
|
| 228 |
+
stride = (1, 1)
|
| 229 |
+
dilation = 1
|
| 230 |
+
bias = False
|
| 231 |
+
|
| 232 |
+
x = torch.rand(B, in_c, *input_size)
|
| 233 |
+
patch_embed = PatchEmbed(
|
| 234 |
+
in_channels=in_c,
|
| 235 |
+
embed_dims=embed_dims,
|
| 236 |
+
kernel_size=kernel_size,
|
| 237 |
+
stride=stride,
|
| 238 |
+
padding=padding,
|
| 239 |
+
dilation=dilation,
|
| 240 |
+
bias=bias)
|
| 241 |
+
|
| 242 |
+
x_out, out_size = patch_embed(x)
|
| 243 |
+
assert x_out.size() == (B, 25, 3)
|
| 244 |
+
assert out_size == (5, 5)
|
| 245 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 246 |
+
|
| 247 |
+
# test kernel_size == stride
|
| 248 |
+
input_size = (5, 5)
|
| 249 |
+
kernel_size = (5, 5)
|
| 250 |
+
stride = (5, 5)
|
| 251 |
+
dilation = 1
|
| 252 |
+
bias = False
|
| 253 |
+
|
| 254 |
+
x = torch.rand(B, in_c, *input_size)
|
| 255 |
+
patch_embed = PatchEmbed(
|
| 256 |
+
in_channels=in_c,
|
| 257 |
+
embed_dims=embed_dims,
|
| 258 |
+
kernel_size=kernel_size,
|
| 259 |
+
stride=stride,
|
| 260 |
+
padding=padding,
|
| 261 |
+
dilation=dilation,
|
| 262 |
+
bias=bias)
|
| 263 |
+
|
| 264 |
+
x_out, out_size = patch_embed(x)
|
| 265 |
+
assert x_out.size() == (B, 1, 3)
|
| 266 |
+
assert out_size == (1, 1)
|
| 267 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 268 |
+
|
| 269 |
+
# test kernel_size == stride
|
| 270 |
+
input_size = (6, 5)
|
| 271 |
+
kernel_size = (5, 5)
|
| 272 |
+
stride = (5, 5)
|
| 273 |
+
dilation = 1
|
| 274 |
+
bias = False
|
| 275 |
+
|
| 276 |
+
x = torch.rand(B, in_c, *input_size)
|
| 277 |
+
patch_embed = PatchEmbed(
|
| 278 |
+
in_channels=in_c,
|
| 279 |
+
embed_dims=embed_dims,
|
| 280 |
+
kernel_size=kernel_size,
|
| 281 |
+
stride=stride,
|
| 282 |
+
padding=padding,
|
| 283 |
+
dilation=dilation,
|
| 284 |
+
bias=bias)
|
| 285 |
+
|
| 286 |
+
x_out, out_size = patch_embed(x)
|
| 287 |
+
assert x_out.size() == (B, 2, 3)
|
| 288 |
+
assert out_size == (2, 1)
|
| 289 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 290 |
+
|
| 291 |
+
# test different kernel_size with different stride
|
| 292 |
+
input_size = (6, 5)
|
| 293 |
+
kernel_size = (6, 2)
|
| 294 |
+
stride = (6, 2)
|
| 295 |
+
dilation = 1
|
| 296 |
+
bias = False
|
| 297 |
+
|
| 298 |
+
x = torch.rand(B, in_c, *input_size)
|
| 299 |
+
patch_embed = PatchEmbed(
|
| 300 |
+
in_channels=in_c,
|
| 301 |
+
embed_dims=embed_dims,
|
| 302 |
+
kernel_size=kernel_size,
|
| 303 |
+
stride=stride,
|
| 304 |
+
padding=padding,
|
| 305 |
+
dilation=dilation,
|
| 306 |
+
bias=bias)
|
| 307 |
+
|
| 308 |
+
x_out, out_size = patch_embed(x)
|
| 309 |
+
assert x_out.size() == (B, 3, 3)
|
| 310 |
+
assert out_size == (1, 3)
|
| 311 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def test_patch_merging():
|
| 315 |
+
|
| 316 |
+
# Test the model with int padding
|
| 317 |
+
in_c = 3
|
| 318 |
+
out_c = 4
|
| 319 |
+
kernel_size = 3
|
| 320 |
+
stride = 3
|
| 321 |
+
padding = 1
|
| 322 |
+
dilation = 1
|
| 323 |
+
bias = False
|
| 324 |
+
# test the case `pad_to_stride` is False
|
| 325 |
+
patch_merge = PatchMerging(
|
| 326 |
+
in_channels=in_c,
|
| 327 |
+
out_channels=out_c,
|
| 328 |
+
kernel_size=kernel_size,
|
| 329 |
+
stride=stride,
|
| 330 |
+
padding=padding,
|
| 331 |
+
dilation=dilation,
|
| 332 |
+
bias=bias)
|
| 333 |
+
B, L, C = 1, 100, 3
|
| 334 |
+
input_size = (10, 10)
|
| 335 |
+
x = torch.rand(B, L, C)
|
| 336 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 337 |
+
assert x_out.size() == (1, 16, 4)
|
| 338 |
+
assert out_size == (4, 4)
|
| 339 |
+
# assert out size is consistent with real output
|
| 340 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 341 |
+
in_c = 4
|
| 342 |
+
out_c = 5
|
| 343 |
+
kernel_size = 6
|
| 344 |
+
stride = 3
|
| 345 |
+
padding = 2
|
| 346 |
+
dilation = 2
|
| 347 |
+
bias = False
|
| 348 |
+
patch_merge = PatchMerging(
|
| 349 |
+
in_channels=in_c,
|
| 350 |
+
out_channels=out_c,
|
| 351 |
+
kernel_size=kernel_size,
|
| 352 |
+
stride=stride,
|
| 353 |
+
padding=padding,
|
| 354 |
+
dilation=dilation,
|
| 355 |
+
bias=bias)
|
| 356 |
+
B, L, C = 1, 100, 4
|
| 357 |
+
input_size = (10, 10)
|
| 358 |
+
x = torch.rand(B, L, C)
|
| 359 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 360 |
+
assert x_out.size() == (1, 4, 5)
|
| 361 |
+
assert out_size == (2, 2)
|
| 362 |
+
# assert out size is consistent with real output
|
| 363 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 364 |
+
|
| 365 |
+
# Test with adaptive padding
|
| 366 |
+
for padding in ('same', 'corner'):
|
| 367 |
+
in_c = 2
|
| 368 |
+
out_c = 3
|
| 369 |
+
B = 2
|
| 370 |
+
|
| 371 |
+
# test stride is 1
|
| 372 |
+
input_size = (5, 5)
|
| 373 |
+
kernel_size = (5, 5)
|
| 374 |
+
stride = (1, 1)
|
| 375 |
+
dilation = 1
|
| 376 |
+
bias = False
|
| 377 |
+
L = input_size[0] * input_size[1]
|
| 378 |
+
|
| 379 |
+
x = torch.rand(B, L, in_c)
|
| 380 |
+
patch_merge = PatchMerging(
|
| 381 |
+
in_channels=in_c,
|
| 382 |
+
out_channels=out_c,
|
| 383 |
+
kernel_size=kernel_size,
|
| 384 |
+
stride=stride,
|
| 385 |
+
padding=padding,
|
| 386 |
+
dilation=dilation,
|
| 387 |
+
bias=bias)
|
| 388 |
+
|
| 389 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 390 |
+
assert x_out.size() == (B, 25, 3)
|
| 391 |
+
assert out_size == (5, 5)
|
| 392 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 393 |
+
|
| 394 |
+
# test kernel_size == stride
|
| 395 |
+
input_size = (5, 5)
|
| 396 |
+
kernel_size = (5, 5)
|
| 397 |
+
stride = (5, 5)
|
| 398 |
+
dilation = 1
|
| 399 |
+
bias = False
|
| 400 |
+
L = input_size[0] * input_size[1]
|
| 401 |
+
|
| 402 |
+
x = torch.rand(B, L, in_c)
|
| 403 |
+
patch_merge = PatchMerging(
|
| 404 |
+
in_channels=in_c,
|
| 405 |
+
out_channels=out_c,
|
| 406 |
+
kernel_size=kernel_size,
|
| 407 |
+
stride=stride,
|
| 408 |
+
padding=padding,
|
| 409 |
+
dilation=dilation,
|
| 410 |
+
bias=bias)
|
| 411 |
+
|
| 412 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 413 |
+
assert x_out.size() == (B, 1, 3)
|
| 414 |
+
assert out_size == (1, 1)
|
| 415 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 416 |
+
|
| 417 |
+
# test kernel_size == stride
|
| 418 |
+
input_size = (6, 5)
|
| 419 |
+
kernel_size = (5, 5)
|
| 420 |
+
stride = (5, 5)
|
| 421 |
+
dilation = 1
|
| 422 |
+
bias = False
|
| 423 |
+
L = input_size[0] * input_size[1]
|
| 424 |
+
|
| 425 |
+
x = torch.rand(B, L, in_c)
|
| 426 |
+
patch_merge = PatchMerging(
|
| 427 |
+
in_channels=in_c,
|
| 428 |
+
out_channels=out_c,
|
| 429 |
+
kernel_size=kernel_size,
|
| 430 |
+
stride=stride,
|
| 431 |
+
padding=padding,
|
| 432 |
+
dilation=dilation,
|
| 433 |
+
bias=bias)
|
| 434 |
+
|
| 435 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 436 |
+
assert x_out.size() == (B, 2, 3)
|
| 437 |
+
assert out_size == (2, 1)
|
| 438 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
| 439 |
+
|
| 440 |
+
# test different kernel_size with different stride
|
| 441 |
+
input_size = (6, 5)
|
| 442 |
+
kernel_size = (6, 2)
|
| 443 |
+
stride = (6, 2)
|
| 444 |
+
dilation = 1
|
| 445 |
+
bias = False
|
| 446 |
+
L = input_size[0] * input_size[1]
|
| 447 |
+
|
| 448 |
+
x = torch.rand(B, L, in_c)
|
| 449 |
+
patch_merge = PatchMerging(
|
| 450 |
+
in_channels=in_c,
|
| 451 |
+
out_channels=out_c,
|
| 452 |
+
kernel_size=kernel_size,
|
| 453 |
+
stride=stride,
|
| 454 |
+
padding=padding,
|
| 455 |
+
dilation=dilation,
|
| 456 |
+
bias=bias)
|
| 457 |
+
|
| 458 |
+
x_out, out_size = patch_merge(x, input_size)
|
| 459 |
+
assert x_out.size() == (B, 3, 3)
|
| 460 |
+
assert out_size == (1, 3)
|
| 461 |
+
assert x_out.size(1) == out_size[0] * out_size[1]
|
EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_shape_convert.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.models.utils import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc,
|
| 5 |
+
nlc_to_nchw)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_nchw2nlc2nchw():
|
| 9 |
+
# Test nchw2nlc2nchw function
|
| 10 |
+
shape_nchw = (4, 2, 5, 5)
|
| 11 |
+
shape_nlc = (4, 25, 2)
|
| 12 |
+
|
| 13 |
+
def test_func(x):
|
| 14 |
+
assert x.shape == torch.Size(shape_nlc)
|
| 15 |
+
return x
|
| 16 |
+
|
| 17 |
+
x = torch.rand(*shape_nchw)
|
| 18 |
+
output = nchw2nlc2nchw(test_func, x)
|
| 19 |
+
assert output.shape == torch.Size(shape_nchw)
|
| 20 |
+
|
| 21 |
+
def test_func2(x, arg):
|
| 22 |
+
assert x.shape == torch.Size(shape_nlc)
|
| 23 |
+
assert arg == 100
|
| 24 |
+
return x
|
| 25 |
+
|
| 26 |
+
x = torch.rand(*shape_nchw)
|
| 27 |
+
output = nchw2nlc2nchw(test_func2, x, arg=100)
|
| 28 |
+
assert output.shape == torch.Size(shape_nchw)
|
| 29 |
+
|
| 30 |
+
def test_func3(x):
|
| 31 |
+
assert x.is_contiguous()
|
| 32 |
+
assert x.shape == torch.Size(shape_nlc)
|
| 33 |
+
return x
|
| 34 |
+
|
| 35 |
+
x = torch.rand(*shape_nchw)
|
| 36 |
+
output = nchw2nlc2nchw(test_func3, x, contiguous=True)
|
| 37 |
+
assert output.shape == torch.Size(shape_nchw)
|
| 38 |
+
assert output.is_contiguous()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_nlc2nchw2nlc():
|
| 42 |
+
# Test nlc2nchw2nlc function
|
| 43 |
+
shape_nchw = (4, 2, 5, 5)
|
| 44 |
+
shape_nlc = (4, 25, 2)
|
| 45 |
+
|
| 46 |
+
def test_func(x):
|
| 47 |
+
assert x.shape == torch.Size(shape_nchw)
|
| 48 |
+
return x
|
| 49 |
+
|
| 50 |
+
x = torch.rand(*shape_nlc)
|
| 51 |
+
output = nlc2nchw2nlc(test_func, x, shape_nchw[2:])
|
| 52 |
+
assert output.shape == torch.Size(shape_nlc)
|
| 53 |
+
|
| 54 |
+
def test_func2(x, arg):
|
| 55 |
+
assert x.shape == torch.Size(shape_nchw)
|
| 56 |
+
assert arg == 100
|
| 57 |
+
return x
|
| 58 |
+
|
| 59 |
+
x = torch.rand(*shape_nlc)
|
| 60 |
+
output = nlc2nchw2nlc(test_func2, x, shape_nchw[2:], arg=100)
|
| 61 |
+
assert output.shape == torch.Size(shape_nlc)
|
| 62 |
+
|
| 63 |
+
def test_func3(x):
|
| 64 |
+
assert x.is_contiguous()
|
| 65 |
+
assert x.shape == torch.Size(shape_nchw)
|
| 66 |
+
return x
|
| 67 |
+
|
| 68 |
+
x = torch.rand(*shape_nlc)
|
| 69 |
+
output = nlc2nchw2nlc(test_func3, x, shape_nchw[2:], contiguous=True)
|
| 70 |
+
assert output.shape == torch.Size(shape_nlc)
|
| 71 |
+
assert output.is_contiguous()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_nchw_to_nlc():
|
| 75 |
+
# Test nchw_to_nlc function
|
| 76 |
+
shape_nchw = (4, 2, 5, 5)
|
| 77 |
+
shape_nlc = (4, 25, 2)
|
| 78 |
+
x = torch.rand(*shape_nchw)
|
| 79 |
+
y = nchw_to_nlc(x)
|
| 80 |
+
assert y.shape == torch.Size(shape_nlc)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_nlc_to_nchw():
|
| 84 |
+
# Test nlc_to_nchw function
|
| 85 |
+
shape_nchw = (4, 2, 5, 5)
|
| 86 |
+
shape_nlc = (4, 25, 2)
|
| 87 |
+
x = torch.rand(*shape_nlc)
|
| 88 |
+
y = nlc_to_nchw(x, (5, 5))
|
| 89 |
+
assert y.shape == torch.Size(shape_nchw)
|
EgoHOS/raw/script/mmsegmentation/tests/test_sampler.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from mmseg.core import OHEMPixelSampler
|
| 6 |
+
from mmseg.models.decode_heads import FCNHead
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _context_for_ohem():
|
| 10 |
+
return FCNHead(in_channels=32, channels=16, num_classes=19)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _context_for_ohem_multiple_loss():
|
| 14 |
+
return FCNHead(
|
| 15 |
+
in_channels=32,
|
| 16 |
+
channels=16,
|
| 17 |
+
num_classes=19,
|
| 18 |
+
loss_decode=[
|
| 19 |
+
dict(type='CrossEntropyLoss', loss_name='loss_1'),
|
| 20 |
+
dict(type='CrossEntropyLoss', loss_name='loss_2')
|
| 21 |
+
])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_ohem_sampler():
|
| 25 |
+
|
| 26 |
+
with pytest.raises(AssertionError):
|
| 27 |
+
# seg_logit and seg_label must be of the same size
|
| 28 |
+
sampler = OHEMPixelSampler(context=_context_for_ohem())
|
| 29 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 30 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 89, 89))
|
| 31 |
+
sampler.sample(seg_logit, seg_label)
|
| 32 |
+
|
| 33 |
+
# test with thresh
|
| 34 |
+
sampler = OHEMPixelSampler(
|
| 35 |
+
context=_context_for_ohem(), thresh=0.7, min_kept=200)
|
| 36 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 37 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 45, 45))
|
| 38 |
+
seg_weight = sampler.sample(seg_logit, seg_label)
|
| 39 |
+
assert seg_weight.shape[0] == seg_logit.shape[0]
|
| 40 |
+
assert seg_weight.shape[1:] == seg_logit.shape[2:]
|
| 41 |
+
assert seg_weight.sum() > 200
|
| 42 |
+
|
| 43 |
+
# test w.o thresh
|
| 44 |
+
sampler = OHEMPixelSampler(context=_context_for_ohem(), min_kept=200)
|
| 45 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 46 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 45, 45))
|
| 47 |
+
seg_weight = sampler.sample(seg_logit, seg_label)
|
| 48 |
+
assert seg_weight.shape[0] == seg_logit.shape[0]
|
| 49 |
+
assert seg_weight.shape[1:] == seg_logit.shape[2:]
|
| 50 |
+
assert seg_weight.sum() == 200
|
| 51 |
+
|
| 52 |
+
# test multiple losses case
|
| 53 |
+
with pytest.raises(AssertionError):
|
| 54 |
+
# seg_logit and seg_label must be of the same size
|
| 55 |
+
sampler = OHEMPixelSampler(context=_context_for_ohem_multiple_loss())
|
| 56 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 57 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 89, 89))
|
| 58 |
+
sampler.sample(seg_logit, seg_label)
|
| 59 |
+
|
| 60 |
+
# test with thresh in multiple losses case
|
| 61 |
+
sampler = OHEMPixelSampler(
|
| 62 |
+
context=_context_for_ohem_multiple_loss(), thresh=0.7, min_kept=200)
|
| 63 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 64 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 45, 45))
|
| 65 |
+
seg_weight = sampler.sample(seg_logit, seg_label)
|
| 66 |
+
assert seg_weight.shape[0] == seg_logit.shape[0]
|
| 67 |
+
assert seg_weight.shape[1:] == seg_logit.shape[2:]
|
| 68 |
+
assert seg_weight.sum() > 200
|
| 69 |
+
|
| 70 |
+
# test w.o thresh in multiple losses case
|
| 71 |
+
sampler = OHEMPixelSampler(
|
| 72 |
+
context=_context_for_ohem_multiple_loss(), min_kept=200)
|
| 73 |
+
seg_logit = torch.randn(1, 19, 45, 45)
|
| 74 |
+
seg_label = torch.randint(0, 19, size=(1, 1, 45, 45))
|
| 75 |
+
seg_weight = sampler.sample(seg_logit, seg_label)
|
| 76 |
+
assert seg_weight.shape[0] == seg_logit.shape[0]
|
| 77 |
+
assert seg_weight.shape[1:] == seg_logit.shape[2:]
|
| 78 |
+
assert seg_weight.sum() == 200
|
EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_misc.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
from mmseg.utils import find_latest_checkpoint
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_find_latest_checkpoint():
|
| 9 |
+
with tempfile.TemporaryDirectory() as tempdir:
|
| 10 |
+
# no checkpoints in the path
|
| 11 |
+
path = tempdir
|
| 12 |
+
latest = find_latest_checkpoint(path)
|
| 13 |
+
assert latest is None
|
| 14 |
+
|
| 15 |
+
# The path doesn't exist
|
| 16 |
+
path = osp.join(tempdir, 'none')
|
| 17 |
+
latest = find_latest_checkpoint(path)
|
| 18 |
+
assert latest is None
|
| 19 |
+
|
| 20 |
+
# test when latest.pth exists
|
| 21 |
+
with tempfile.TemporaryDirectory() as tempdir:
|
| 22 |
+
with open(osp.join(tempdir, 'latest.pth'), 'w') as f:
|
| 23 |
+
f.write('latest')
|
| 24 |
+
path = tempdir
|
| 25 |
+
latest = find_latest_checkpoint(path)
|
| 26 |
+
assert latest == osp.join(tempdir, 'latest.pth')
|
| 27 |
+
|
| 28 |
+
with tempfile.TemporaryDirectory() as tempdir:
|
| 29 |
+
for iter in range(1600, 160001, 1600):
|
| 30 |
+
with open(osp.join(tempdir, f'iter_{iter}.pth'), 'w') as f:
|
| 31 |
+
f.write(f'iter_{iter}.pth')
|
| 32 |
+
latest = find_latest_checkpoint(tempdir)
|
| 33 |
+
assert latest == osp.join(tempdir, 'iter_160000.pth')
|
| 34 |
+
|
| 35 |
+
with tempfile.TemporaryDirectory() as tempdir:
|
| 36 |
+
for epoch in range(1, 21):
|
| 37 |
+
with open(osp.join(tempdir, f'epoch_{epoch}.pth'), 'w') as f:
|
| 38 |
+
f.write(f'epoch_{epoch}.pth')
|
| 39 |
+
latest = find_latest_checkpoint(tempdir)
|
| 40 |
+
assert latest == osp.join(tempdir, 'epoch_20.pth')
|
EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_set_env.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import multiprocessing as mp
|
| 3 |
+
import os
|
| 4 |
+
import platform
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import pytest
|
| 8 |
+
from mmcv import Config
|
| 9 |
+
|
| 10 |
+
from mmseg.utils import setup_multi_processes
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.parametrize('workers_per_gpu', (0, 2))
|
| 14 |
+
@pytest.mark.parametrize(('valid', 'env_cfg'), [(True,
|
| 15 |
+
dict(
|
| 16 |
+
mp_start_method='fork',
|
| 17 |
+
opencv_num_threads=0,
|
| 18 |
+
omp_num_threads=1,
|
| 19 |
+
mkl_num_threads=1)),
|
| 20 |
+
(False,
|
| 21 |
+
dict(
|
| 22 |
+
mp_start_method=1,
|
| 23 |
+
opencv_num_threads=0.1,
|
| 24 |
+
omp_num_threads='s',
|
| 25 |
+
mkl_num_threads='1'))])
|
| 26 |
+
def test_setup_multi_processes(workers_per_gpu, valid, env_cfg):
|
| 27 |
+
# temp save system setting
|
| 28 |
+
sys_start_mehod = mp.get_start_method(allow_none=True)
|
| 29 |
+
sys_cv_threads = cv2.getNumThreads()
|
| 30 |
+
# pop and temp save system env vars
|
| 31 |
+
sys_omp_threads = os.environ.pop('OMP_NUM_THREADS', default=None)
|
| 32 |
+
sys_mkl_threads = os.environ.pop('MKL_NUM_THREADS', default=None)
|
| 33 |
+
|
| 34 |
+
config = dict(data=dict(workers_per_gpu=workers_per_gpu))
|
| 35 |
+
config.update(env_cfg)
|
| 36 |
+
cfg = Config(config)
|
| 37 |
+
setup_multi_processes(cfg)
|
| 38 |
+
|
| 39 |
+
# test when cfg is valid and workers_per_gpu > 0
|
| 40 |
+
# setup_multi_processes will work
|
| 41 |
+
if valid and workers_per_gpu > 0:
|
| 42 |
+
# test config without setting env
|
| 43 |
+
|
| 44 |
+
assert os.getenv('OMP_NUM_THREADS') == str(env_cfg['omp_num_threads'])
|
| 45 |
+
assert os.getenv('MKL_NUM_THREADS') == str(env_cfg['mkl_num_threads'])
|
| 46 |
+
# when set to 0, the num threads will be 1
|
| 47 |
+
assert cv2.getNumThreads() == env_cfg[
|
| 48 |
+
'opencv_num_threads'] if env_cfg['opencv_num_threads'] > 0 else 1
|
| 49 |
+
if platform.system() != 'Windows':
|
| 50 |
+
assert mp.get_start_method() == env_cfg['mp_start_method']
|
| 51 |
+
|
| 52 |
+
# revert setting to avoid affecting other programs
|
| 53 |
+
if sys_start_mehod:
|
| 54 |
+
mp.set_start_method(sys_start_mehod, force=True)
|
| 55 |
+
cv2.setNumThreads(sys_cv_threads)
|
| 56 |
+
if sys_omp_threads:
|
| 57 |
+
os.environ['OMP_NUM_THREADS'] = sys_omp_threads
|
| 58 |
+
else:
|
| 59 |
+
os.environ.pop('OMP_NUM_THREADS')
|
| 60 |
+
if sys_mkl_threads:
|
| 61 |
+
os.environ['MKL_NUM_THREADS'] = sys_mkl_threads
|
| 62 |
+
else:
|
| 63 |
+
os.environ.pop('MKL_NUM_THREADS')
|
| 64 |
+
|
| 65 |
+
elif valid and workers_per_gpu == 0:
|
| 66 |
+
|
| 67 |
+
if platform.system() != 'Windows':
|
| 68 |
+
assert mp.get_start_method() == env_cfg['mp_start_method']
|
| 69 |
+
assert cv2.getNumThreads() == env_cfg[
|
| 70 |
+
'opencv_num_threads'] if env_cfg['opencv_num_threads'] > 0 else 1
|
| 71 |
+
assert 'OMP_NUM_THREADS' not in os.environ
|
| 72 |
+
assert 'MKL_NUM_THREADS' not in os.environ
|
| 73 |
+
if sys_start_mehod:
|
| 74 |
+
mp.set_start_method(sys_start_mehod, force=True)
|
| 75 |
+
cv2.setNumThreads(sys_cv_threads)
|
| 76 |
+
if sys_omp_threads:
|
| 77 |
+
os.environ['OMP_NUM_THREADS'] = sys_omp_threads
|
| 78 |
+
if sys_mkl_threads:
|
| 79 |
+
os.environ['MKL_NUM_THREADS'] = sys_mkl_threads
|
| 80 |
+
|
| 81 |
+
else:
|
| 82 |
+
assert mp.get_start_method() == sys_start_mehod
|
| 83 |
+
assert cv2.getNumThreads() == sys_cv_threads
|
| 84 |
+
assert 'OMP_NUM_THREADS' not in os.environ
|
| 85 |
+
assert 'MKL_NUM_THREADS' not in os.environ
|
EgoHOS/raw/script/mmsegmentation/tools/analyze_logs.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
"""Modified from https://github.com/open-
|
| 3 |
+
mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py."""
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
import seaborn as sns
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def plot_curve(log_dicts, args):
|
| 13 |
+
if args.backend is not None:
|
| 14 |
+
plt.switch_backend(args.backend)
|
| 15 |
+
sns.set_style(args.style)
|
| 16 |
+
# if legend is None, use {filename}_{key} as legend
|
| 17 |
+
legend = args.legend
|
| 18 |
+
if legend is None:
|
| 19 |
+
legend = []
|
| 20 |
+
for json_log in args.json_logs:
|
| 21 |
+
for metric in args.keys:
|
| 22 |
+
legend.append(f'{json_log}_{metric}')
|
| 23 |
+
assert len(legend) == (len(args.json_logs) * len(args.keys))
|
| 24 |
+
metrics = args.keys
|
| 25 |
+
|
| 26 |
+
num_metrics = len(metrics)
|
| 27 |
+
for i, log_dict in enumerate(log_dicts):
|
| 28 |
+
epochs = list(log_dict.keys())
|
| 29 |
+
for j, metric in enumerate(metrics):
|
| 30 |
+
print(f'plot curve of {args.json_logs[i]}, metric is {metric}')
|
| 31 |
+
plot_epochs = []
|
| 32 |
+
plot_iters = []
|
| 33 |
+
plot_values = []
|
| 34 |
+
# In some log files exist lines of validation,
|
| 35 |
+
# `mode` list is used to only collect iter number
|
| 36 |
+
# of training line.
|
| 37 |
+
for epoch in epochs:
|
| 38 |
+
epoch_logs = log_dict[epoch]
|
| 39 |
+
if metric not in epoch_logs.keys():
|
| 40 |
+
continue
|
| 41 |
+
if metric in ['mIoU', 'mAcc', 'aAcc']:
|
| 42 |
+
plot_epochs.append(epoch)
|
| 43 |
+
plot_values.append(epoch_logs[metric][0])
|
| 44 |
+
else:
|
| 45 |
+
for idx in range(len(epoch_logs[metric])):
|
| 46 |
+
if epoch_logs['mode'][idx] == 'train':
|
| 47 |
+
plot_iters.append(epoch_logs['iter'][idx])
|
| 48 |
+
plot_values.append(epoch_logs[metric][idx])
|
| 49 |
+
ax = plt.gca()
|
| 50 |
+
label = legend[i * num_metrics + j]
|
| 51 |
+
if metric in ['mIoU', 'mAcc', 'aAcc']:
|
| 52 |
+
ax.set_xticks(plot_epochs)
|
| 53 |
+
plt.xlabel('epoch')
|
| 54 |
+
plt.plot(plot_epochs, plot_values, label=label, marker='o')
|
| 55 |
+
else:
|
| 56 |
+
plt.xlabel('iter')
|
| 57 |
+
plt.plot(plot_iters, plot_values, label=label, linewidth=0.5)
|
| 58 |
+
plt.legend()
|
| 59 |
+
if args.title is not None:
|
| 60 |
+
plt.title(args.title)
|
| 61 |
+
if args.out is None:
|
| 62 |
+
plt.show()
|
| 63 |
+
else:
|
| 64 |
+
print(f'save curve to: {args.out}')
|
| 65 |
+
plt.savefig(args.out)
|
| 66 |
+
plt.cla()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def parse_args():
|
| 70 |
+
parser = argparse.ArgumentParser(description='Analyze Json Log')
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
'json_logs',
|
| 73 |
+
type=str,
|
| 74 |
+
nargs='+',
|
| 75 |
+
help='path of train log in json format')
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
'--keys',
|
| 78 |
+
type=str,
|
| 79 |
+
nargs='+',
|
| 80 |
+
default=['mIoU'],
|
| 81 |
+
help='the metric that you want to plot')
|
| 82 |
+
parser.add_argument('--title', type=str, help='title of figure')
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
'--legend',
|
| 85 |
+
type=str,
|
| 86 |
+
nargs='+',
|
| 87 |
+
default=None,
|
| 88 |
+
help='legend of each plot')
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
'--backend', type=str, default=None, help='backend of plt')
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
'--style', type=str, default='dark', help='style of plt')
|
| 93 |
+
parser.add_argument('--out', type=str, default=None)
|
| 94 |
+
args = parser.parse_args()
|
| 95 |
+
return args
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def load_json_logs(json_logs):
|
| 99 |
+
# load and convert json_logs to log_dict, key is epoch, value is a sub dict
|
| 100 |
+
# keys of sub dict is different metrics
|
| 101 |
+
# value of sub dict is a list of corresponding values of all iterations
|
| 102 |
+
log_dicts = [dict() for _ in json_logs]
|
| 103 |
+
for json_log, log_dict in zip(json_logs, log_dicts):
|
| 104 |
+
with open(json_log, 'r') as log_file:
|
| 105 |
+
for line in log_file:
|
| 106 |
+
log = json.loads(line.strip())
|
| 107 |
+
# skip lines without `epoch` field
|
| 108 |
+
if 'epoch' not in log:
|
| 109 |
+
continue
|
| 110 |
+
epoch = log.pop('epoch')
|
| 111 |
+
if epoch not in log_dict:
|
| 112 |
+
log_dict[epoch] = defaultdict(list)
|
| 113 |
+
for k, v in log.items():
|
| 114 |
+
log_dict[epoch][k].append(v)
|
| 115 |
+
return log_dicts
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main():
|
| 119 |
+
args = parse_args()
|
| 120 |
+
json_logs = args.json_logs
|
| 121 |
+
for json_log in json_logs:
|
| 122 |
+
assert json_log.endswith('.json')
|
| 123 |
+
log_dicts = load_json_logs(json_logs)
|
| 124 |
+
plot_curve(log_dicts, args)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == '__main__':
|
| 128 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/benchmark.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os.path as osp
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import mmcv
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from mmcv import Config
|
| 10 |
+
from mmcv.parallel import MMDataParallel
|
| 11 |
+
from mmcv.runner import load_checkpoint, wrap_fp16_model
|
| 12 |
+
|
| 13 |
+
from mmseg.datasets import build_dataloader, build_dataset
|
| 14 |
+
from mmseg.models import build_segmentor
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def parse_args():
|
| 18 |
+
parser = argparse.ArgumentParser(description='MMSeg benchmark a model')
|
| 19 |
+
parser.add_argument('config', help='test config file path')
|
| 20 |
+
parser.add_argument('checkpoint', help='checkpoint file')
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
'--log-interval', type=int, default=50, help='interval of logging')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--work-dir',
|
| 25 |
+
help=('if specified, the results will be dumped '
|
| 26 |
+
'into the directory as json'))
|
| 27 |
+
parser.add_argument('--repeat-times', type=int, default=1)
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
return args
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def main():
|
| 33 |
+
args = parse_args()
|
| 34 |
+
|
| 35 |
+
cfg = Config.fromfile(args.config)
|
| 36 |
+
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
|
| 37 |
+
if args.work_dir is not None:
|
| 38 |
+
mmcv.mkdir_or_exist(osp.abspath(args.work_dir))
|
| 39 |
+
json_file = osp.join(args.work_dir, f'fps_{timestamp}.json')
|
| 40 |
+
else:
|
| 41 |
+
# use config filename as default work_dir if cfg.work_dir is None
|
| 42 |
+
work_dir = osp.join('./work_dirs',
|
| 43 |
+
osp.splitext(osp.basename(args.config))[0])
|
| 44 |
+
mmcv.mkdir_or_exist(osp.abspath(work_dir))
|
| 45 |
+
json_file = osp.join(work_dir, f'fps_{timestamp}.json')
|
| 46 |
+
|
| 47 |
+
repeat_times = args.repeat_times
|
| 48 |
+
# set cudnn_benchmark
|
| 49 |
+
torch.backends.cudnn.benchmark = False
|
| 50 |
+
cfg.model.pretrained = None
|
| 51 |
+
cfg.data.test.test_mode = True
|
| 52 |
+
|
| 53 |
+
benchmark_dict = dict(config=args.config, unit='img / s')
|
| 54 |
+
overall_fps_list = []
|
| 55 |
+
for time_index in range(repeat_times):
|
| 56 |
+
print(f'Run {time_index + 1}:')
|
| 57 |
+
# build the dataloader
|
| 58 |
+
# TODO: support multiple images per gpu (only minor changes are needed)
|
| 59 |
+
dataset = build_dataset(cfg.data.test)
|
| 60 |
+
data_loader = build_dataloader(
|
| 61 |
+
dataset,
|
| 62 |
+
samples_per_gpu=1,
|
| 63 |
+
workers_per_gpu=cfg.data.workers_per_gpu,
|
| 64 |
+
dist=False,
|
| 65 |
+
shuffle=False)
|
| 66 |
+
|
| 67 |
+
# build the model and load checkpoint
|
| 68 |
+
cfg.model.train_cfg = None
|
| 69 |
+
model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg'))
|
| 70 |
+
fp16_cfg = cfg.get('fp16', None)
|
| 71 |
+
if fp16_cfg is not None:
|
| 72 |
+
wrap_fp16_model(model)
|
| 73 |
+
if 'checkpoint' in args and osp.exists(args.checkpoint):
|
| 74 |
+
load_checkpoint(model, args.checkpoint, map_location='cpu')
|
| 75 |
+
|
| 76 |
+
model = MMDataParallel(model, device_ids=[0])
|
| 77 |
+
|
| 78 |
+
model.eval()
|
| 79 |
+
|
| 80 |
+
# the first several iterations may be very slow so skip them
|
| 81 |
+
num_warmup = 5
|
| 82 |
+
pure_inf_time = 0
|
| 83 |
+
total_iters = 200
|
| 84 |
+
|
| 85 |
+
# benchmark with 200 image and take the average
|
| 86 |
+
for i, data in enumerate(data_loader):
|
| 87 |
+
|
| 88 |
+
torch.cuda.synchronize()
|
| 89 |
+
start_time = time.perf_counter()
|
| 90 |
+
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
model(return_loss=False, rescale=True, **data)
|
| 93 |
+
|
| 94 |
+
torch.cuda.synchronize()
|
| 95 |
+
elapsed = time.perf_counter() - start_time
|
| 96 |
+
|
| 97 |
+
if i >= num_warmup:
|
| 98 |
+
pure_inf_time += elapsed
|
| 99 |
+
if (i + 1) % args.log_interval == 0:
|
| 100 |
+
fps = (i + 1 - num_warmup) / pure_inf_time
|
| 101 |
+
print(f'Done image [{i + 1:<3}/ {total_iters}], '
|
| 102 |
+
f'fps: {fps:.2f} img / s')
|
| 103 |
+
|
| 104 |
+
if (i + 1) == total_iters:
|
| 105 |
+
fps = (i + 1 - num_warmup) / pure_inf_time
|
| 106 |
+
print(f'Overall fps: {fps:.2f} img / s\n')
|
| 107 |
+
benchmark_dict[f'overall_fps_{time_index + 1}'] = round(fps, 2)
|
| 108 |
+
overall_fps_list.append(fps)
|
| 109 |
+
break
|
| 110 |
+
benchmark_dict['average_fps'] = round(np.mean(overall_fps_list), 2)
|
| 111 |
+
benchmark_dict['fps_variance'] = round(np.var(overall_fps_list), 4)
|
| 112 |
+
print(f'Average fps of {repeat_times} evaluations: '
|
| 113 |
+
f'{benchmark_dict["average_fps"]}')
|
| 114 |
+
print(f'The variance of {repeat_times} evaluations: '
|
| 115 |
+
f'{benchmark_dict["fps_variance"]}')
|
| 116 |
+
mmcv.dump(benchmark_dict, json_file, indent=4)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == '__main__':
|
| 120 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/browse_dataset.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import warnings
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import mmcv
|
| 8 |
+
import numpy as np
|
| 9 |
+
from mmcv import Config, DictAction
|
| 10 |
+
|
| 11 |
+
from mmseg.datasets.builder import build_dataset
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(description='Browse a dataset')
|
| 16 |
+
parser.add_argument('config', help='train config file path')
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
'--show-origin',
|
| 19 |
+
default=False,
|
| 20 |
+
action='store_true',
|
| 21 |
+
help='if True, omit all augmentation in pipeline,'
|
| 22 |
+
' show origin image and seg map')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--skip-type',
|
| 25 |
+
type=str,
|
| 26 |
+
nargs='+',
|
| 27 |
+
default=['DefaultFormatBundle', 'Normalize', 'Collect'],
|
| 28 |
+
help='skip some useless pipeline,if `show-origin` is true, '
|
| 29 |
+
'all pipeline except `Load` will be skipped')
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
'--output-dir',
|
| 32 |
+
default='./output',
|
| 33 |
+
type=str,
|
| 34 |
+
help='If there is no display interface, you can save it')
|
| 35 |
+
parser.add_argument('--show', default=False, action='store_true')
|
| 36 |
+
parser.add_argument(
|
| 37 |
+
'--show-interval',
|
| 38 |
+
type=int,
|
| 39 |
+
default=999,
|
| 40 |
+
help='the interval of show (ms)')
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
'--opacity',
|
| 43 |
+
type=float,
|
| 44 |
+
default=0.5,
|
| 45 |
+
help='the opacity of semantic map')
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
'--cfg-options',
|
| 48 |
+
nargs='+',
|
| 49 |
+
action=DictAction,
|
| 50 |
+
help='override some settings in the used config, the key-value pair '
|
| 51 |
+
'in xxx=yyy format will be merged into config file. If the value to '
|
| 52 |
+
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
|
| 53 |
+
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
|
| 54 |
+
'Note that the quotation marks are necessary and that no white space '
|
| 55 |
+
'is allowed.')
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
return args
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def imshow_semantic(img,
|
| 61 |
+
seg,
|
| 62 |
+
class_names,
|
| 63 |
+
palette=None,
|
| 64 |
+
win_name='',
|
| 65 |
+
show=False,
|
| 66 |
+
wait_time=0,
|
| 67 |
+
out_file=None,
|
| 68 |
+
opacity=0.5):
|
| 69 |
+
"""Draw `result` over `img`.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
img (str or Tensor): The image to be displayed.
|
| 73 |
+
seg (Tensor): The semantic segmentation results to draw over
|
| 74 |
+
`img`.
|
| 75 |
+
class_names (list[str]): Names of each classes.
|
| 76 |
+
palette (list[list[int]]] | np.ndarray | None): The palette of
|
| 77 |
+
segmentation map. If None is given, random palette will be
|
| 78 |
+
generated. Default: None
|
| 79 |
+
win_name (str): The window name.
|
| 80 |
+
wait_time (int): Value of waitKey param.
|
| 81 |
+
Default: 0.
|
| 82 |
+
show (bool): Whether to show the image.
|
| 83 |
+
Default: False.
|
| 84 |
+
out_file (str or None): The filename to write the image.
|
| 85 |
+
Default: None.
|
| 86 |
+
opacity(float): Opacity of painted segmentation map.
|
| 87 |
+
Default 0.5.
|
| 88 |
+
Must be in (0, 1] range.
|
| 89 |
+
Returns:
|
| 90 |
+
img (Tensor): Only if not `show` or `out_file`
|
| 91 |
+
"""
|
| 92 |
+
img = mmcv.imread(img)
|
| 93 |
+
img = img.copy()
|
| 94 |
+
if palette is None:
|
| 95 |
+
palette = np.random.randint(0, 255, size=(len(class_names), 3))
|
| 96 |
+
palette = np.array(palette)
|
| 97 |
+
assert palette.shape[0] == len(class_names)
|
| 98 |
+
assert palette.shape[1] == 3
|
| 99 |
+
assert len(palette.shape) == 2
|
| 100 |
+
assert 0 < opacity <= 1.0
|
| 101 |
+
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
|
| 102 |
+
for label, color in enumerate(palette):
|
| 103 |
+
color_seg[seg == label, :] = color
|
| 104 |
+
# convert to BGR
|
| 105 |
+
color_seg = color_seg[..., ::-1]
|
| 106 |
+
|
| 107 |
+
img = img * (1 - opacity) + color_seg * opacity
|
| 108 |
+
img = img.astype(np.uint8)
|
| 109 |
+
# if out_file specified, do not show image in window
|
| 110 |
+
if out_file is not None:
|
| 111 |
+
show = False
|
| 112 |
+
|
| 113 |
+
if show:
|
| 114 |
+
mmcv.imshow(img, win_name, wait_time)
|
| 115 |
+
if out_file is not None:
|
| 116 |
+
mmcv.imwrite(img, out_file)
|
| 117 |
+
|
| 118 |
+
if not (show or out_file):
|
| 119 |
+
warnings.warn('show==False and out_file is not specified, only '
|
| 120 |
+
'result image will be returned')
|
| 121 |
+
return img
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _retrieve_data_cfg(_data_cfg, skip_type, show_origin):
|
| 125 |
+
if show_origin is True:
|
| 126 |
+
# only keep pipeline of Loading data and ann
|
| 127 |
+
_data_cfg['pipeline'] = [
|
| 128 |
+
x for x in _data_cfg.pipeline if 'Load' in x['type']
|
| 129 |
+
]
|
| 130 |
+
else:
|
| 131 |
+
_data_cfg['pipeline'] = [
|
| 132 |
+
x for x in _data_cfg.pipeline if x['type'] not in skip_type
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def retrieve_data_cfg(config_path, skip_type, cfg_options, show_origin=False):
|
| 137 |
+
cfg = Config.fromfile(config_path)
|
| 138 |
+
if cfg_options is not None:
|
| 139 |
+
cfg.merge_from_dict(cfg_options)
|
| 140 |
+
train_data_cfg = cfg.data.train
|
| 141 |
+
if isinstance(train_data_cfg, list):
|
| 142 |
+
for _data_cfg in train_data_cfg:
|
| 143 |
+
while 'dataset' in _data_cfg and _data_cfg[
|
| 144 |
+
'type'] != 'MultiImageMixDataset':
|
| 145 |
+
_data_cfg = _data_cfg['dataset']
|
| 146 |
+
if 'pipeline' in _data_cfg:
|
| 147 |
+
_retrieve_data_cfg(_data_cfg, skip_type, show_origin)
|
| 148 |
+
else:
|
| 149 |
+
raise ValueError
|
| 150 |
+
else:
|
| 151 |
+
while 'dataset' in train_data_cfg and train_data_cfg[
|
| 152 |
+
'type'] != 'MultiImageMixDataset':
|
| 153 |
+
train_data_cfg = train_data_cfg['dataset']
|
| 154 |
+
_retrieve_data_cfg(train_data_cfg, skip_type, show_origin)
|
| 155 |
+
return cfg
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main():
|
| 159 |
+
args = parse_args()
|
| 160 |
+
cfg = retrieve_data_cfg(args.config, args.skip_type, args.cfg_options,
|
| 161 |
+
args.show_origin)
|
| 162 |
+
dataset = build_dataset(cfg.data.train)
|
| 163 |
+
progress_bar = mmcv.ProgressBar(len(dataset))
|
| 164 |
+
for item in dataset:
|
| 165 |
+
filename = os.path.join(args.output_dir,
|
| 166 |
+
Path(item['filename']).name
|
| 167 |
+
) if args.output_dir is not None else None
|
| 168 |
+
imshow_semantic(
|
| 169 |
+
item['img'],
|
| 170 |
+
item['gt_semantic_seg'],
|
| 171 |
+
dataset.CLASSES,
|
| 172 |
+
dataset.PALETTE,
|
| 173 |
+
show=args.show,
|
| 174 |
+
wait_time=args.show_interval,
|
| 175 |
+
out_file=filename,
|
| 176 |
+
opacity=args.opacity,
|
| 177 |
+
)
|
| 178 |
+
progress_bar.update()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
if __name__ == '__main__':
|
| 182 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/confusion_matrix.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import mmcv
|
| 7 |
+
import numpy as np
|
| 8 |
+
from matplotlib.ticker import MultipleLocator
|
| 9 |
+
from mmcv import Config, DictAction
|
| 10 |
+
|
| 11 |
+
from mmseg.datasets import build_dataset
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description='Generate confusion matrix from segmentation results')
|
| 17 |
+
parser.add_argument('config', help='test config file path')
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
'prediction_path', help='prediction path where test .pkl result')
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
'save_dir', help='directory where confusion matrix will be saved')
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
'--show', action='store_true', help='show confusion matrix')
|
| 24 |
+
parser.add_argument(
|
| 25 |
+
'--color-theme',
|
| 26 |
+
default='winter',
|
| 27 |
+
help='theme of the matrix color map')
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
'--title',
|
| 30 |
+
default='Normalized Confusion Matrix',
|
| 31 |
+
help='title of the matrix color map')
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
'--cfg-options',
|
| 34 |
+
nargs='+',
|
| 35 |
+
action=DictAction,
|
| 36 |
+
help='override some settings in the used config, the key-value pair '
|
| 37 |
+
'in xxx=yyy format will be merged into config file. If the value to '
|
| 38 |
+
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
|
| 39 |
+
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
|
| 40 |
+
'Note that the quotation marks are necessary and that no white space '
|
| 41 |
+
'is allowed.')
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
return args
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def calculate_confusion_matrix(dataset, results):
|
| 47 |
+
"""Calculate the confusion matrix.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
dataset (Dataset): Test or val dataset.
|
| 51 |
+
results (list[ndarray]): A list of segmentation results in each image.
|
| 52 |
+
"""
|
| 53 |
+
n = len(dataset.CLASSES)
|
| 54 |
+
confusion_matrix = np.zeros(shape=[n, n])
|
| 55 |
+
assert len(dataset) == len(results)
|
| 56 |
+
prog_bar = mmcv.ProgressBar(len(results))
|
| 57 |
+
for idx, per_img_res in enumerate(results):
|
| 58 |
+
res_segm = per_img_res
|
| 59 |
+
gt_segm = dataset.get_gt_seg_map_by_idx(idx)
|
| 60 |
+
inds = n * gt_segm + res_segm
|
| 61 |
+
inds = inds.flatten()
|
| 62 |
+
mat = np.bincount(inds, minlength=n**2).reshape(n, n)
|
| 63 |
+
confusion_matrix += mat
|
| 64 |
+
prog_bar.update()
|
| 65 |
+
return confusion_matrix
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def plot_confusion_matrix(confusion_matrix,
|
| 69 |
+
labels,
|
| 70 |
+
save_dir=None,
|
| 71 |
+
show=True,
|
| 72 |
+
title='Normalized Confusion Matrix',
|
| 73 |
+
color_theme='winter'):
|
| 74 |
+
"""Draw confusion matrix with matplotlib.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
confusion_matrix (ndarray): The confusion matrix.
|
| 78 |
+
labels (list[str]): List of class names.
|
| 79 |
+
save_dir (str|optional): If set, save the confusion matrix plot to the
|
| 80 |
+
given path. Default: None.
|
| 81 |
+
show (bool): Whether to show the plot. Default: True.
|
| 82 |
+
title (str): Title of the plot. Default: `Normalized Confusion Matrix`.
|
| 83 |
+
color_theme (str): Theme of the matrix color map. Default: `winter`.
|
| 84 |
+
"""
|
| 85 |
+
# normalize the confusion matrix
|
| 86 |
+
per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis]
|
| 87 |
+
confusion_matrix = \
|
| 88 |
+
confusion_matrix.astype(np.float32) / per_label_sums * 100
|
| 89 |
+
|
| 90 |
+
num_classes = len(labels)
|
| 91 |
+
fig, ax = plt.subplots(
|
| 92 |
+
figsize=(2 * num_classes, 2 * num_classes * 0.8), dpi=180)
|
| 93 |
+
cmap = plt.get_cmap(color_theme)
|
| 94 |
+
im = ax.imshow(confusion_matrix, cmap=cmap)
|
| 95 |
+
plt.colorbar(mappable=im, ax=ax)
|
| 96 |
+
|
| 97 |
+
title_font = {'weight': 'bold', 'size': 12}
|
| 98 |
+
ax.set_title(title, fontdict=title_font)
|
| 99 |
+
label_font = {'size': 10}
|
| 100 |
+
plt.ylabel('Ground Truth Label', fontdict=label_font)
|
| 101 |
+
plt.xlabel('Prediction Label', fontdict=label_font)
|
| 102 |
+
|
| 103 |
+
# draw locator
|
| 104 |
+
xmajor_locator = MultipleLocator(1)
|
| 105 |
+
xminor_locator = MultipleLocator(0.5)
|
| 106 |
+
ax.xaxis.set_major_locator(xmajor_locator)
|
| 107 |
+
ax.xaxis.set_minor_locator(xminor_locator)
|
| 108 |
+
ymajor_locator = MultipleLocator(1)
|
| 109 |
+
yminor_locator = MultipleLocator(0.5)
|
| 110 |
+
ax.yaxis.set_major_locator(ymajor_locator)
|
| 111 |
+
ax.yaxis.set_minor_locator(yminor_locator)
|
| 112 |
+
|
| 113 |
+
# draw grid
|
| 114 |
+
ax.grid(True, which='minor', linestyle='-')
|
| 115 |
+
|
| 116 |
+
# draw label
|
| 117 |
+
ax.set_xticks(np.arange(num_classes))
|
| 118 |
+
ax.set_yticks(np.arange(num_classes))
|
| 119 |
+
ax.set_xticklabels(labels)
|
| 120 |
+
ax.set_yticklabels(labels)
|
| 121 |
+
|
| 122 |
+
ax.tick_params(
|
| 123 |
+
axis='x', bottom=False, top=True, labelbottom=False, labeltop=True)
|
| 124 |
+
plt.setp(
|
| 125 |
+
ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor')
|
| 126 |
+
|
| 127 |
+
# draw confusion matrix value
|
| 128 |
+
for i in range(num_classes):
|
| 129 |
+
for j in range(num_classes):
|
| 130 |
+
ax.text(
|
| 131 |
+
j,
|
| 132 |
+
i,
|
| 133 |
+
'{}%'.format(
|
| 134 |
+
round(confusion_matrix[i, j], 2
|
| 135 |
+
) if not np.isnan(confusion_matrix[i, j]) else -1),
|
| 136 |
+
ha='center',
|
| 137 |
+
va='center',
|
| 138 |
+
color='w',
|
| 139 |
+
size=7)
|
| 140 |
+
|
| 141 |
+
ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1
|
| 142 |
+
|
| 143 |
+
fig.tight_layout()
|
| 144 |
+
if save_dir is not None:
|
| 145 |
+
plt.savefig(
|
| 146 |
+
os.path.join(save_dir, 'confusion_matrix.png'), format='png')
|
| 147 |
+
if show:
|
| 148 |
+
plt.show()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
args = parse_args()
|
| 153 |
+
|
| 154 |
+
cfg = Config.fromfile(args.config)
|
| 155 |
+
if args.cfg_options is not None:
|
| 156 |
+
cfg.merge_from_dict(args.cfg_options)
|
| 157 |
+
|
| 158 |
+
results = mmcv.load(args.prediction_path)
|
| 159 |
+
|
| 160 |
+
assert isinstance(results, list)
|
| 161 |
+
if isinstance(results[0], np.ndarray):
|
| 162 |
+
pass
|
| 163 |
+
else:
|
| 164 |
+
raise TypeError('invalid type of prediction results')
|
| 165 |
+
|
| 166 |
+
if isinstance(cfg.data.test, dict):
|
| 167 |
+
cfg.data.test.test_mode = True
|
| 168 |
+
elif isinstance(cfg.data.test, list):
|
| 169 |
+
for ds_cfg in cfg.data.test:
|
| 170 |
+
ds_cfg.test_mode = True
|
| 171 |
+
|
| 172 |
+
dataset = build_dataset(cfg.data.test)
|
| 173 |
+
confusion_matrix = calculate_confusion_matrix(dataset, results)
|
| 174 |
+
plot_confusion_matrix(
|
| 175 |
+
confusion_matrix,
|
| 176 |
+
dataset.CLASSES,
|
| 177 |
+
save_dir=args.save_dir,
|
| 178 |
+
show=args.show,
|
| 179 |
+
title=args.title,
|
| 180 |
+
color_theme=args.color_theme)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == '__main__':
|
| 184 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/chase_db1.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import tempfile
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
import mmcv
|
| 9 |
+
|
| 10 |
+
CHASE_DB1_LEN = 28 * 3
|
| 11 |
+
TRAINING_LEN = 60
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description='Convert CHASE_DB1 dataset to mmsegmentation format')
|
| 17 |
+
parser.add_argument('dataset_path', help='path of CHASEDB1.zip')
|
| 18 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 19 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
return args
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main():
|
| 25 |
+
args = parse_args()
|
| 26 |
+
dataset_path = args.dataset_path
|
| 27 |
+
if args.out_dir is None:
|
| 28 |
+
out_dir = osp.join('data', 'CHASE_DB1')
|
| 29 |
+
else:
|
| 30 |
+
out_dir = args.out_dir
|
| 31 |
+
|
| 32 |
+
print('Making directories...')
|
| 33 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 34 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images'))
|
| 35 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training'))
|
| 36 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation'))
|
| 37 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations'))
|
| 38 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training'))
|
| 39 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation'))
|
| 40 |
+
|
| 41 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 42 |
+
print('Extracting CHASEDB1.zip...')
|
| 43 |
+
zip_file = zipfile.ZipFile(dataset_path)
|
| 44 |
+
zip_file.extractall(tmp_dir)
|
| 45 |
+
|
| 46 |
+
print('Generating training dataset...')
|
| 47 |
+
|
| 48 |
+
assert len(os.listdir(tmp_dir)) == CHASE_DB1_LEN, \
|
| 49 |
+
'len(os.listdir(tmp_dir)) != {}'.format(CHASE_DB1_LEN)
|
| 50 |
+
|
| 51 |
+
for img_name in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]:
|
| 52 |
+
img = mmcv.imread(osp.join(tmp_dir, img_name))
|
| 53 |
+
if osp.splitext(img_name)[1] == '.jpg':
|
| 54 |
+
mmcv.imwrite(
|
| 55 |
+
img,
|
| 56 |
+
osp.join(out_dir, 'images', 'training',
|
| 57 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 58 |
+
else:
|
| 59 |
+
# The annotation img should be divided by 128, because some of
|
| 60 |
+
# the annotation imgs are not standard. We should set a
|
| 61 |
+
# threshold to convert the nonstandard annotation imgs. The
|
| 62 |
+
# value divided by 128 is equivalent to '1 if value >= 128
|
| 63 |
+
# else 0'
|
| 64 |
+
mmcv.imwrite(
|
| 65 |
+
img[:, :, 0] // 128,
|
| 66 |
+
osp.join(out_dir, 'annotations', 'training',
|
| 67 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 68 |
+
|
| 69 |
+
for img_name in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]:
|
| 70 |
+
img = mmcv.imread(osp.join(tmp_dir, img_name))
|
| 71 |
+
if osp.splitext(img_name)[1] == '.jpg':
|
| 72 |
+
mmcv.imwrite(
|
| 73 |
+
img,
|
| 74 |
+
osp.join(out_dir, 'images', 'validation',
|
| 75 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 76 |
+
else:
|
| 77 |
+
mmcv.imwrite(
|
| 78 |
+
img[:, :, 0] // 128,
|
| 79 |
+
osp.join(out_dir, 'annotations', 'validation',
|
| 80 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 81 |
+
|
| 82 |
+
print('Removing the temporary files...')
|
| 83 |
+
|
| 84 |
+
print('Done!')
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == '__main__':
|
| 88 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/cityscapes.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os.path as osp
|
| 4 |
+
|
| 5 |
+
import mmcv
|
| 6 |
+
from cityscapesscripts.preparation.json2labelImg import json2labelImg
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def convert_json_to_label(json_file):
|
| 10 |
+
label_file = json_file.replace('_polygons.json', '_labelTrainIds.png')
|
| 11 |
+
json2labelImg(json_file, label_file, 'trainIds')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description='Convert Cityscapes annotations to TrainIds')
|
| 17 |
+
parser.add_argument('cityscapes_path', help='cityscapes data path')
|
| 18 |
+
parser.add_argument('--gt-dir', default='gtFine', type=str)
|
| 19 |
+
parser.add_argument('-o', '--out-dir', help='output path')
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
'--nproc', default=1, type=int, help='number of process')
|
| 22 |
+
args = parser.parse_args()
|
| 23 |
+
return args
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
args = parse_args()
|
| 28 |
+
cityscapes_path = args.cityscapes_path
|
| 29 |
+
out_dir = args.out_dir if args.out_dir else cityscapes_path
|
| 30 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 31 |
+
|
| 32 |
+
gt_dir = osp.join(cityscapes_path, args.gt_dir)
|
| 33 |
+
|
| 34 |
+
poly_files = []
|
| 35 |
+
for poly in mmcv.scandir(gt_dir, '_polygons.json', recursive=True):
|
| 36 |
+
poly_file = osp.join(gt_dir, poly)
|
| 37 |
+
poly_files.append(poly_file)
|
| 38 |
+
if args.nproc > 1:
|
| 39 |
+
mmcv.track_parallel_progress(convert_json_to_label, poly_files,
|
| 40 |
+
args.nproc)
|
| 41 |
+
else:
|
| 42 |
+
mmcv.track_progress(convert_json_to_label, poly_files)
|
| 43 |
+
|
| 44 |
+
split_names = ['train', 'val', 'test']
|
| 45 |
+
|
| 46 |
+
for split in split_names:
|
| 47 |
+
filenames = []
|
| 48 |
+
for poly in mmcv.scandir(
|
| 49 |
+
osp.join(gt_dir, split), '_polygons.json', recursive=True):
|
| 50 |
+
filenames.append(poly.replace('_gtFine_polygons.json', ''))
|
| 51 |
+
with open(osp.join(out_dir, f'{split}.txt'), 'w') as f:
|
| 52 |
+
f.writelines(f + '\n' for f in filenames)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == '__main__':
|
| 56 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff10k.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os.path as osp
|
| 4 |
+
import shutil
|
| 5 |
+
from functools import partial
|
| 6 |
+
|
| 7 |
+
import mmcv
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from scipy.io import loadmat
|
| 11 |
+
|
| 12 |
+
COCO_LEN = 10000
|
| 13 |
+
|
| 14 |
+
clsID_to_trID = {
|
| 15 |
+
0: 0,
|
| 16 |
+
1: 1,
|
| 17 |
+
2: 2,
|
| 18 |
+
3: 3,
|
| 19 |
+
4: 4,
|
| 20 |
+
5: 5,
|
| 21 |
+
6: 6,
|
| 22 |
+
7: 7,
|
| 23 |
+
8: 8,
|
| 24 |
+
9: 9,
|
| 25 |
+
10: 10,
|
| 26 |
+
11: 11,
|
| 27 |
+
13: 12,
|
| 28 |
+
14: 13,
|
| 29 |
+
15: 14,
|
| 30 |
+
16: 15,
|
| 31 |
+
17: 16,
|
| 32 |
+
18: 17,
|
| 33 |
+
19: 18,
|
| 34 |
+
20: 19,
|
| 35 |
+
21: 20,
|
| 36 |
+
22: 21,
|
| 37 |
+
23: 22,
|
| 38 |
+
24: 23,
|
| 39 |
+
25: 24,
|
| 40 |
+
27: 25,
|
| 41 |
+
28: 26,
|
| 42 |
+
31: 27,
|
| 43 |
+
32: 28,
|
| 44 |
+
33: 29,
|
| 45 |
+
34: 30,
|
| 46 |
+
35: 31,
|
| 47 |
+
36: 32,
|
| 48 |
+
37: 33,
|
| 49 |
+
38: 34,
|
| 50 |
+
39: 35,
|
| 51 |
+
40: 36,
|
| 52 |
+
41: 37,
|
| 53 |
+
42: 38,
|
| 54 |
+
43: 39,
|
| 55 |
+
44: 40,
|
| 56 |
+
46: 41,
|
| 57 |
+
47: 42,
|
| 58 |
+
48: 43,
|
| 59 |
+
49: 44,
|
| 60 |
+
50: 45,
|
| 61 |
+
51: 46,
|
| 62 |
+
52: 47,
|
| 63 |
+
53: 48,
|
| 64 |
+
54: 49,
|
| 65 |
+
55: 50,
|
| 66 |
+
56: 51,
|
| 67 |
+
57: 52,
|
| 68 |
+
58: 53,
|
| 69 |
+
59: 54,
|
| 70 |
+
60: 55,
|
| 71 |
+
61: 56,
|
| 72 |
+
62: 57,
|
| 73 |
+
63: 58,
|
| 74 |
+
64: 59,
|
| 75 |
+
65: 60,
|
| 76 |
+
67: 61,
|
| 77 |
+
70: 62,
|
| 78 |
+
72: 63,
|
| 79 |
+
73: 64,
|
| 80 |
+
74: 65,
|
| 81 |
+
75: 66,
|
| 82 |
+
76: 67,
|
| 83 |
+
77: 68,
|
| 84 |
+
78: 69,
|
| 85 |
+
79: 70,
|
| 86 |
+
80: 71,
|
| 87 |
+
81: 72,
|
| 88 |
+
82: 73,
|
| 89 |
+
84: 74,
|
| 90 |
+
85: 75,
|
| 91 |
+
86: 76,
|
| 92 |
+
87: 77,
|
| 93 |
+
88: 78,
|
| 94 |
+
89: 79,
|
| 95 |
+
90: 80,
|
| 96 |
+
92: 81,
|
| 97 |
+
93: 82,
|
| 98 |
+
94: 83,
|
| 99 |
+
95: 84,
|
| 100 |
+
96: 85,
|
| 101 |
+
97: 86,
|
| 102 |
+
98: 87,
|
| 103 |
+
99: 88,
|
| 104 |
+
100: 89,
|
| 105 |
+
101: 90,
|
| 106 |
+
102: 91,
|
| 107 |
+
103: 92,
|
| 108 |
+
104: 93,
|
| 109 |
+
105: 94,
|
| 110 |
+
106: 95,
|
| 111 |
+
107: 96,
|
| 112 |
+
108: 97,
|
| 113 |
+
109: 98,
|
| 114 |
+
110: 99,
|
| 115 |
+
111: 100,
|
| 116 |
+
112: 101,
|
| 117 |
+
113: 102,
|
| 118 |
+
114: 103,
|
| 119 |
+
115: 104,
|
| 120 |
+
116: 105,
|
| 121 |
+
117: 106,
|
| 122 |
+
118: 107,
|
| 123 |
+
119: 108,
|
| 124 |
+
120: 109,
|
| 125 |
+
121: 110,
|
| 126 |
+
122: 111,
|
| 127 |
+
123: 112,
|
| 128 |
+
124: 113,
|
| 129 |
+
125: 114,
|
| 130 |
+
126: 115,
|
| 131 |
+
127: 116,
|
| 132 |
+
128: 117,
|
| 133 |
+
129: 118,
|
| 134 |
+
130: 119,
|
| 135 |
+
131: 120,
|
| 136 |
+
132: 121,
|
| 137 |
+
133: 122,
|
| 138 |
+
134: 123,
|
| 139 |
+
135: 124,
|
| 140 |
+
136: 125,
|
| 141 |
+
137: 126,
|
| 142 |
+
138: 127,
|
| 143 |
+
139: 128,
|
| 144 |
+
140: 129,
|
| 145 |
+
141: 130,
|
| 146 |
+
142: 131,
|
| 147 |
+
143: 132,
|
| 148 |
+
144: 133,
|
| 149 |
+
145: 134,
|
| 150 |
+
146: 135,
|
| 151 |
+
147: 136,
|
| 152 |
+
148: 137,
|
| 153 |
+
149: 138,
|
| 154 |
+
150: 139,
|
| 155 |
+
151: 140,
|
| 156 |
+
152: 141,
|
| 157 |
+
153: 142,
|
| 158 |
+
154: 143,
|
| 159 |
+
155: 144,
|
| 160 |
+
156: 145,
|
| 161 |
+
157: 146,
|
| 162 |
+
158: 147,
|
| 163 |
+
159: 148,
|
| 164 |
+
160: 149,
|
| 165 |
+
161: 150,
|
| 166 |
+
162: 151,
|
| 167 |
+
163: 152,
|
| 168 |
+
164: 153,
|
| 169 |
+
165: 154,
|
| 170 |
+
166: 155,
|
| 171 |
+
167: 156,
|
| 172 |
+
168: 157,
|
| 173 |
+
169: 158,
|
| 174 |
+
170: 159,
|
| 175 |
+
171: 160,
|
| 176 |
+
172: 161,
|
| 177 |
+
173: 162,
|
| 178 |
+
174: 163,
|
| 179 |
+
175: 164,
|
| 180 |
+
176: 165,
|
| 181 |
+
177: 166,
|
| 182 |
+
178: 167,
|
| 183 |
+
179: 168,
|
| 184 |
+
180: 169,
|
| 185 |
+
181: 170,
|
| 186 |
+
182: 171
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def convert_to_trainID(tuple_path, in_img_dir, in_ann_dir, out_img_dir,
|
| 191 |
+
out_mask_dir, is_train):
|
| 192 |
+
imgpath, maskpath = tuple_path
|
| 193 |
+
shutil.copyfile(
|
| 194 |
+
osp.join(in_img_dir, imgpath),
|
| 195 |
+
osp.join(out_img_dir, 'train2014', imgpath) if is_train else osp.join(
|
| 196 |
+
out_img_dir, 'test2014', imgpath))
|
| 197 |
+
annotate = loadmat(osp.join(in_ann_dir, maskpath))
|
| 198 |
+
mask = annotate['S'].astype(np.uint8)
|
| 199 |
+
mask_copy = mask.copy()
|
| 200 |
+
for clsID, trID in clsID_to_trID.items():
|
| 201 |
+
mask_copy[mask == clsID] = trID
|
| 202 |
+
seg_filename = osp.join(out_mask_dir, 'train2014',
|
| 203 |
+
maskpath.split('.')[0] +
|
| 204 |
+
'_labelTrainIds.png') if is_train else osp.join(
|
| 205 |
+
out_mask_dir, 'test2014',
|
| 206 |
+
maskpath.split('.')[0] + '_labelTrainIds.png')
|
| 207 |
+
Image.fromarray(mask_copy).save(seg_filename, 'PNG')
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def generate_coco_list(folder):
|
| 211 |
+
train_list = osp.join(folder, 'imageLists', 'train.txt')
|
| 212 |
+
test_list = osp.join(folder, 'imageLists', 'test.txt')
|
| 213 |
+
train_paths = []
|
| 214 |
+
test_paths = []
|
| 215 |
+
|
| 216 |
+
with open(train_list) as f:
|
| 217 |
+
for filename in f:
|
| 218 |
+
basename = filename.strip()
|
| 219 |
+
imgpath = basename + '.jpg'
|
| 220 |
+
maskpath = basename + '.mat'
|
| 221 |
+
train_paths.append((imgpath, maskpath))
|
| 222 |
+
|
| 223 |
+
with open(test_list) as f:
|
| 224 |
+
for filename in f:
|
| 225 |
+
basename = filename.strip()
|
| 226 |
+
imgpath = basename + '.jpg'
|
| 227 |
+
maskpath = basename + '.mat'
|
| 228 |
+
test_paths.append((imgpath, maskpath))
|
| 229 |
+
|
| 230 |
+
return train_paths, test_paths
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def parse_args():
|
| 234 |
+
parser = argparse.ArgumentParser(
|
| 235 |
+
description=\
|
| 236 |
+
'Convert COCO Stuff 10k annotations to mmsegmentation format') # noqa
|
| 237 |
+
parser.add_argument('coco_path', help='coco stuff path')
|
| 238 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
'--nproc', default=16, type=int, help='number of process')
|
| 241 |
+
args = parser.parse_args()
|
| 242 |
+
return args
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def main():
|
| 246 |
+
args = parse_args()
|
| 247 |
+
coco_path = args.coco_path
|
| 248 |
+
nproc = args.nproc
|
| 249 |
+
|
| 250 |
+
out_dir = args.out_dir or coco_path
|
| 251 |
+
out_img_dir = osp.join(out_dir, 'images')
|
| 252 |
+
out_mask_dir = osp.join(out_dir, 'annotations')
|
| 253 |
+
|
| 254 |
+
mmcv.mkdir_or_exist(osp.join(out_img_dir, 'train2014'))
|
| 255 |
+
mmcv.mkdir_or_exist(osp.join(out_img_dir, 'test2014'))
|
| 256 |
+
mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'train2014'))
|
| 257 |
+
mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'test2014'))
|
| 258 |
+
|
| 259 |
+
train_list, test_list = generate_coco_list(coco_path)
|
| 260 |
+
assert (len(train_list) +
|
| 261 |
+
len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format(
|
| 262 |
+
len(train_list), len(test_list))
|
| 263 |
+
|
| 264 |
+
if args.nproc > 1:
|
| 265 |
+
mmcv.track_parallel_progress(
|
| 266 |
+
partial(
|
| 267 |
+
convert_to_trainID,
|
| 268 |
+
in_img_dir=osp.join(coco_path, 'images'),
|
| 269 |
+
in_ann_dir=osp.join(coco_path, 'annotations'),
|
| 270 |
+
out_img_dir=out_img_dir,
|
| 271 |
+
out_mask_dir=out_mask_dir,
|
| 272 |
+
is_train=True),
|
| 273 |
+
train_list,
|
| 274 |
+
nproc=nproc)
|
| 275 |
+
mmcv.track_parallel_progress(
|
| 276 |
+
partial(
|
| 277 |
+
convert_to_trainID,
|
| 278 |
+
in_img_dir=osp.join(coco_path, 'images'),
|
| 279 |
+
in_ann_dir=osp.join(coco_path, 'annotations'),
|
| 280 |
+
out_img_dir=out_img_dir,
|
| 281 |
+
out_mask_dir=out_mask_dir,
|
| 282 |
+
is_train=False),
|
| 283 |
+
test_list,
|
| 284 |
+
nproc=nproc)
|
| 285 |
+
else:
|
| 286 |
+
mmcv.track_progress(
|
| 287 |
+
partial(
|
| 288 |
+
convert_to_trainID,
|
| 289 |
+
in_img_dir=osp.join(coco_path, 'images'),
|
| 290 |
+
in_ann_dir=osp.join(coco_path, 'annotations'),
|
| 291 |
+
out_img_dir=out_img_dir,
|
| 292 |
+
out_mask_dir=out_mask_dir,
|
| 293 |
+
is_train=True), train_list)
|
| 294 |
+
mmcv.track_progress(
|
| 295 |
+
partial(
|
| 296 |
+
convert_to_trainID,
|
| 297 |
+
in_img_dir=osp.join(coco_path, 'images'),
|
| 298 |
+
in_ann_dir=osp.join(coco_path, 'annotations'),
|
| 299 |
+
out_img_dir=out_img_dir,
|
| 300 |
+
out_mask_dir=out_mask_dir,
|
| 301 |
+
is_train=False), test_list)
|
| 302 |
+
|
| 303 |
+
print('Done!')
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == '__main__':
|
| 307 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff164k.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os.path as osp
|
| 4 |
+
import shutil
|
| 5 |
+
from functools import partial
|
| 6 |
+
from glob import glob
|
| 7 |
+
|
| 8 |
+
import mmcv
|
| 9 |
+
import numpy as np
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
COCO_LEN = 123287
|
| 13 |
+
|
| 14 |
+
clsID_to_trID = {
|
| 15 |
+
0: 0,
|
| 16 |
+
1: 1,
|
| 17 |
+
2: 2,
|
| 18 |
+
3: 3,
|
| 19 |
+
4: 4,
|
| 20 |
+
5: 5,
|
| 21 |
+
6: 6,
|
| 22 |
+
7: 7,
|
| 23 |
+
8: 8,
|
| 24 |
+
9: 9,
|
| 25 |
+
10: 10,
|
| 26 |
+
12: 11,
|
| 27 |
+
13: 12,
|
| 28 |
+
14: 13,
|
| 29 |
+
15: 14,
|
| 30 |
+
16: 15,
|
| 31 |
+
17: 16,
|
| 32 |
+
18: 17,
|
| 33 |
+
19: 18,
|
| 34 |
+
20: 19,
|
| 35 |
+
21: 20,
|
| 36 |
+
22: 21,
|
| 37 |
+
23: 22,
|
| 38 |
+
24: 23,
|
| 39 |
+
26: 24,
|
| 40 |
+
27: 25,
|
| 41 |
+
30: 26,
|
| 42 |
+
31: 27,
|
| 43 |
+
32: 28,
|
| 44 |
+
33: 29,
|
| 45 |
+
34: 30,
|
| 46 |
+
35: 31,
|
| 47 |
+
36: 32,
|
| 48 |
+
37: 33,
|
| 49 |
+
38: 34,
|
| 50 |
+
39: 35,
|
| 51 |
+
40: 36,
|
| 52 |
+
41: 37,
|
| 53 |
+
42: 38,
|
| 54 |
+
43: 39,
|
| 55 |
+
45: 40,
|
| 56 |
+
46: 41,
|
| 57 |
+
47: 42,
|
| 58 |
+
48: 43,
|
| 59 |
+
49: 44,
|
| 60 |
+
50: 45,
|
| 61 |
+
51: 46,
|
| 62 |
+
52: 47,
|
| 63 |
+
53: 48,
|
| 64 |
+
54: 49,
|
| 65 |
+
55: 50,
|
| 66 |
+
56: 51,
|
| 67 |
+
57: 52,
|
| 68 |
+
58: 53,
|
| 69 |
+
59: 54,
|
| 70 |
+
60: 55,
|
| 71 |
+
61: 56,
|
| 72 |
+
62: 57,
|
| 73 |
+
63: 58,
|
| 74 |
+
64: 59,
|
| 75 |
+
66: 60,
|
| 76 |
+
69: 61,
|
| 77 |
+
71: 62,
|
| 78 |
+
72: 63,
|
| 79 |
+
73: 64,
|
| 80 |
+
74: 65,
|
| 81 |
+
75: 66,
|
| 82 |
+
76: 67,
|
| 83 |
+
77: 68,
|
| 84 |
+
78: 69,
|
| 85 |
+
79: 70,
|
| 86 |
+
80: 71,
|
| 87 |
+
81: 72,
|
| 88 |
+
83: 73,
|
| 89 |
+
84: 74,
|
| 90 |
+
85: 75,
|
| 91 |
+
86: 76,
|
| 92 |
+
87: 77,
|
| 93 |
+
88: 78,
|
| 94 |
+
89: 79,
|
| 95 |
+
91: 80,
|
| 96 |
+
92: 81,
|
| 97 |
+
93: 82,
|
| 98 |
+
94: 83,
|
| 99 |
+
95: 84,
|
| 100 |
+
96: 85,
|
| 101 |
+
97: 86,
|
| 102 |
+
98: 87,
|
| 103 |
+
99: 88,
|
| 104 |
+
100: 89,
|
| 105 |
+
101: 90,
|
| 106 |
+
102: 91,
|
| 107 |
+
103: 92,
|
| 108 |
+
104: 93,
|
| 109 |
+
105: 94,
|
| 110 |
+
106: 95,
|
| 111 |
+
107: 96,
|
| 112 |
+
108: 97,
|
| 113 |
+
109: 98,
|
| 114 |
+
110: 99,
|
| 115 |
+
111: 100,
|
| 116 |
+
112: 101,
|
| 117 |
+
113: 102,
|
| 118 |
+
114: 103,
|
| 119 |
+
115: 104,
|
| 120 |
+
116: 105,
|
| 121 |
+
117: 106,
|
| 122 |
+
118: 107,
|
| 123 |
+
119: 108,
|
| 124 |
+
120: 109,
|
| 125 |
+
121: 110,
|
| 126 |
+
122: 111,
|
| 127 |
+
123: 112,
|
| 128 |
+
124: 113,
|
| 129 |
+
125: 114,
|
| 130 |
+
126: 115,
|
| 131 |
+
127: 116,
|
| 132 |
+
128: 117,
|
| 133 |
+
129: 118,
|
| 134 |
+
130: 119,
|
| 135 |
+
131: 120,
|
| 136 |
+
132: 121,
|
| 137 |
+
133: 122,
|
| 138 |
+
134: 123,
|
| 139 |
+
135: 124,
|
| 140 |
+
136: 125,
|
| 141 |
+
137: 126,
|
| 142 |
+
138: 127,
|
| 143 |
+
139: 128,
|
| 144 |
+
140: 129,
|
| 145 |
+
141: 130,
|
| 146 |
+
142: 131,
|
| 147 |
+
143: 132,
|
| 148 |
+
144: 133,
|
| 149 |
+
145: 134,
|
| 150 |
+
146: 135,
|
| 151 |
+
147: 136,
|
| 152 |
+
148: 137,
|
| 153 |
+
149: 138,
|
| 154 |
+
150: 139,
|
| 155 |
+
151: 140,
|
| 156 |
+
152: 141,
|
| 157 |
+
153: 142,
|
| 158 |
+
154: 143,
|
| 159 |
+
155: 144,
|
| 160 |
+
156: 145,
|
| 161 |
+
157: 146,
|
| 162 |
+
158: 147,
|
| 163 |
+
159: 148,
|
| 164 |
+
160: 149,
|
| 165 |
+
161: 150,
|
| 166 |
+
162: 151,
|
| 167 |
+
163: 152,
|
| 168 |
+
164: 153,
|
| 169 |
+
165: 154,
|
| 170 |
+
166: 155,
|
| 171 |
+
167: 156,
|
| 172 |
+
168: 157,
|
| 173 |
+
169: 158,
|
| 174 |
+
170: 159,
|
| 175 |
+
171: 160,
|
| 176 |
+
172: 161,
|
| 177 |
+
173: 162,
|
| 178 |
+
174: 163,
|
| 179 |
+
175: 164,
|
| 180 |
+
176: 165,
|
| 181 |
+
177: 166,
|
| 182 |
+
178: 167,
|
| 183 |
+
179: 168,
|
| 184 |
+
180: 169,
|
| 185 |
+
181: 170,
|
| 186 |
+
255: 255
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def convert_to_trainID(maskpath, out_mask_dir, is_train):
|
| 191 |
+
mask = np.array(Image.open(maskpath))
|
| 192 |
+
mask_copy = mask.copy()
|
| 193 |
+
for clsID, trID in clsID_to_trID.items():
|
| 194 |
+
mask_copy[mask == clsID] = trID
|
| 195 |
+
seg_filename = osp.join(
|
| 196 |
+
out_mask_dir, 'train2017',
|
| 197 |
+
osp.basename(maskpath).split('.')[0] +
|
| 198 |
+
'_labelTrainIds.png') if is_train else osp.join(
|
| 199 |
+
out_mask_dir, 'val2017',
|
| 200 |
+
osp.basename(maskpath).split('.')[0] + '_labelTrainIds.png')
|
| 201 |
+
Image.fromarray(mask_copy).save(seg_filename, 'PNG')
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def parse_args():
|
| 205 |
+
parser = argparse.ArgumentParser(
|
| 206 |
+
description=\
|
| 207 |
+
'Convert COCO Stuff 164k annotations to mmsegmentation format') # noqa
|
| 208 |
+
parser.add_argument('coco_path', help='coco stuff path')
|
| 209 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
'--nproc', default=16, type=int, help='number of process')
|
| 212 |
+
args = parser.parse_args()
|
| 213 |
+
return args
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def main():
|
| 217 |
+
args = parse_args()
|
| 218 |
+
coco_path = args.coco_path
|
| 219 |
+
nproc = args.nproc
|
| 220 |
+
|
| 221 |
+
out_dir = args.out_dir or coco_path
|
| 222 |
+
out_img_dir = osp.join(out_dir, 'images')
|
| 223 |
+
out_mask_dir = osp.join(out_dir, 'annotations')
|
| 224 |
+
|
| 225 |
+
mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'train2017'))
|
| 226 |
+
mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'val2017'))
|
| 227 |
+
|
| 228 |
+
if out_dir != coco_path:
|
| 229 |
+
shutil.copytree(osp.join(coco_path, 'images'), out_img_dir)
|
| 230 |
+
|
| 231 |
+
train_list = glob(osp.join(coco_path, 'annotations', 'train2017', '*.png'))
|
| 232 |
+
train_list = [file for file in train_list if '_labelTrainIds' not in file]
|
| 233 |
+
test_list = glob(osp.join(coco_path, 'annotations', 'val2017', '*.png'))
|
| 234 |
+
test_list = [file for file in test_list if '_labelTrainIds' not in file]
|
| 235 |
+
assert (len(train_list) +
|
| 236 |
+
len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format(
|
| 237 |
+
len(train_list), len(test_list))
|
| 238 |
+
|
| 239 |
+
if args.nproc > 1:
|
| 240 |
+
mmcv.track_parallel_progress(
|
| 241 |
+
partial(
|
| 242 |
+
convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True),
|
| 243 |
+
train_list,
|
| 244 |
+
nproc=nproc)
|
| 245 |
+
mmcv.track_parallel_progress(
|
| 246 |
+
partial(
|
| 247 |
+
convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False),
|
| 248 |
+
test_list,
|
| 249 |
+
nproc=nproc)
|
| 250 |
+
else:
|
| 251 |
+
mmcv.track_progress(
|
| 252 |
+
partial(
|
| 253 |
+
convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True),
|
| 254 |
+
train_list)
|
| 255 |
+
mmcv.track_progress(
|
| 256 |
+
partial(
|
| 257 |
+
convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False),
|
| 258 |
+
test_list)
|
| 259 |
+
|
| 260 |
+
print('Done!')
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
if __name__ == '__main__':
|
| 264 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/drive.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import tempfile
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import mmcv
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_args():
|
| 13 |
+
parser = argparse.ArgumentParser(
|
| 14 |
+
description='Convert DRIVE dataset to mmsegmentation format')
|
| 15 |
+
parser.add_argument(
|
| 16 |
+
'training_path', help='the training part of DRIVE dataset')
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
'testing_path', help='the testing part of DRIVE dataset')
|
| 19 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 20 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 21 |
+
args = parser.parse_args()
|
| 22 |
+
return args
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
args = parse_args()
|
| 27 |
+
training_path = args.training_path
|
| 28 |
+
testing_path = args.testing_path
|
| 29 |
+
if args.out_dir is None:
|
| 30 |
+
out_dir = osp.join('data', 'DRIVE')
|
| 31 |
+
else:
|
| 32 |
+
out_dir = args.out_dir
|
| 33 |
+
|
| 34 |
+
print('Making directories...')
|
| 35 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 36 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images'))
|
| 37 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training'))
|
| 38 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation'))
|
| 39 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations'))
|
| 40 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training'))
|
| 41 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation'))
|
| 42 |
+
|
| 43 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 44 |
+
print('Extracting training.zip...')
|
| 45 |
+
zip_file = zipfile.ZipFile(training_path)
|
| 46 |
+
zip_file.extractall(tmp_dir)
|
| 47 |
+
|
| 48 |
+
print('Generating training dataset...')
|
| 49 |
+
now_dir = osp.join(tmp_dir, 'training', 'images')
|
| 50 |
+
for img_name in os.listdir(now_dir):
|
| 51 |
+
img = mmcv.imread(osp.join(now_dir, img_name))
|
| 52 |
+
mmcv.imwrite(
|
| 53 |
+
img,
|
| 54 |
+
osp.join(
|
| 55 |
+
out_dir, 'images', 'training',
|
| 56 |
+
osp.splitext(img_name)[0].replace('_training', '') +
|
| 57 |
+
'.png'))
|
| 58 |
+
|
| 59 |
+
now_dir = osp.join(tmp_dir, 'training', '1st_manual')
|
| 60 |
+
for img_name in os.listdir(now_dir):
|
| 61 |
+
cap = cv2.VideoCapture(osp.join(now_dir, img_name))
|
| 62 |
+
ret, img = cap.read()
|
| 63 |
+
mmcv.imwrite(
|
| 64 |
+
img[:, :, 0] // 128,
|
| 65 |
+
osp.join(out_dir, 'annotations', 'training',
|
| 66 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 67 |
+
|
| 68 |
+
print('Extracting test.zip...')
|
| 69 |
+
zip_file = zipfile.ZipFile(testing_path)
|
| 70 |
+
zip_file.extractall(tmp_dir)
|
| 71 |
+
|
| 72 |
+
print('Generating validation dataset...')
|
| 73 |
+
now_dir = osp.join(tmp_dir, 'test', 'images')
|
| 74 |
+
for img_name in os.listdir(now_dir):
|
| 75 |
+
img = mmcv.imread(osp.join(now_dir, img_name))
|
| 76 |
+
mmcv.imwrite(
|
| 77 |
+
img,
|
| 78 |
+
osp.join(
|
| 79 |
+
out_dir, 'images', 'validation',
|
| 80 |
+
osp.splitext(img_name)[0].replace('_test', '') + '.png'))
|
| 81 |
+
|
| 82 |
+
now_dir = osp.join(tmp_dir, 'test', '1st_manual')
|
| 83 |
+
if osp.exists(now_dir):
|
| 84 |
+
for img_name in os.listdir(now_dir):
|
| 85 |
+
cap = cv2.VideoCapture(osp.join(now_dir, img_name))
|
| 86 |
+
ret, img = cap.read()
|
| 87 |
+
# The annotation img should be divided by 128, because some of
|
| 88 |
+
# the annotation imgs are not standard. We should set a
|
| 89 |
+
# threshold to convert the nonstandard annotation imgs. The
|
| 90 |
+
# value divided by 128 is equivalent to '1 if value >= 128
|
| 91 |
+
# else 0'
|
| 92 |
+
mmcv.imwrite(
|
| 93 |
+
img[:, :, 0] // 128,
|
| 94 |
+
osp.join(out_dir, 'annotations', 'validation',
|
| 95 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 96 |
+
|
| 97 |
+
now_dir = osp.join(tmp_dir, 'test', '2nd_manual')
|
| 98 |
+
if osp.exists(now_dir):
|
| 99 |
+
for img_name in os.listdir(now_dir):
|
| 100 |
+
cap = cv2.VideoCapture(osp.join(now_dir, img_name))
|
| 101 |
+
ret, img = cap.read()
|
| 102 |
+
mmcv.imwrite(
|
| 103 |
+
img[:, :, 0] // 128,
|
| 104 |
+
osp.join(out_dir, 'annotations', 'validation',
|
| 105 |
+
osp.splitext(img_name)[0] + '.png'))
|
| 106 |
+
|
| 107 |
+
print('Removing the temporary files...')
|
| 108 |
+
|
| 109 |
+
print('Done!')
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == '__main__':
|
| 113 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/hrf.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import tempfile
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
import mmcv
|
| 9 |
+
|
| 10 |
+
HRF_LEN = 15
|
| 11 |
+
TRAINING_LEN = 5
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description='Convert HRF dataset to mmsegmentation format')
|
| 17 |
+
parser.add_argument('healthy_path', help='the path of healthy.zip')
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
'healthy_manualsegm_path', help='the path of healthy_manualsegm.zip')
|
| 20 |
+
parser.add_argument('glaucoma_path', help='the path of glaucoma.zip')
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
'glaucoma_manualsegm_path', help='the path of glaucoma_manualsegm.zip')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'diabetic_retinopathy_path',
|
| 25 |
+
help='the path of diabetic_retinopathy.zip')
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
'diabetic_retinopathy_manualsegm_path',
|
| 28 |
+
help='the path of diabetic_retinopathy_manualsegm.zip')
|
| 29 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 30 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
return args
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
args = parse_args()
|
| 37 |
+
images_path = [
|
| 38 |
+
args.healthy_path, args.glaucoma_path, args.diabetic_retinopathy_path
|
| 39 |
+
]
|
| 40 |
+
annotations_path = [
|
| 41 |
+
args.healthy_manualsegm_path, args.glaucoma_manualsegm_path,
|
| 42 |
+
args.diabetic_retinopathy_manualsegm_path
|
| 43 |
+
]
|
| 44 |
+
if args.out_dir is None:
|
| 45 |
+
out_dir = osp.join('data', 'HRF')
|
| 46 |
+
else:
|
| 47 |
+
out_dir = args.out_dir
|
| 48 |
+
|
| 49 |
+
print('Making directories...')
|
| 50 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 51 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images'))
|
| 52 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training'))
|
| 53 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation'))
|
| 54 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations'))
|
| 55 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training'))
|
| 56 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation'))
|
| 57 |
+
|
| 58 |
+
print('Generating images...')
|
| 59 |
+
for now_path in images_path:
|
| 60 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 61 |
+
zip_file = zipfile.ZipFile(now_path)
|
| 62 |
+
zip_file.extractall(tmp_dir)
|
| 63 |
+
|
| 64 |
+
assert len(os.listdir(tmp_dir)) == HRF_LEN, \
|
| 65 |
+
'len(os.listdir(tmp_dir)) != {}'.format(HRF_LEN)
|
| 66 |
+
|
| 67 |
+
for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]:
|
| 68 |
+
img = mmcv.imread(osp.join(tmp_dir, filename))
|
| 69 |
+
mmcv.imwrite(
|
| 70 |
+
img,
|
| 71 |
+
osp.join(out_dir, 'images', 'training',
|
| 72 |
+
osp.splitext(filename)[0] + '.png'))
|
| 73 |
+
for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]:
|
| 74 |
+
img = mmcv.imread(osp.join(tmp_dir, filename))
|
| 75 |
+
mmcv.imwrite(
|
| 76 |
+
img,
|
| 77 |
+
osp.join(out_dir, 'images', 'validation',
|
| 78 |
+
osp.splitext(filename)[0] + '.png'))
|
| 79 |
+
|
| 80 |
+
print('Generating annotations...')
|
| 81 |
+
for now_path in annotations_path:
|
| 82 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 83 |
+
zip_file = zipfile.ZipFile(now_path)
|
| 84 |
+
zip_file.extractall(tmp_dir)
|
| 85 |
+
|
| 86 |
+
assert len(os.listdir(tmp_dir)) == HRF_LEN, \
|
| 87 |
+
'len(os.listdir(tmp_dir)) != {}'.format(HRF_LEN)
|
| 88 |
+
|
| 89 |
+
for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]:
|
| 90 |
+
img = mmcv.imread(osp.join(tmp_dir, filename))
|
| 91 |
+
# The annotation img should be divided by 128, because some of
|
| 92 |
+
# the annotation imgs are not standard. We should set a
|
| 93 |
+
# threshold to convert the nonstandard annotation imgs. The
|
| 94 |
+
# value divided by 128 is equivalent to '1 if value >= 128
|
| 95 |
+
# else 0'
|
| 96 |
+
mmcv.imwrite(
|
| 97 |
+
img[:, :, 0] // 128,
|
| 98 |
+
osp.join(out_dir, 'annotations', 'training',
|
| 99 |
+
osp.splitext(filename)[0] + '.png'))
|
| 100 |
+
for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]:
|
| 101 |
+
img = mmcv.imread(osp.join(tmp_dir, filename))
|
| 102 |
+
mmcv.imwrite(
|
| 103 |
+
img[:, :, 0] // 128,
|
| 104 |
+
osp.join(out_dir, 'annotations', 'validation',
|
| 105 |
+
osp.splitext(filename)[0] + '.png'))
|
| 106 |
+
|
| 107 |
+
print('Done!')
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == '__main__':
|
| 111 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/isaid.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import glob
|
| 4 |
+
import os
|
| 5 |
+
import os.path as osp
|
| 6 |
+
import shutil
|
| 7 |
+
import tempfile
|
| 8 |
+
import zipfile
|
| 9 |
+
|
| 10 |
+
import mmcv
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
iSAID_palette = \
|
| 15 |
+
{
|
| 16 |
+
0: (0, 0, 0),
|
| 17 |
+
1: (0, 0, 63),
|
| 18 |
+
2: (0, 63, 63),
|
| 19 |
+
3: (0, 63, 0),
|
| 20 |
+
4: (0, 63, 127),
|
| 21 |
+
5: (0, 63, 191),
|
| 22 |
+
6: (0, 63, 255),
|
| 23 |
+
7: (0, 127, 63),
|
| 24 |
+
8: (0, 127, 127),
|
| 25 |
+
9: (0, 0, 127),
|
| 26 |
+
10: (0, 0, 191),
|
| 27 |
+
11: (0, 0, 255),
|
| 28 |
+
12: (0, 191, 127),
|
| 29 |
+
13: (0, 127, 191),
|
| 30 |
+
14: (0, 127, 255),
|
| 31 |
+
15: (0, 100, 155)
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
iSAID_invert_palette = {v: k for k, v in iSAID_palette.items()}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def iSAID_convert_from_color(arr_3d, palette=iSAID_invert_palette):
|
| 38 |
+
"""RGB-color encoding to grayscale labels."""
|
| 39 |
+
arr_2d = np.zeros((arr_3d.shape[0], arr_3d.shape[1]), dtype=np.uint8)
|
| 40 |
+
|
| 41 |
+
for c, i in palette.items():
|
| 42 |
+
m = np.all(arr_3d == np.array(c).reshape(1, 1, 3), axis=2)
|
| 43 |
+
arr_2d[m] = i
|
| 44 |
+
|
| 45 |
+
return arr_2d
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def slide_crop_image(src_path, out_dir, mode, patch_H, patch_W, overlap):
|
| 49 |
+
img = np.asarray(Image.open(src_path).convert('RGB'))
|
| 50 |
+
|
| 51 |
+
img_H, img_W, _ = img.shape
|
| 52 |
+
|
| 53 |
+
if img_H < patch_H and img_W > patch_W:
|
| 54 |
+
|
| 55 |
+
img = mmcv.impad(img, shape=(patch_H, img_W), pad_val=0)
|
| 56 |
+
|
| 57 |
+
img_H, img_W, _ = img.shape
|
| 58 |
+
|
| 59 |
+
elif img_H > patch_H and img_W < patch_W:
|
| 60 |
+
|
| 61 |
+
img = mmcv.impad(img, shape=(img_H, patch_W), pad_val=0)
|
| 62 |
+
|
| 63 |
+
img_H, img_W, _ = img.shape
|
| 64 |
+
|
| 65 |
+
elif img_H < patch_H and img_W < patch_W:
|
| 66 |
+
|
| 67 |
+
img = mmcv.impad(img, shape=(patch_H, patch_W), pad_val=0)
|
| 68 |
+
|
| 69 |
+
img_H, img_W, _ = img.shape
|
| 70 |
+
|
| 71 |
+
for x in range(0, img_W, patch_W - overlap):
|
| 72 |
+
for y in range(0, img_H, patch_H - overlap):
|
| 73 |
+
x_str = x
|
| 74 |
+
x_end = x + patch_W
|
| 75 |
+
if x_end > img_W:
|
| 76 |
+
diff_x = x_end - img_W
|
| 77 |
+
x_str -= diff_x
|
| 78 |
+
x_end = img_W
|
| 79 |
+
y_str = y
|
| 80 |
+
y_end = y + patch_H
|
| 81 |
+
if y_end > img_H:
|
| 82 |
+
diff_y = y_end - img_H
|
| 83 |
+
y_str -= diff_y
|
| 84 |
+
y_end = img_H
|
| 85 |
+
|
| 86 |
+
img_patch = img[y_str:y_end, x_str:x_end, :]
|
| 87 |
+
img_patch = Image.fromarray(img_patch.astype(np.uint8))
|
| 88 |
+
image = osp.basename(src_path).split('.')[0] + '_' + str(
|
| 89 |
+
y_str) + '_' + str(y_end) + '_' + str(x_str) + '_' + str(
|
| 90 |
+
x_end) + '.png'
|
| 91 |
+
# print(image)
|
| 92 |
+
save_path_image = osp.join(out_dir, 'img_dir', mode, str(image))
|
| 93 |
+
img_patch.save(save_path_image)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def slide_crop_label(src_path, out_dir, mode, patch_H, patch_W, overlap):
|
| 97 |
+
label = mmcv.imread(src_path, channel_order='rgb')
|
| 98 |
+
label = iSAID_convert_from_color(label)
|
| 99 |
+
img_H, img_W = label.shape
|
| 100 |
+
|
| 101 |
+
if img_H < patch_H and img_W > patch_W:
|
| 102 |
+
|
| 103 |
+
label = mmcv.impad(label, shape=(patch_H, img_W), pad_val=255)
|
| 104 |
+
|
| 105 |
+
img_H = patch_H
|
| 106 |
+
|
| 107 |
+
elif img_H > patch_H and img_W < patch_W:
|
| 108 |
+
|
| 109 |
+
label = mmcv.impad(label, shape=(img_H, patch_W), pad_val=255)
|
| 110 |
+
|
| 111 |
+
img_W = patch_W
|
| 112 |
+
|
| 113 |
+
elif img_H < patch_H and img_W < patch_W:
|
| 114 |
+
|
| 115 |
+
label = mmcv.impad(label, shape=(patch_H, patch_W), pad_val=255)
|
| 116 |
+
|
| 117 |
+
img_H = patch_H
|
| 118 |
+
img_W = patch_W
|
| 119 |
+
|
| 120 |
+
for x in range(0, img_W, patch_W - overlap):
|
| 121 |
+
for y in range(0, img_H, patch_H - overlap):
|
| 122 |
+
x_str = x
|
| 123 |
+
x_end = x + patch_W
|
| 124 |
+
if x_end > img_W:
|
| 125 |
+
diff_x = x_end - img_W
|
| 126 |
+
x_str -= diff_x
|
| 127 |
+
x_end = img_W
|
| 128 |
+
y_str = y
|
| 129 |
+
y_end = y + patch_H
|
| 130 |
+
if y_end > img_H:
|
| 131 |
+
diff_y = y_end - img_H
|
| 132 |
+
y_str -= diff_y
|
| 133 |
+
y_end = img_H
|
| 134 |
+
|
| 135 |
+
lab_patch = label[y_str:y_end, x_str:x_end]
|
| 136 |
+
lab_patch = Image.fromarray(lab_patch.astype(np.uint8), mode='P')
|
| 137 |
+
|
| 138 |
+
image = osp.basename(src_path).split('.')[0].split(
|
| 139 |
+
'_')[0] + '_' + str(y_str) + '_' + str(y_end) + '_' + str(
|
| 140 |
+
x_str) + '_' + str(x_end) + '_instance_color_RGB' + '.png'
|
| 141 |
+
lab_patch.save(osp.join(out_dir, 'ann_dir', mode, str(image)))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def parse_args():
|
| 145 |
+
parser = argparse.ArgumentParser(
|
| 146 |
+
description='Convert iSAID dataset to mmsegmentation format')
|
| 147 |
+
parser.add_argument('dataset_path', help='iSAID folder path')
|
| 148 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 149 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 150 |
+
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
'--patch_width',
|
| 153 |
+
default=896,
|
| 154 |
+
type=int,
|
| 155 |
+
help='Width of the cropped image patch')
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
'--patch_height',
|
| 158 |
+
default=896,
|
| 159 |
+
type=int,
|
| 160 |
+
help='Height of the cropped image patch')
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
'--overlap_area', default=384, type=int, help='Overlap area')
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
return args
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def main():
|
| 168 |
+
args = parse_args()
|
| 169 |
+
dataset_path = args.dataset_path
|
| 170 |
+
# image patch width and height
|
| 171 |
+
patch_H, patch_W = args.patch_width, args.patch_height
|
| 172 |
+
|
| 173 |
+
overlap = args.overlap_area # overlap area
|
| 174 |
+
|
| 175 |
+
if args.out_dir is None:
|
| 176 |
+
out_dir = osp.join('data', 'iSAID')
|
| 177 |
+
else:
|
| 178 |
+
out_dir = args.out_dir
|
| 179 |
+
|
| 180 |
+
print('Making directories...')
|
| 181 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train'))
|
| 182 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val'))
|
| 183 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test'))
|
| 184 |
+
|
| 185 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train'))
|
| 186 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val'))
|
| 187 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'test'))
|
| 188 |
+
|
| 189 |
+
assert os.path.exists(os.path.join(dataset_path, 'train')), \
|
| 190 |
+
'train is not in {}'.format(dataset_path)
|
| 191 |
+
assert os.path.exists(os.path.join(dataset_path, 'val')), \
|
| 192 |
+
'val is not in {}'.format(dataset_path)
|
| 193 |
+
assert os.path.exists(os.path.join(dataset_path, 'test')), \
|
| 194 |
+
'test is not in {}'.format(dataset_path)
|
| 195 |
+
|
| 196 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 197 |
+
for dataset_mode in ['train', 'val', 'test']:
|
| 198 |
+
|
| 199 |
+
# for dataset_mode in [ 'test']:
|
| 200 |
+
print('Extracting {}ing.zip...'.format(dataset_mode))
|
| 201 |
+
img_zipp_list = glob.glob(
|
| 202 |
+
os.path.join(dataset_path, dataset_mode, 'images', '*.zip'))
|
| 203 |
+
print('Find the data', img_zipp_list)
|
| 204 |
+
for img_zipp in img_zipp_list:
|
| 205 |
+
zip_file = zipfile.ZipFile(img_zipp)
|
| 206 |
+
zip_file.extractall(os.path.join(tmp_dir, dataset_mode, 'img'))
|
| 207 |
+
src_path_list = glob.glob(
|
| 208 |
+
os.path.join(tmp_dir, dataset_mode, 'img', 'images', '*.png'))
|
| 209 |
+
|
| 210 |
+
src_prog_bar = mmcv.ProgressBar(len(src_path_list))
|
| 211 |
+
for i, img_path in enumerate(src_path_list):
|
| 212 |
+
if dataset_mode != 'test':
|
| 213 |
+
slide_crop_image(img_path, out_dir, dataset_mode, patch_H,
|
| 214 |
+
patch_W, overlap)
|
| 215 |
+
|
| 216 |
+
else:
|
| 217 |
+
shutil.move(img_path,
|
| 218 |
+
os.path.join(out_dir, 'img_dir', dataset_mode))
|
| 219 |
+
src_prog_bar.update()
|
| 220 |
+
|
| 221 |
+
if dataset_mode != 'test':
|
| 222 |
+
label_zipp_list = glob.glob(
|
| 223 |
+
os.path.join(dataset_path, dataset_mode, 'Semantic_masks',
|
| 224 |
+
'*.zip'))
|
| 225 |
+
for label_zipp in label_zipp_list:
|
| 226 |
+
zip_file = zipfile.ZipFile(label_zipp)
|
| 227 |
+
zip_file.extractall(
|
| 228 |
+
os.path.join(tmp_dir, dataset_mode, 'lab'))
|
| 229 |
+
|
| 230 |
+
lab_path_list = glob.glob(
|
| 231 |
+
os.path.join(tmp_dir, dataset_mode, 'lab', 'images',
|
| 232 |
+
'*.png'))
|
| 233 |
+
lab_prog_bar = mmcv.ProgressBar(len(lab_path_list))
|
| 234 |
+
for i, lab_path in enumerate(lab_path_list):
|
| 235 |
+
slide_crop_label(lab_path, out_dir, dataset_mode, patch_H,
|
| 236 |
+
patch_W, overlap)
|
| 237 |
+
lab_prog_bar.update()
|
| 238 |
+
|
| 239 |
+
print('Removing the temporary files...')
|
| 240 |
+
|
| 241 |
+
print('Done!')
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == '__main__':
|
| 245 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/loveda.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import shutil
|
| 6 |
+
import tempfile
|
| 7 |
+
import zipfile
|
| 8 |
+
|
| 9 |
+
import mmcv
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_args():
|
| 13 |
+
parser = argparse.ArgumentParser(
|
| 14 |
+
description='Convert LoveDA dataset to mmsegmentation format')
|
| 15 |
+
parser.add_argument('dataset_path', help='LoveDA folder path')
|
| 16 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 17 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
return args
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
args = parse_args()
|
| 24 |
+
dataset_path = args.dataset_path
|
| 25 |
+
if args.out_dir is None:
|
| 26 |
+
out_dir = osp.join('data', 'loveDA')
|
| 27 |
+
else:
|
| 28 |
+
out_dir = args.out_dir
|
| 29 |
+
|
| 30 |
+
print('Making directories...')
|
| 31 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 32 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir'))
|
| 33 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train'))
|
| 34 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val'))
|
| 35 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test'))
|
| 36 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir'))
|
| 37 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train'))
|
| 38 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val'))
|
| 39 |
+
|
| 40 |
+
assert 'Train.zip' in os.listdir(dataset_path), \
|
| 41 |
+
'Train.zip is not in {}'.format(dataset_path)
|
| 42 |
+
assert 'Val.zip' in os.listdir(dataset_path), \
|
| 43 |
+
'Val.zip is not in {}'.format(dataset_path)
|
| 44 |
+
assert 'Test.zip' in os.listdir(dataset_path), \
|
| 45 |
+
'Test.zip is not in {}'.format(dataset_path)
|
| 46 |
+
|
| 47 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 48 |
+
for dataset in ['Train', 'Val', 'Test']:
|
| 49 |
+
zip_file = zipfile.ZipFile(
|
| 50 |
+
os.path.join(dataset_path, dataset + '.zip'))
|
| 51 |
+
zip_file.extractall(tmp_dir)
|
| 52 |
+
data_type = dataset.lower()
|
| 53 |
+
for location in ['Rural', 'Urban']:
|
| 54 |
+
for image_type in ['images_png', 'masks_png']:
|
| 55 |
+
if image_type == 'images_png':
|
| 56 |
+
dst = osp.join(out_dir, 'img_dir', data_type)
|
| 57 |
+
else:
|
| 58 |
+
dst = osp.join(out_dir, 'ann_dir', data_type)
|
| 59 |
+
if dataset == 'Test' and image_type == 'masks_png':
|
| 60 |
+
continue
|
| 61 |
+
else:
|
| 62 |
+
src_dir = osp.join(tmp_dir, dataset, location,
|
| 63 |
+
image_type)
|
| 64 |
+
src_lst = os.listdir(src_dir)
|
| 65 |
+
for file in src_lst:
|
| 66 |
+
shutil.move(osp.join(src_dir, file), dst)
|
| 67 |
+
print('Removing the temporary files...')
|
| 68 |
+
|
| 69 |
+
print('Done!')
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == '__main__':
|
| 73 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/pascal_context.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import os.path as osp
|
| 4 |
+
from functools import partial
|
| 5 |
+
|
| 6 |
+
import mmcv
|
| 7 |
+
import numpy as np
|
| 8 |
+
from detail import Detail
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
_mapping = np.sort(
|
| 12 |
+
np.array([
|
| 13 |
+
0, 2, 259, 260, 415, 324, 9, 258, 144, 18, 19, 22, 23, 397, 25, 284,
|
| 14 |
+
158, 159, 416, 33, 162, 420, 454, 295, 296, 427, 44, 45, 46, 308, 59,
|
| 15 |
+
440, 445, 31, 232, 65, 354, 424, 68, 326, 72, 458, 34, 207, 80, 355,
|
| 16 |
+
85, 347, 220, 349, 360, 98, 187, 104, 105, 366, 189, 368, 113, 115
|
| 17 |
+
]))
|
| 18 |
+
_key = np.array(range(len(_mapping))).astype('uint8')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def generate_labels(img_id, detail, out_dir):
|
| 22 |
+
|
| 23 |
+
def _class_to_index(mask, _mapping, _key):
|
| 24 |
+
# assert the values
|
| 25 |
+
values = np.unique(mask)
|
| 26 |
+
for i in range(len(values)):
|
| 27 |
+
assert (values[i] in _mapping)
|
| 28 |
+
index = np.digitize(mask.ravel(), _mapping, right=True)
|
| 29 |
+
return _key[index].reshape(mask.shape)
|
| 30 |
+
|
| 31 |
+
mask = Image.fromarray(
|
| 32 |
+
_class_to_index(detail.getMask(img_id), _mapping=_mapping, _key=_key))
|
| 33 |
+
filename = img_id['file_name']
|
| 34 |
+
mask.save(osp.join(out_dir, filename.replace('jpg', 'png')))
|
| 35 |
+
return osp.splitext(osp.basename(filename))[0]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def parse_args():
|
| 39 |
+
parser = argparse.ArgumentParser(
|
| 40 |
+
description='Convert PASCAL VOC annotations to mmsegmentation format')
|
| 41 |
+
parser.add_argument('devkit_path', help='pascal voc devkit path')
|
| 42 |
+
parser.add_argument('json_path', help='annoation json filepath')
|
| 43 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 44 |
+
args = parser.parse_args()
|
| 45 |
+
return args
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main():
|
| 49 |
+
args = parse_args()
|
| 50 |
+
devkit_path = args.devkit_path
|
| 51 |
+
if args.out_dir is None:
|
| 52 |
+
out_dir = osp.join(devkit_path, 'VOC2010', 'SegmentationClassContext')
|
| 53 |
+
else:
|
| 54 |
+
out_dir = args.out_dir
|
| 55 |
+
json_path = args.json_path
|
| 56 |
+
mmcv.mkdir_or_exist(out_dir)
|
| 57 |
+
img_dir = osp.join(devkit_path, 'VOC2010', 'JPEGImages')
|
| 58 |
+
|
| 59 |
+
train_detail = Detail(json_path, img_dir, 'train')
|
| 60 |
+
train_ids = train_detail.getImgs()
|
| 61 |
+
|
| 62 |
+
val_detail = Detail(json_path, img_dir, 'val')
|
| 63 |
+
val_ids = val_detail.getImgs()
|
| 64 |
+
|
| 65 |
+
mmcv.mkdir_or_exist(
|
| 66 |
+
osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext'))
|
| 67 |
+
|
| 68 |
+
train_list = mmcv.track_progress(
|
| 69 |
+
partial(generate_labels, detail=train_detail, out_dir=out_dir),
|
| 70 |
+
train_ids)
|
| 71 |
+
with open(
|
| 72 |
+
osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext',
|
| 73 |
+
'train.txt'), 'w') as f:
|
| 74 |
+
f.writelines(line + '\n' for line in sorted(train_list))
|
| 75 |
+
|
| 76 |
+
val_list = mmcv.track_progress(
|
| 77 |
+
partial(generate_labels, detail=val_detail, out_dir=out_dir), val_ids)
|
| 78 |
+
with open(
|
| 79 |
+
osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext',
|
| 80 |
+
'val.txt'), 'w') as f:
|
| 81 |
+
f.writelines(line + '\n' for line in sorted(val_list))
|
| 82 |
+
|
| 83 |
+
print('Done!')
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == '__main__':
|
| 87 |
+
main()
|
EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/potsdam.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import glob
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import os.path as osp
|
| 7 |
+
import tempfile
|
| 8 |
+
import zipfile
|
| 9 |
+
|
| 10 |
+
import mmcv
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description='Convert potsdam dataset to mmsegmentation format')
|
| 17 |
+
parser.add_argument('dataset_path', help='potsdam folder path')
|
| 18 |
+
parser.add_argument('--tmp_dir', help='path of the temporary directory')
|
| 19 |
+
parser.add_argument('-o', '--out_dir', help='output path')
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
'--clip_size',
|
| 22 |
+
type=int,
|
| 23 |
+
help='clipped size of image after preparation',
|
| 24 |
+
default=512)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
'--stride_size',
|
| 27 |
+
type=int,
|
| 28 |
+
help='stride of clipping original images',
|
| 29 |
+
default=256)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
return args
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def clip_big_image(image_path, clip_save_dir, args, to_label=False):
|
| 35 |
+
# Original image of Potsdam dataset is very large, thus pre-processing
|
| 36 |
+
# of them is adopted. Given fixed clip size and stride size to generate
|
| 37 |
+
# clipped image, the intersection of width and height is determined.
|
| 38 |
+
# For example, given one 5120 x 5120 original image, the clip size is
|
| 39 |
+
# 512 and stride size is 256, thus it would generate 20x20 = 400 images
|
| 40 |
+
# whose size are all 512x512.
|
| 41 |
+
image = mmcv.imread(image_path)
|
| 42 |
+
|
| 43 |
+
h, w, c = image.shape
|
| 44 |
+
clip_size = args.clip_size
|
| 45 |
+
stride_size = args.stride_size
|
| 46 |
+
|
| 47 |
+
num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil(
|
| 48 |
+
(h - clip_size) /
|
| 49 |
+
stride_size) * stride_size + clip_size >= h else math.ceil(
|
| 50 |
+
(h - clip_size) / stride_size) + 1
|
| 51 |
+
num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil(
|
| 52 |
+
(w - clip_size) /
|
| 53 |
+
stride_size) * stride_size + clip_size >= w else math.ceil(
|
| 54 |
+
(w - clip_size) / stride_size) + 1
|
| 55 |
+
|
| 56 |
+
x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1))
|
| 57 |
+
xmin = x * clip_size
|
| 58 |
+
ymin = y * clip_size
|
| 59 |
+
|
| 60 |
+
xmin = xmin.ravel()
|
| 61 |
+
ymin = ymin.ravel()
|
| 62 |
+
xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size,
|
| 63 |
+
np.zeros_like(xmin))
|
| 64 |
+
ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size,
|
| 65 |
+
np.zeros_like(ymin))
|
| 66 |
+
boxes = np.stack([
|
| 67 |
+
xmin + xmin_offset, ymin + ymin_offset,
|
| 68 |
+
np.minimum(xmin + clip_size, w),
|
| 69 |
+
np.minimum(ymin + clip_size, h)
|
| 70 |
+
],
|
| 71 |
+
axis=1)
|
| 72 |
+
|
| 73 |
+
if to_label:
|
| 74 |
+
color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0],
|
| 75 |
+
[255, 255, 0], [0, 255, 0], [0, 255, 255],
|
| 76 |
+
[0, 0, 255]])
|
| 77 |
+
flatten_v = np.matmul(
|
| 78 |
+
image.reshape(-1, c),
|
| 79 |
+
np.array([2, 3, 4]).reshape(3, 1))
|
| 80 |
+
out = np.zeros_like(flatten_v)
|
| 81 |
+
for idx, class_color in enumerate(color_map):
|
| 82 |
+
value_idx = np.matmul(class_color,
|
| 83 |
+
np.array([2, 3, 4]).reshape(3, 1))
|
| 84 |
+
out[flatten_v == value_idx] = idx
|
| 85 |
+
image = out.reshape(h, w)
|
| 86 |
+
|
| 87 |
+
for box in boxes:
|
| 88 |
+
start_x, start_y, end_x, end_y = box
|
| 89 |
+
clipped_image = image[start_y:end_y,
|
| 90 |
+
start_x:end_x] if to_label else image[
|
| 91 |
+
start_y:end_y, start_x:end_x, :]
|
| 92 |
+
idx_i, idx_j = osp.basename(image_path).split('_')[2:4]
|
| 93 |
+
mmcv.imwrite(
|
| 94 |
+
clipped_image.astype(np.uint8),
|
| 95 |
+
osp.join(
|
| 96 |
+
clip_save_dir,
|
| 97 |
+
f'{idx_i}_{idx_j}_{start_x}_{start_y}_{end_x}_{end_y}.png'))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def main():
|
| 101 |
+
args = parse_args()
|
| 102 |
+
splits = {
|
| 103 |
+
'train': [
|
| 104 |
+
'2_10', '2_11', '2_12', '3_10', '3_11', '3_12', '4_10', '4_11',
|
| 105 |
+
'4_12', '5_10', '5_11', '5_12', '6_10', '6_11', '6_12', '6_7',
|
| 106 |
+
'6_8', '6_9', '7_10', '7_11', '7_12', '7_7', '7_8', '7_9'
|
| 107 |
+
],
|
| 108 |
+
'val': [
|
| 109 |
+
'5_15', '6_15', '6_13', '3_13', '4_14', '6_14', '5_14', '2_13',
|
| 110 |
+
'4_15', '2_14', '5_13', '4_13', '3_14', '7_13'
|
| 111 |
+
]
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
dataset_path = args.dataset_path
|
| 115 |
+
if args.out_dir is None:
|
| 116 |
+
out_dir = osp.join('data', 'potsdam')
|
| 117 |
+
else:
|
| 118 |
+
out_dir = args.out_dir
|
| 119 |
+
|
| 120 |
+
print('Making directories...')
|
| 121 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train'))
|
| 122 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val'))
|
| 123 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train'))
|
| 124 |
+
mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val'))
|
| 125 |
+
|
| 126 |
+
zipp_list = glob.glob(os.path.join(dataset_path, '*.zip'))
|
| 127 |
+
print('Find the data', zipp_list)
|
| 128 |
+
|
| 129 |
+
for zipp in zipp_list:
|
| 130 |
+
with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
|
| 131 |
+
zip_file = zipfile.ZipFile(zipp)
|
| 132 |
+
zip_file.extractall(tmp_dir)
|
| 133 |
+
src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif'))
|
| 134 |
+
if not len(src_path_list):
|
| 135 |
+
sub_tmp_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0])
|
| 136 |
+
src_path_list = glob.glob(os.path.join(sub_tmp_dir, '*.tif'))
|
| 137 |
+
|
| 138 |
+
prog_bar = mmcv.ProgressBar(len(src_path_list))
|
| 139 |
+
for i, src_path in enumerate(src_path_list):
|
| 140 |
+
idx_i, idx_j = osp.basename(src_path).split('_')[2:4]
|
| 141 |
+
data_type = 'train' if f'{idx_i}_{idx_j}' in splits[
|
| 142 |
+
'train'] else 'val'
|
| 143 |
+
if 'label' in src_path:
|
| 144 |
+
dst_dir = osp.join(out_dir, 'ann_dir', data_type)
|
| 145 |
+
clip_big_image(src_path, dst_dir, args, to_label=True)
|
| 146 |
+
else:
|
| 147 |
+
dst_dir = osp.join(out_dir, 'img_dir', data_type)
|
| 148 |
+
clip_big_image(src_path, dst_dir, args, to_label=False)
|
| 149 |
+
prog_bar.update()
|
| 150 |
+
|
| 151 |
+
print('Removing the temporary files...')
|
| 152 |
+
|
| 153 |
+
print('Done!')
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == '__main__':
|
| 157 |
+
main()
|