diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_lraspp_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_lraspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a46e6a19a221d4d13f5d2d53d368169398e834a0 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_lraspp_head.py @@ -0,0 +1,68 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import LRASPPHead + + +def test_lraspp_head(): + with pytest.raises(ValueError): + # check invalid input_transform + LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + input_transform='resize_concat', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + + with pytest.raises(AssertionError): + # check invalid branch_channels + LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + branch_channels=64, + input_transform='multiple_select', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + + # test with default settings + lraspp_head = LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + input_transform='multiple_select', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + inputs = [ + torch.randn(2, 4, 45, 45), + torch.randn(2, 4, 28, 28), + torch.randn(2, 123, 14, 14) + ] + with pytest.raises(RuntimeError): + # check invalid inputs + output = lraspp_head(inputs) + + inputs = [ + torch.randn(2, 4, 111, 111), + torch.randn(2, 4, 77, 77), + torch.randn(2, 123, 55, 55) + ] + output = lraspp_head(inputs) + assert output.shape == (2, 19, 111, 111) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_nl_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_nl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ef0b9db312b627649f118488ae162c9ef7b197 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_nl_head.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import NLHead +from .utils import to_cuda + + +def test_nl_head(): + head = NLHead(in_channels=8, channels=4, num_classes=19) + assert len(head.convs) == 2 + assert hasattr(head, 'nl_block') + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_ocr_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_ocr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5d669b140b4d4a71addf75e04559eac75c1137 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_ocr_head.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import FCNHead, OCRHead +from .utils import to_cuda + + +def test_ocr_head(): + + inputs = [torch.randn(1, 8, 23, 23)] + ocr_head = OCRHead( + in_channels=8, channels=4, num_classes=19, ocr_channels=8) + fcn_head = FCNHead(in_channels=8, channels=4, num_classes=19) + if torch.cuda.is_available(): + head, inputs = to_cuda(ocr_head, inputs) + head, inputs = to_cuda(fcn_head, inputs) + prev_output = fcn_head(inputs) + output = ocr_head(inputs, prev_output) + assert output.shape == (1, ocr_head.num_classes, 23, 23) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_point_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_point_head.py new file mode 100644 index 0000000000000000000000000000000000000000..142ab16c6c49a1e94099e5eb8297206110a91f49 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_point_head.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.utils import ConfigDict + +from mmseg.models.decode_heads import FCNHead, PointHead +from .utils import to_cuda + + +def test_point_head(): + + inputs = [torch.randn(1, 32, 45, 45)] + point_head = PointHead( + in_channels=[32], in_index=[0], channels=16, num_classes=19) + assert len(point_head.fcs) == 3 + fcn_head = FCNHead(in_channels=32, channels=16, num_classes=19) + if torch.cuda.is_available(): + head, inputs = to_cuda(point_head, inputs) + head, inputs = to_cuda(fcn_head, inputs) + prev_output = fcn_head(inputs) + test_cfg = ConfigDict( + subdivision_steps=2, subdivision_num_points=8196, scale_factor=2) + output = point_head.forward_test(inputs, prev_output, None, test_cfg) + assert output.shape == (1, point_head.num_classes, 180, 180) + + # test multiple losses case + inputs = [torch.randn(1, 32, 45, 45)] + point_head_multiple_losses = PointHead( + in_channels=[32], + in_index=[0], + channels=16, + num_classes=19, + loss_decode=[ + dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2') + ]) + assert len(point_head_multiple_losses.fcs) == 3 + fcn_head_multiple_losses = FCNHead( + in_channels=32, + channels=16, + num_classes=19, + loss_decode=[ + dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2') + ]) + if torch.cuda.is_available(): + head, inputs = to_cuda(point_head_multiple_losses, inputs) + head, inputs = to_cuda(fcn_head_multiple_losses, inputs) + prev_output = fcn_head_multiple_losses(inputs) + test_cfg = ConfigDict( + subdivision_steps=2, subdivision_num_points=8196, scale_factor=2) + output = point_head_multiple_losses.forward_test(inputs, prev_output, None, + test_cfg) + assert output.shape == (1, point_head.num_classes, 180, 180) + + fake_label = torch.ones([1, 180, 180], dtype=torch.long) + + if torch.cuda.is_available(): + fake_label = fake_label.cuda() + loss = point_head_multiple_losses.losses(output, fake_label) + assert 'pointloss_1' in loss + assert 'pointloss_2' in loss diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psa_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..34f592b026293b1e7fa15f6cde103c0c1ae0052c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psa_head.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import PSAHead +from .utils import _conv_has_norm, to_cuda + + +def test_psa_head(): + + with pytest.raises(AssertionError): + # psa_type must be in 'bi-direction', 'collect', 'distribute' + PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='gather') + + # test no norm_cfg + head = PSAHead( + in_channels=4, channels=2, num_classes=19, mask_size=(13, 13)) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + # test 'bi-direction' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, channels=2, num_classes=19, mask_size=(13, 13)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'bi-direction' psa_type, shrink_factor=1 + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + shrink_factor=1) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'bi-direction' psa_type with soft_max + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_softmax=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='collect') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type, shrink_factor=1 + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + shrink_factor=1, + psa_type='collect') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type, shrink_factor=1, compact=True + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='collect', + shrink_factor=1, + compact=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'distribute' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='distribute') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psp_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fde4087c8e4c1f5979c1e5e3247f9633e4798f60 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_psp_head.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import PSPHead +from .utils import _conv_has_norm, to_cuda + + +def test_psp_head(): + + with pytest.raises(AssertionError): + # pool_scales must be list|tuple + PSPHead(in_channels=4, channels=2, num_classes=19, pool_scales=1) + + # test no norm_cfg + head = PSPHead(in_channels=4, channels=2, num_classes=19) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = PSPHead( + in_channels=4, + channels=2, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + inputs = [torch.randn(1, 4, 23, 23)] + head = PSPHead( + in_channels=4, channels=2, num_classes=19, pool_scales=(1, 2, 3)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.psp_modules[0][0].output_size == 1 + assert head.psp_modules[1][0].output_size == 2 + assert head.psp_modules[2][0].output_size == 3 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segformer_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..73afaba2ca7957364e5ebd56cd6e0416655354ec --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segformer_head.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SegformerHead + + +def test_segformer_head(): + with pytest.raises(AssertionError): + # `in_channels` must have same length as `in_index` + SegformerHead( + in_channels=(1, 2, 3), in_index=(0, 1), channels=5, num_classes=2) + + H, W = (64, 64) + in_channels = (32, 64, 160, 256) + shapes = [(H // 2**(i + 2), W // 2**(i + 2)) + for i in range(len(in_channels))] + model = SegformerHead( + in_channels=in_channels, + in_index=[0, 1, 2, 3], + channels=256, + num_classes=19) + + with pytest.raises(IndexError): + # in_index must match the input feature maps. + inputs = [ + torch.randn((1, in_channel, *shape)) + for in_channel, shape in zip(in_channels, shapes) + ][:3] + temp = model(inputs) + + # Normal Input + # ((1, 32, 16, 16), (1, 64, 8, 8), (1, 160, 4, 4), (1, 256, 2, 2) + inputs = [ + torch.randn((1, in_channel, *shape)) + for in_channel, shape in zip(in_channels, shapes) + ] + temp = model(inputs) + + assert temp.shape == (1, 19, H // 4, W // 4) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segmenter_mask_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segmenter_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7b681ac15ce594e9ac641bf307fea77d1928204a --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_segmenter_mask_head.py @@ -0,0 +1,24 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import SegmenterMaskTransformerHead +from .utils import _conv_has_norm, to_cuda + + +def test_segmenter_mask_transformer_head(): + head = SegmenterMaskTransformerHead( + in_channels=2, + channels=2, + num_classes=150, + num_layers=2, + num_heads=3, + embed_dims=192, + dropout_ratio=0.0) + assert _conv_has_norm(head, sync_bn=True) + head.init_weights() + + inputs = [torch.randn(1, 2, 32, 32)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 32, 32) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_mla_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_mla_head.py new file mode 100644 index 0000000000000000000000000000000000000000..301bc0bff4c0bce8751b3cd2cc4cd4b2d7eaac06 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_mla_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SETRMLAHead +from .utils import to_cuda + + +def test_setr_mla_head(capsys): + + with pytest.raises(AssertionError): + # MLA requires input multiple stage feature information. + SETRMLAHead(in_channels=8, channels=4, num_classes=19, in_index=1) + + with pytest.raises(AssertionError): + # multiple in_indexs requires multiple in_channels. + SETRMLAHead( + in_channels=8, channels=4, num_classes=19, in_index=(0, 1, 2, 3)) + + with pytest.raises(AssertionError): + # channels should be len(in_channels) * mla_channels + SETRMLAHead( + in_channels=(8, 8, 8, 8), + channels=8, + mla_channels=4, + in_index=(0, 1, 2, 3), + num_classes=19) + + # test inference of MLA head + img_size = (8, 8) + patch_size = 4 + head = SETRMLAHead( + in_channels=(8, 8, 8, 8), + channels=16, + mla_channels=4, + in_index=(0, 1, 2, 3), + num_classes=19, + norm_cfg=dict(type='BN')) + + h, w = img_size[0] // patch_size, img_size[1] // patch_size + # Input square NCHW format feature information + x = [ + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w) + ] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 4) + + # Input non-square NCHW format feature information + x = [ + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2) + ] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 8) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_up_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_up_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a05192229c7ff216425fae9bd10b75fc8f493873 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_setr_up_head.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SETRUPHead +from .utils import to_cuda + + +def test_setr_up_head(capsys): + + with pytest.raises(AssertionError): + # kernel_size must be [1/3] + SETRUPHead(num_classes=19, kernel_size=2) + + with pytest.raises(AssertionError): + # in_channels must be int type and in_channels must be same + # as embed_dim. + SETRUPHead(in_channels=(4, 4), channels=2, num_classes=19) + + # test init_cfg of head + head = SETRUPHead( + in_channels=4, + channels=2, + norm_cfg=dict(type='SyncBN'), + num_classes=19, + init_cfg=dict(type='Kaiming')) + super(SETRUPHead, head).init_weights() + + # test inference of Naive head + # the auxiliary head of Naive head is same as Naive head + img_size = (4, 4) + patch_size = 2 + head = SETRUPHead( + in_channels=4, + channels=2, + num_classes=19, + num_convs=1, + up_scale=4, + kernel_size=1, + norm_cfg=dict(type='BN')) + + h, w = img_size[0] // patch_size, img_size[1] // patch_size + + # Input square NCHW format feature information + x = [torch.randn(1, 4, h, w)] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 4) + + # Input non-square NCHW format feature information + x = [torch.randn(1, 4, h, w * 2)] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 8) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_stdc_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_stdc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1628209f36a7c71d92c4c495129e5bd0a2d3e5ad --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_stdc_head.py @@ -0,0 +1,31 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import STDCHead +from .utils import to_cuda + + +def test_stdc_head(): + inputs = [torch.randn(1, 32, 21, 21)] + head = STDCHead( + in_channels=32, + channels=8, + num_convs=1, + num_classes=2, + in_index=-1, + loss_decode=[ + dict( + type='CrossEntropyLoss', loss_name='loss_ce', loss_weight=1.0), + dict(type='DiceLoss', loss_name='loss_dice', loss_weight=1.0) + ]) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert isinstance(outputs, torch.Tensor) and len(outputs) == 1 + assert outputs.shape == torch.Size([1, head.num_classes, 21, 21]) + + fake_label = torch.ones_like( + outputs[:, 0:1, :, :], dtype=torch.int16).long() + loss = head.losses(seg_logit=outputs, seg_label=fake_label) + assert loss['loss_ce'] != torch.zeros_like(loss['loss_ce']) + assert loss['loss_dice'] != torch.zeros_like(loss['loss_dice']) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_uper_head.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_uper_head.py new file mode 100644 index 0000000000000000000000000000000000000000..09456a80c4e2a38527a631e8818c2ec9d778f312 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/test_uper_head.py @@ -0,0 +1,35 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import UPerHead +from .utils import _conv_has_norm, to_cuda + + +def test_uper_head(): + + with pytest.raises(AssertionError): + # fpn_in_channels must be list|tuple + UPerHead(in_channels=4, channels=2, num_classes=19) + + # test no norm_cfg + head = UPerHead( + in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1]) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = UPerHead( + in_channels=[4, 2], + channels=2, + num_classes=19, + norm_cfg=dict(type='SyncBN'), + in_index=[-2, -1]) + assert _conv_has_norm(head, sync_bn=True) + + inputs = [torch.randn(1, 4, 45, 45), torch.randn(1, 2, 21, 21)] + head = UPerHead( + in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1]) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/utils.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..675241c21cef916fa09fde23a0894a9db9e7d006 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_heads/utils.py @@ -0,0 +1,22 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import ConvModule +from mmcv.utils.parrots_wrapper import SyncBatchNorm + + +def _conv_has_norm(module, sync_bn): + for m in module.modules(): + if isinstance(m, ConvModule): + if not m.with_norm: + return False + if sync_bn: + if not isinstance(m.bn, SyncBatchNorm): + return False + return True + + +def to_cuda(module, data): + module = module.cuda() + if isinstance(data, list): + for i in range(len(data)): + data[i] = data[i].cuda() + return module, data diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/__init__.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_ce_loss.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_ce_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..afa57064622839865b5b3588dcdff3a0058c4ba6 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_ce_loss.py @@ -0,0 +1,294 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.losses.cross_entropy_loss import _expand_onehot_labels + + +@pytest.mark.parametrize('use_sigmoid', [True, False]) +@pytest.mark.parametrize('reduction', ('mean', 'sum', 'none')) +@pytest.mark.parametrize('avg_non_ignore', [True, False]) +@pytest.mark.parametrize('bce_input_same_dim', [True, False]) +def test_ce_loss(use_sigmoid, reduction, avg_non_ignore, bce_input_same_dim): + from mmseg.models import build_loss + + # use_mask and use_sigmoid cannot be true at the same time + with pytest.raises(AssertionError): + loss_cfg = dict( + type='CrossEntropyLoss', + use_mask=True, + use_sigmoid=True, + loss_weight=1.0) + build_loss(loss_cfg) + + # test loss with simple case for ce/bce + fake_pred = torch.Tensor([[100, -100]]) + fake_label = torch.Tensor([1]).long() + loss_cls_cfg = dict( + type='CrossEntropyLoss', + use_sigmoid=use_sigmoid, + loss_weight=1.0, + avg_non_ignore=avg_non_ignore, + loss_name='loss_ce') + loss_cls = build_loss(loss_cls_cfg) + if use_sigmoid: + assert torch.allclose( + loss_cls(fake_pred, fake_label), torch.tensor(100.)) + else: + assert torch.allclose( + loss_cls(fake_pred, fake_label), torch.tensor(200.)) + + # test loss with complicated case for ce/bce + # when avg_non_ignore is False, `avg_factor` would not be calculated + fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5) + fake_label = torch.ones(2, 8, 8).long() + fake_label[:, 0, 0] = 255 + fake_weight = None + # extra test bce loss when pred.shape == label.shape + if use_sigmoid and bce_input_same_dim: + fake_pred = torch.randn(2, 10).float() + fake_label = torch.rand(2, 10).float() + fake_weight = torch.rand(2, 10) # set weight in forward function + fake_label[0, [1, 2, 5, 7]] = 255 # set ignore_index + fake_label[1, [0, 5, 8, 9]] = 255 + loss_cls = build_loss(loss_cls_cfg) + loss = loss_cls( + fake_pred, fake_label, weight=fake_weight, ignore_index=255) + if use_sigmoid: + if fake_pred.dim() != fake_label.dim(): + fake_label, weight, valid_mask = _expand_onehot_labels( + labels=fake_label, + label_weights=None, + target_shape=fake_pred.shape, + ignore_index=255) + else: + # should mask out the ignored elements + valid_mask = ((fake_label >= 0) & (fake_label != 255)).float() + weight = valid_mask + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred, + fake_label.float(), + reduction='none', + weight=fake_weight) + if avg_non_ignore: + avg_factor = valid_mask.sum().item() + torch_loss = (torch_loss * weight).sum() / avg_factor + else: + torch_loss = (torch_loss * weight).mean() + else: + if avg_non_ignore: + torch_loss = torch.nn.functional.cross_entropy( + fake_pred, fake_label, reduction='mean', ignore_index=255) + else: + torch_loss = torch.nn.functional.cross_entropy( + fake_pred, fake_label, reduction='sum', + ignore_index=255) / fake_label.numel() + assert torch.allclose(loss, torch_loss) + + if use_sigmoid: + # test loss with complicated case for ce/bce + # when avg_non_ignore is False, `avg_factor` would not be calculated + fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5) + fake_label = torch.ones(2, 8, 8).long() + fake_label[:, 0, 0] = 255 + fake_weight = torch.rand(2, 8, 8) + + loss_cls = build_loss(loss_cls_cfg) + loss = loss_cls( + fake_pred, fake_label, weight=fake_weight, ignore_index=255) + if use_sigmoid: + fake_label, weight, valid_mask = _expand_onehot_labels( + labels=fake_label, + label_weights=None, + target_shape=fake_pred.shape, + ignore_index=255) + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred, + fake_label.float(), + reduction='none', + weight=fake_weight.unsqueeze(1).expand(fake_pred.shape)) + if avg_non_ignore: + avg_factor = valid_mask.sum().item() + torch_loss = (torch_loss * weight).sum() / avg_factor + else: + torch_loss = (torch_loss * weight).mean() + assert torch.allclose(loss, torch_loss) + + # test loss with class weights from file + fake_pred = torch.Tensor([[100, -100]]) + fake_label = torch.Tensor([1]).long() + import os + import tempfile + + import mmcv + import numpy as np + tmp_file = tempfile.NamedTemporaryFile() + + mmcv.dump([0.8, 0.2], f'{tmp_file.name}.pkl', 'pkl') # from pkl file + loss_cls_cfg = dict( + type='CrossEntropyLoss', + use_sigmoid=False, + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + loss_name='loss_ce') + loss_cls = build_loss(loss_cls_cfg) + assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(40.)) + + np.save(f'{tmp_file.name}.npy', np.array([0.8, 0.2])) # from npy file + loss_cls_cfg = dict( + type='CrossEntropyLoss', + use_sigmoid=False, + class_weight=f'{tmp_file.name}.npy', + loss_weight=1.0, + loss_name='loss_ce') + loss_cls = build_loss(loss_cls_cfg) + assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(40.)) + tmp_file.close() + os.remove(f'{tmp_file.name}.pkl') + os.remove(f'{tmp_file.name}.npy') + + loss_cls_cfg = dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0) + loss_cls = build_loss(loss_cls_cfg) + assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(200.)) + + # test `avg_non_ignore` without ignore index would not affect ce/bce loss + # when reduction='sum'/'none'/'mean' + loss_cls_cfg1 = dict( + type='CrossEntropyLoss', + use_sigmoid=use_sigmoid, + reduction=reduction, + loss_weight=1.0, + avg_non_ignore=True) + loss_cls1 = build_loss(loss_cls_cfg1) + loss_cls_cfg2 = dict( + type='CrossEntropyLoss', + use_sigmoid=use_sigmoid, + reduction=reduction, + loss_weight=1.0, + avg_non_ignore=False) + loss_cls2 = build_loss(loss_cls_cfg2) + assert torch.allclose( + loss_cls1(fake_pred, fake_label, ignore_index=255) / fake_pred.numel(), + loss_cls2(fake_pred, fake_label, ignore_index=255) / fake_pred.numel(), + atol=1e-4) + + # test ce/bce loss with ignore index and class weight + # in 5-way classification + if use_sigmoid: + # test bce loss when pred.shape == or != label.shape + if bce_input_same_dim: + fake_pred = torch.randn(2, 10).float() + fake_label = torch.rand(2, 10).float() + class_weight = torch.rand(2, 10) + else: + fake_pred = torch.full(size=(2, 21, 8, 8), fill_value=0.5) + fake_label = torch.ones(2, 8, 8).long() + class_weight = torch.randn(2, 21, 8, 8) + fake_label, weight, valid_mask = _expand_onehot_labels( + labels=fake_label, + label_weights=None, + target_shape=fake_pred.shape, + ignore_index=-100) + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred, + fake_label.float(), + reduction='mean', + pos_weight=class_weight) + else: + fake_pred = torch.randn(2, 5, 10).float() # 5-way classification + fake_label = torch.randint(0, 5, (2, 10)).long() + class_weight = torch.rand(5) + class_weight /= class_weight.sum() + torch_loss = torch.nn.functional.cross_entropy( + fake_pred, fake_label, reduction='sum', + weight=class_weight) / fake_label.numel() + loss_cls_cfg = dict( + type='CrossEntropyLoss', + use_sigmoid=use_sigmoid, + reduction='mean', + class_weight=class_weight, + loss_weight=1.0, + avg_non_ignore=avg_non_ignore) + loss_cls = build_loss(loss_cls_cfg) + + # test cross entropy loss has name `loss_ce` + assert loss_cls.loss_name == 'loss_ce' + # test avg_non_ignore is in extra_repr + assert loss_cls.extra_repr() == f'avg_non_ignore={avg_non_ignore}' + + loss = loss_cls(fake_pred, fake_label) + assert torch.allclose(loss, torch_loss) + + fake_label[0, [1, 2, 5, 7]] = 10 # set ignore_index + fake_label[1, [0, 5, 8, 9]] = 10 + loss = loss_cls(fake_pred, fake_label, ignore_index=10) + if use_sigmoid: + if avg_non_ignore: + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred[fake_label != 10], + fake_label[fake_label != 10].float(), + pos_weight=class_weight[fake_label != 10], + reduction='mean') + else: + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred[fake_label != 10], + fake_label[fake_label != 10].float(), + pos_weight=class_weight[fake_label != 10], + reduction='sum') / fake_label.numel() + else: + if avg_non_ignore: + torch_loss = torch.nn.functional.cross_entropy( + fake_pred, + fake_label, + ignore_index=10, + reduction='sum', + weight=class_weight) / fake_label[fake_label != 10].numel() + else: + torch_loss = torch.nn.functional.cross_entropy( + fake_pred, + fake_label, + ignore_index=10, + reduction='sum', + weight=class_weight) / fake_label.numel() + assert torch.allclose(loss, torch_loss) + + +@pytest.mark.parametrize('avg_non_ignore', [True, False]) +@pytest.mark.parametrize('with_weight', [True, False]) +def test_binary_class_ce_loss(avg_non_ignore, with_weight): + from mmseg.models import build_loss + + fake_pred = torch.rand(3, 1, 10, 10) + fake_label = torch.randint(0, 2, (3, 10, 10)) + fake_weight = torch.rand(3, 10, 10) + valid_mask = ((fake_label >= 0) & (fake_label != 255)).float() + weight = valid_mask + + torch_loss = torch.nn.functional.binary_cross_entropy_with_logits( + fake_pred, + fake_label.unsqueeze(1).float(), + reduction='none', + weight=fake_weight.unsqueeze(1).float() if with_weight else None) + if avg_non_ignore: + eps = torch.finfo(torch.float32).eps + avg_factor = valid_mask.sum().item() + torch_loss = (torch_loss * weight.unsqueeze(1)).sum() / ( + avg_factor + eps) + else: + torch_loss = (torch_loss * weight.unsqueeze(1)).mean() + + loss_cls_cfg = dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=1.0, + avg_non_ignore=avg_non_ignore, + reduction='mean', + loss_name='loss_ce') + loss_cls = build_loss(loss_cls_cfg) + loss = loss_cls( + fake_pred, + fake_label, + weight=fake_weight if with_weight else None, + ignore_index=255) + assert torch.allclose(loss, torch_loss) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_dice_loss.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_dice_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..3936f5d74154cdd9e174d58f0efbf1b8df4663ea --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_dice_loss.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + + +def test_dice_lose(): + from mmseg.models import build_loss + + # test dice loss with loss_type = 'multi_class' + loss_cfg = dict( + type='DiceLoss', + reduction='none', + class_weight=[1.0, 2.0, 3.0], + loss_weight=1.0, + ignore_index=1, + loss_name='loss_dice') + dice_loss = build_loss(loss_cfg) + logits = torch.rand(8, 3, 4, 4) + labels = (torch.rand(8, 4, 4) * 3).long() + dice_loss(logits, labels) + + # test loss with class weights from file + import os + import tempfile + + import mmcv + import numpy as np + tmp_file = tempfile.NamedTemporaryFile() + + mmcv.dump([1.0, 2.0, 3.0], f'{tmp_file.name}.pkl', 'pkl') # from pkl file + loss_cfg = dict( + type='DiceLoss', + reduction='none', + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + ignore_index=1, + loss_name='loss_dice') + dice_loss = build_loss(loss_cfg) + dice_loss(logits, labels, ignore_index=None) + + np.save(f'{tmp_file.name}.npy', np.array([1.0, 2.0, 3.0])) # from npy file + loss_cfg = dict( + type='DiceLoss', + reduction='none', + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + ignore_index=1, + loss_name='loss_dice') + dice_loss = build_loss(loss_cfg) + dice_loss(logits, labels, ignore_index=None) + tmp_file.close() + os.remove(f'{tmp_file.name}.pkl') + os.remove(f'{tmp_file.name}.npy') + + # test dice loss with loss_type = 'binary' + loss_cfg = dict( + type='DiceLoss', + smooth=2, + exponent=3, + reduction='sum', + loss_weight=1.0, + ignore_index=0, + loss_name='loss_dice') + dice_loss = build_loss(loss_cfg) + logits = torch.rand(8, 2, 4, 4) + labels = (torch.rand(8, 4, 4) * 2).long() + dice_loss(logits, labels) + + # test dice loss has name `loss_dice` + loss_cfg = dict( + type='DiceLoss', + smooth=2, + exponent=3, + reduction='sum', + loss_weight=1.0, + ignore_index=0, + loss_name='loss_dice') + dice_loss = build_loss(loss_cfg) + assert dice_loss.loss_name == 'loss_dice' diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_focal_loss.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..687312b94b936cc370d5e52b9455ec759d574aee --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_focal_loss.py @@ -0,0 +1,216 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +import torch.nn.functional as F + +from mmseg.models import build_loss + + +# test focal loss with use_sigmoid=False +def test_use_sigmoid(): + # can't init with use_sigmoid=True + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', use_sigmoid=False) + build_loss(loss_cfg) + + # can't forward with use_sigmoid=True + with pytest.raises(NotImplementedError): + loss_cfg = dict(type='FocalLoss', use_sigmoid=True) + focal_loss = build_loss(loss_cfg) + focal_loss.use_sigmoid = False + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + focal_loss(fake_pred, fake_target) + + +# reduction type must be 'none', 'mean' or 'sum' +def test_wrong_reduction_type(): + # can't init with wrong reduction + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', reduction='test') + build_loss(loss_cfg) + + # can't forward with wrong reduction override + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss') + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + focal_loss(fake_pred, fake_target, reduction_override='test') + + +# test focal loss can handle input parameters with +# unacceptable types +def test_unacceptable_parameters(): + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', gamma='test') + build_loss(loss_cfg) + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', alpha='test') + build_loss(loss_cfg) + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', class_weight='test') + build_loss(loss_cfg) + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', loss_weight='test') + build_loss(loss_cfg) + with pytest.raises(AssertionError): + loss_cfg = dict(type='FocalLoss', loss_name=123) + build_loss(loss_cfg) + + +# test if focal loss can be correctly initialize +def test_init_focal_loss(): + loss_cfg = dict( + type='FocalLoss', + use_sigmoid=True, + gamma=3.0, + alpha=3.0, + class_weight=[1, 2, 3, 4], + reduction='sum') + focal_loss = build_loss(loss_cfg) + assert focal_loss.use_sigmoid is True + assert focal_loss.gamma == 3.0 + assert focal_loss.alpha == 3.0 + assert focal_loss.reduction == 'sum' + assert focal_loss.class_weight == [1, 2, 3, 4] + assert focal_loss.loss_weight == 1.0 + assert focal_loss.loss_name == 'loss_focal' + + +# test reduction override +def test_reduction_override(): + loss_cfg = dict(type='FocalLoss', reduction='mean') + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + loss = focal_loss(fake_pred, fake_target, reduction_override='none') + assert loss.shape == fake_pred.shape + + +# test wrong pred and target shape +def test_wrong_pred_and_target_shape(): + loss_cfg = dict(type='FocalLoss') + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 2, 2)) + fake_target = F.one_hot(fake_target, num_classes=4) + fake_target = fake_target.permute(0, 3, 1, 2) + with pytest.raises(AssertionError): + focal_loss(fake_pred, fake_target) + + +# test forward with different shape of target +def test_forward_with_different_shape_of_target(): + loss_cfg = dict(type='FocalLoss') + focal_loss = build_loss(loss_cfg) + + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + loss1 = focal_loss(fake_pred, fake_target) + + fake_target = F.one_hot(fake_target, num_classes=4) + fake_target = fake_target.permute(0, 3, 1, 2) + loss2 = focal_loss(fake_pred, fake_target) + assert loss1 == loss2 + + +# test forward with weight +def test_forward_with_weight(): + loss_cfg = dict(type='FocalLoss') + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + weight = torch.rand(3 * 5 * 6, 1) + loss1 = focal_loss(fake_pred, fake_target, weight=weight) + + weight2 = weight.view(-1) + loss2 = focal_loss(fake_pred, fake_target, weight=weight2) + + weight3 = weight.expand(3 * 5 * 6, 4) + loss3 = focal_loss(fake_pred, fake_target, weight=weight3) + assert loss1 == loss2 == loss3 + + +# test none reduction type +def test_none_reduction_type(): + loss_cfg = dict(type='FocalLoss', reduction='none') + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + loss = focal_loss(fake_pred, fake_target) + assert loss.shape == fake_pred.shape + + +# test the usage of class weight +def test_class_weight(): + loss_cfg_cw = dict( + type='FocalLoss', reduction='none', class_weight=[1.0, 2.0, 3.0, 4.0]) + loss_cfg = dict(type='FocalLoss', reduction='none') + focal_loss_cw = build_loss(loss_cfg_cw) + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + loss_cw = focal_loss_cw(fake_pred, fake_target) + loss = focal_loss(fake_pred, fake_target) + weight = torch.tensor([1, 2, 3, 4]).view(1, 4, 1, 1) + assert (loss * weight == loss_cw).all() + + +# test ignore index +def test_ignore_index(): + loss_cfg = dict(type='FocalLoss', reduction='none') + # ignore_index within C classes + focal_loss = build_loss(loss_cfg) + fake_pred = torch.rand(3, 5, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + dim1 = torch.randint(0, 3, (4, )) + dim2 = torch.randint(0, 5, (4, )) + dim3 = torch.randint(0, 6, (4, )) + fake_target[dim1, dim2, dim3] = 4 + loss1 = focal_loss(fake_pred, fake_target, ignore_index=4) + one_hot_target = F.one_hot(fake_target, num_classes=5) + one_hot_target = one_hot_target.permute(0, 3, 1, 2) + loss2 = focal_loss(fake_pred, one_hot_target, ignore_index=4) + assert (loss1 == loss2).all() + assert (loss1[dim1, :, dim2, dim3] == 0).all() + assert (loss2[dim1, :, dim2, dim3] == 0).all() + + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + loss1 = focal_loss(fake_pred, fake_target, ignore_index=2) + one_hot_target = F.one_hot(fake_target, num_classes=4) + one_hot_target = one_hot_target.permute(0, 3, 1, 2) + loss2 = focal_loss(fake_pred, one_hot_target, ignore_index=2) + ignore_mask = one_hot_target == 2 + assert (loss1 == loss2).all() + assert torch.sum(loss1 * ignore_mask) == 0 + assert torch.sum(loss2 * ignore_mask) == 0 + + # ignore index is not in prediction's classes + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + dim1 = torch.randint(0, 3, (4, )) + dim2 = torch.randint(0, 5, (4, )) + dim3 = torch.randint(0, 6, (4, )) + fake_target[dim1, dim2, dim3] = 255 + loss1 = focal_loss(fake_pred, fake_target, ignore_index=255) + assert (loss1[dim1, :, dim2, dim3] == 0).all() + + +# test list alpha +def test_alpha(): + loss_cfg = dict(type='FocalLoss') + focal_loss = build_loss(loss_cfg) + alpha_float = 0.4 + alpha = [0.4, 0.4, 0.4, 0.4] + alpha2 = [0.1, 0.3, 0.2, 0.1] + fake_pred = torch.rand(3, 4, 5, 6) + fake_target = torch.randint(0, 4, (3, 5, 6)) + focal_loss.alpha = alpha_float + loss1 = focal_loss(fake_pred, fake_target) + focal_loss.alpha = alpha + loss2 = focal_loss(fake_pred, fake_target) + assert loss1 == loss2 + focal_loss.alpha = alpha2 + focal_loss(fake_pred, fake_target) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_lovasz_loss.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_lovasz_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bea3f4b77f4499052aa5d408a19ab7d94d73f848 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_lovasz_loss.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + + +def test_lovasz_loss(): + from mmseg.models import build_loss + + # loss_type should be 'binary' or 'multi_class' + with pytest.raises(AssertionError): + loss_cfg = dict( + type='LovaszLoss', + loss_type='Binary', + reduction='none', + loss_weight=1.0, + loss_name='loss_lovasz') + build_loss(loss_cfg) + + # reduction should be 'none' when per_image is False. + with pytest.raises(AssertionError): + loss_cfg = dict( + type='LovaszLoss', + loss_type='multi_class', + loss_name='loss_lovasz') + build_loss(loss_cfg) + + # test lovasz loss with loss_type = 'multi_class' and per_image = False + loss_cfg = dict( + type='LovaszLoss', + reduction='none', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + logits = torch.rand(1, 3, 4, 4) + labels = (torch.rand(1, 4, 4) * 2).long() + lovasz_loss(logits, labels) + + # test lovasz loss with loss_type = 'multi_class' and per_image = True + loss_cfg = dict( + type='LovaszLoss', + per_image=True, + reduction='mean', + class_weight=[1.0, 2.0, 3.0], + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + logits = torch.rand(1, 3, 4, 4) + labels = (torch.rand(1, 4, 4) * 2).long() + lovasz_loss(logits, labels, ignore_index=None) + + # test loss with class weights from file + import os + import tempfile + + import mmcv + import numpy as np + tmp_file = tempfile.NamedTemporaryFile() + + mmcv.dump([1.0, 2.0, 3.0], f'{tmp_file.name}.pkl', 'pkl') # from pkl file + loss_cfg = dict( + type='LovaszLoss', + per_image=True, + reduction='mean', + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + lovasz_loss(logits, labels, ignore_index=None) + + np.save(f'{tmp_file.name}.npy', np.array([1.0, 2.0, 3.0])) # from npy file + loss_cfg = dict( + type='LovaszLoss', + per_image=True, + reduction='mean', + class_weight=f'{tmp_file.name}.npy', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + lovasz_loss(logits, labels, ignore_index=None) + tmp_file.close() + os.remove(f'{tmp_file.name}.pkl') + os.remove(f'{tmp_file.name}.npy') + + # test lovasz loss with loss_type = 'binary' and per_image = False + loss_cfg = dict( + type='LovaszLoss', + loss_type='binary', + reduction='none', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + logits = torch.rand(2, 4, 4) + labels = (torch.rand(2, 4, 4)).long() + lovasz_loss(logits, labels) + + # test lovasz loss with loss_type = 'binary' and per_image = True + loss_cfg = dict( + type='LovaszLoss', + loss_type='binary', + per_image=True, + reduction='mean', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + logits = torch.rand(2, 4, 4) + labels = (torch.rand(2, 4, 4)).long() + lovasz_loss(logits, labels, ignore_index=None) + + # test lovasz loss has name `loss_lovasz` + loss_cfg = dict( + type='LovaszLoss', + loss_type='binary', + per_image=True, + reduction='mean', + loss_weight=1.0, + loss_name='loss_lovasz') + lovasz_loss = build_loss(loss_cfg) + assert lovasz_loss.loss_name == 'loss_lovasz' diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_utils.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9927fe1cfde0ad3916bd84fd4a6884caeb05ff --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_losses/test_utils.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import pytest +import torch + +from mmseg.models.losses import Accuracy, reduce_loss, weight_reduce_loss + + +def test_weight_reduce_loss(): + loss = torch.rand(1, 3, 4, 4) + weight = torch.zeros(1, 3, 4, 4) + weight[:, :, :2, :2] = 1 + + # test reduce_loss() + reduced = reduce_loss(loss, 'none') + assert reduced is loss + + reduced = reduce_loss(loss, 'mean') + np.testing.assert_almost_equal(reduced.numpy(), loss.mean()) + + reduced = reduce_loss(loss, 'sum') + np.testing.assert_almost_equal(reduced.numpy(), loss.sum()) + + # test weight_reduce_loss() + reduced = weight_reduce_loss(loss, weight=None, reduction='none') + assert reduced is loss + + reduced = weight_reduce_loss(loss, weight=weight, reduction='mean') + target = (loss * weight).mean() + np.testing.assert_almost_equal(reduced.numpy(), target) + + reduced = weight_reduce_loss(loss, weight=weight, reduction='sum') + np.testing.assert_almost_equal(reduced.numpy(), (loss * weight).sum()) + + with pytest.raises(AssertionError): + weight_wrong = weight[0, 0, ...] + weight_reduce_loss(loss, weight=weight_wrong, reduction='mean') + + with pytest.raises(AssertionError): + weight_wrong = weight[:, 0:2, ...] + weight_reduce_loss(loss, weight=weight_wrong, reduction='mean') + + +def test_accuracy(): + # test for empty pred + pred = torch.empty(0, 4) + label = torch.empty(0) + accuracy = Accuracy(topk=1) + acc = accuracy(pred, label) + assert acc.item() == 0 + + pred = torch.Tensor([[0.2, 0.3, 0.6, 0.5], [0.1, 0.1, 0.2, 0.6], + [0.9, 0.0, 0.0, 0.1], [0.4, 0.7, 0.1, 0.1], + [0.0, 0.0, 0.99, 0]]) + # test for ignore_index + true_label = torch.Tensor([2, 3, 0, 1, 2]).long() + accuracy = Accuracy(topk=1, ignore_index=None) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(100.0)) + + # test for ignore_index with a wrong prediction of that index + true_label = torch.Tensor([2, 3, 1, 1, 2]).long() + accuracy = Accuracy(topk=1, ignore_index=1) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(100.0)) + + # test for ignore_index 1 with a wrong prediction of other index + true_label = torch.Tensor([2, 0, 0, 1, 2]).long() + accuracy = Accuracy(topk=1, ignore_index=1) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(75.0)) + + # test for ignore_index 4 with a wrong prediction of other index + true_label = torch.Tensor([2, 0, 0, 1, 2]).long() + accuracy = Accuracy(topk=1, ignore_index=4) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(80.0)) + + # test for ignoring all the pixels + true_label = torch.Tensor([2, 2, 2, 2, 2]).long() + accuracy = Accuracy(topk=1, ignore_index=2) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(100.0)) + + # test for top1 + true_label = torch.Tensor([2, 3, 0, 1, 2]).long() + accuracy = Accuracy(topk=1) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(100.0)) + + # test for top1 with score thresh=0.8 + true_label = torch.Tensor([2, 3, 0, 1, 2]).long() + accuracy = Accuracy(topk=1, thresh=0.8) + acc = accuracy(pred, true_label) + assert torch.allclose(acc, torch.tensor(40.0)) + + # test for top2 + accuracy = Accuracy(topk=2) + label = torch.Tensor([3, 2, 0, 0, 2]).long() + acc = accuracy(pred, label) + assert torch.allclose(acc, torch.tensor(100.0)) + + # test for both top1 and top2 + accuracy = Accuracy(topk=(1, 2)) + true_label = torch.Tensor([2, 3, 0, 1, 2]).long() + acc = accuracy(pred, true_label) + for a in acc: + assert torch.allclose(a, torch.tensor(100.0)) + + # topk is larger than pred class number + with pytest.raises(AssertionError): + accuracy = Accuracy(topk=5) + accuracy(pred, true_label) + + # wrong topk type + with pytest.raises(AssertionError): + accuracy = Accuracy(topk='wrong type') + accuracy(pred, true_label) + + # label size is larger than required + with pytest.raises(AssertionError): + label = torch.Tensor([2, 3, 0, 1, 2, 0]).long() # size mismatch + accuracy = Accuracy() + accuracy(pred, label) + + # wrong pred dimension + with pytest.raises(AssertionError): + accuracy = Accuracy() + accuracy(pred[:, :, None], true_label) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/__init__.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_feature2pyramid.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_feature2pyramid.py new file mode 100644 index 0000000000000000000000000000000000000000..44fd02c489152846b17f7d46abd8064a771e6493 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_feature2pyramid.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models import Feature2Pyramid + + +def test_feature2pyramid(): + # test + rescales = [4, 2, 1, 0.5] + embed_dim = 64 + inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))] + + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 128, 128]) + assert outputs[1].shape == torch.Size([1, 64, 64, 64]) + assert outputs[2].shape == torch.Size([1, 64, 32, 32]) + assert outputs[3].shape == torch.Size([1, 64, 16, 16]) + + # test rescales = [2, 1, 0.5, 0.25] + rescales = [2, 1, 0.5, 0.25] + inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))] + + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 64, 64]) + assert outputs[1].shape == torch.Size([1, 64, 32, 32]) + assert outputs[2].shape == torch.Size([1, 64, 16, 16]) + assert outputs[3].shape == torch.Size([1, 64, 8, 8]) + + # test rescales = [4, 2, 0.25, 0] + rescales = [4, 2, 0.25, 0] + with pytest.raises(KeyError): + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_fpn.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..c29400602d55319621fbff5423196131200929d9 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_fpn.py @@ -0,0 +1,30 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import FPN + + +def test_fpn(): + in_channels = [64, 128, 256, 512] + inputs = [ + torch.randn(1, c, 56 // 2**i, 56 // 2**i) + for i, c in enumerate(in_channels) + ] + + fpn = FPN(in_channels, 64, len(in_channels)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 56, 56]) + assert outputs[1].shape == torch.Size([1, 64, 28, 28]) + assert outputs[2].shape == torch.Size([1, 64, 14, 14]) + assert outputs[3].shape == torch.Size([1, 64, 7, 7]) + + fpn = FPN( + in_channels, + 64, + len(in_channels), + upsample_cfg=dict(mode='nearest', scale_factor=2.0)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 56, 56]) + assert outputs[1].shape == torch.Size([1, 64, 28, 28]) + assert outputs[2].shape == torch.Size([1, 64, 14, 14]) + assert outputs[3].shape == torch.Size([1, 64, 7, 7]) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_ic_neck.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_ic_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..3d13008b5fbf1899acf86dfd42a704bf39c7124e --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_ic_neck.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.necks import ICNeck +from mmseg.models.necks.ic_neck import CascadeFeatureFusion +from ..test_heads.utils import _conv_has_norm, to_cuda + + +def test_ic_neck(): + # test with norm_cfg + neck = ICNeck( + in_channels=(4, 16, 16), + out_channels=8, + norm_cfg=dict(type='SyncBN'), + align_corners=False) + assert _conv_has_norm(neck, sync_bn=True) + + inputs = [ + torch.randn(1, 4, 32, 64), + torch.randn(1, 16, 16, 32), + torch.randn(1, 16, 8, 16) + ] + neck = ICNeck( + in_channels=(4, 16, 16), + out_channels=4, + norm_cfg=dict(type='BN', requires_grad=True), + align_corners=False) + if torch.cuda.is_available(): + neck, inputs = to_cuda(neck, inputs) + + outputs = neck(inputs) + assert outputs[0].shape == (1, 4, 16, 32) + assert outputs[1].shape == (1, 4, 32, 64) + assert outputs[1].shape == (1, 4, 32, 64) + + +def test_ic_neck_cascade_feature_fusion(): + cff = CascadeFeatureFusion(64, 64, 32) + assert cff.conv_low.in_channels == 64 + assert cff.conv_low.out_channels == 32 + assert cff.conv_high.in_channels == 64 + assert cff.conv_high.out_channels == 32 + + +def test_ic_neck_input_channels(): + with pytest.raises(AssertionError): + # ICNet Neck input channel constraints. + ICNeck( + in_channels=(16, 64, 64, 64), + out_channels=32, + norm_cfg=dict(type='BN', requires_grad=True), + align_corners=False) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_jpu.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_jpu.py new file mode 100644 index 0000000000000000000000000000000000000000..4c3fa9f6bb8ca6f965f4b34bcbb43ceb7996c67b --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_jpu.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.necks import JPU + + +def test_fastfcn_neck(): + # Test FastFCN Standard Forward + model = JPU( + in_channels=(64, 128, 256), + mid_channels=64, + start_level=0, + end_level=-1, + dilations=(1, 2, 4, 8), + ) + model.init_weights() + model.train() + batch_size = 1 + input = [ + torch.randn(batch_size, 64, 64, 128), + torch.randn(batch_size, 128, 32, 64), + torch.randn(batch_size, 256, 16, 32) + ] + feat = model(input) + + assert len(feat) == 3 + assert feat[0].shape == torch.Size([batch_size, 64, 64, 128]) + assert feat[1].shape == torch.Size([batch_size, 128, 32, 64]) + assert feat[2].shape == torch.Size([batch_size, 256, 64, 128]) + + with pytest.raises(AssertionError): + # FastFCN input and in_channels constraints. + JPU(in_channels=(256, 64, 128), start_level=0, end_level=5) + + # Test not default start_level + model = JPU(in_channels=(64, 128, 256), start_level=1, end_level=-1) + input = [ + torch.randn(batch_size, 64, 64, 128), + torch.randn(batch_size, 128, 32, 64), + torch.randn(batch_size, 256, 16, 32) + ] + feat = model(input) + assert len(feat) == 2 + assert feat[0].shape == torch.Size([batch_size, 128, 32, 64]) + assert feat[1].shape == torch.Size([batch_size, 2048, 32, 64]) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_mla_neck.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_mla_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..e385418949aad1e5016670b485cc10725ab69e93 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_mla_neck.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import MLANeck + + +def test_mla(): + in_channels = [4, 4, 4, 4] + mla = MLANeck(in_channels, 32) + + inputs = [torch.randn(1, c, 12, 12) for i, c in enumerate(in_channels)] + outputs = mla(inputs) + assert outputs[0].shape == torch.Size([1, 32, 12, 12]) + assert outputs[1].shape == torch.Size([1, 32, 12, 12]) + assert outputs[2].shape == torch.Size([1, 32, 12, 12]) + assert outputs[3].shape == torch.Size([1, 32, 12, 12]) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_multilevel_neck.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_multilevel_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..9c71d51563ffc1f0c7a1d14c3e6e7171f42440e7 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_necks/test_multilevel_neck.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import MultiLevelNeck + + +def test_multilevel_neck(): + + # Test init_weights + MultiLevelNeck([266], 32).init_weights() + + # Test multi feature maps + in_channels = [32, 64, 128, 256] + inputs = [torch.randn(1, c, 14, 14) for i, c in enumerate(in_channels)] + + neck = MultiLevelNeck(in_channels, 32) + outputs = neck(inputs) + assert outputs[0].shape == torch.Size([1, 32, 7, 7]) + assert outputs[1].shape == torch.Size([1, 32, 14, 14]) + assert outputs[2].shape == torch.Size([1, 32, 28, 28]) + assert outputs[3].shape == torch.Size([1, 32, 56, 56]) + + # Test one feature map + in_channels = [768] + inputs = [torch.randn(1, 768, 14, 14)] + + neck = MultiLevelNeck(in_channels, 32) + outputs = neck(inputs) + assert outputs[0].shape == torch.Size([1, 32, 7, 7]) + assert outputs[1].shape == torch.Size([1, 32, 14, 14]) + assert outputs[2].shape == torch.Size([1, 32, 28, 28]) + assert outputs[3].shape == torch.Size([1, 32, 56, 56]) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/__init__.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..07ad5c3fbbdfb0a4cd29178944c497873d021331 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv import ConfigDict + +from mmseg.models import build_segmentor +from .utils import _segmentor_forward_train_test + + +def test_cascade_encoder_decoder(): + + # test 1 decode head, w.o. aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test slide mode + cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2)) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 1 aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ], + auxiliary_head=dict(type='ExampleDecodeHead')) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 2 aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ], + auxiliary_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_encoder_decoder.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed143727dd303ca3816781cce3fecdff56bf8ff --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/test_encoder_decoder.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv import ConfigDict + +from mmseg.models import build_segmentor +from .utils import _segmentor_forward_train_test + + +def test_encoder_decoder(): + + # test 1 decode head, w.o. aux head + + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + train_cfg=None, + test_cfg=dict(mode='whole')) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test slide mode + cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2)) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 1 aux head + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + auxiliary_head=dict(type='ExampleDecodeHead')) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 2 aux head + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + auxiliary_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/utils.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1826dbf8597b2924163c642d9104c2f43b210182 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_segmentors/utils.py @@ -0,0 +1,140 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import torch +from torch import nn + +from mmseg.models import BACKBONES, HEADS +from mmseg.models.decode_heads.cascade_decode_head import BaseCascadeDecodeHead +from mmseg.models.decode_heads.decode_head import BaseDecodeHead + + +def _demo_mm_inputs(input_shape=(1, 3, 8, 16), num_classes=10): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + + rng = np.random.RandomState(0) + + imgs = rng.rand(*input_shape) + segs = rng.randint( + low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8) + + img_metas = [{ + 'img_shape': (H, W, C), + 'ori_shape': (H, W, C), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + 'flip_direction': 'horizontal' + } for _ in range(N)] + + mm_inputs = { + 'imgs': torch.FloatTensor(imgs), + 'img_metas': img_metas, + 'gt_semantic_seg': torch.LongTensor(segs) + } + return mm_inputs + + +@BACKBONES.register_module() +class ExampleBackbone(nn.Module): + + def __init__(self): + super(ExampleBackbone, self).__init__() + self.conv = nn.Conv2d(3, 3, 3) + + def init_weights(self, pretrained=None): + pass + + def forward(self, x): + return [self.conv(x)] + + +@HEADS.register_module() +class ExampleDecodeHead(BaseDecodeHead): + + def __init__(self): + super(ExampleDecodeHead, self).__init__(3, 3, num_classes=19) + + def forward(self, inputs): + return self.cls_seg(inputs[0]) + + +@HEADS.register_module() +class ExampleCascadeDecodeHead(BaseCascadeDecodeHead): + + def __init__(self): + super(ExampleCascadeDecodeHead, self).__init__(3, 3, num_classes=19) + + def forward(self, inputs, prev_out): + return self.cls_seg(inputs[0]) + + +def _segmentor_forward_train_test(segmentor): + if isinstance(segmentor.decode_head, nn.ModuleList): + num_classes = segmentor.decode_head[-1].num_classes + else: + num_classes = segmentor.decode_head.num_classes + # batch_size=2 for BatchNorm + mm_inputs = _demo_mm_inputs(num_classes=num_classes) + + imgs = mm_inputs.pop('imgs') + img_metas = mm_inputs.pop('img_metas') + gt_semantic_seg = mm_inputs['gt_semantic_seg'] + + # convert to cuda Tensor if applicable + if torch.cuda.is_available(): + segmentor = segmentor.cuda() + imgs = imgs.cuda() + gt_semantic_seg = gt_semantic_seg.cuda() + + # Test forward train + losses = segmentor.forward( + imgs, img_metas, gt_semantic_seg=gt_semantic_seg, return_loss=True) + assert isinstance(losses, dict) + + # Test train_step + data_batch = dict( + img=imgs, img_metas=img_metas, gt_semantic_seg=gt_semantic_seg) + outputs = segmentor.train_step(data_batch, None) + assert isinstance(outputs, dict) + assert 'loss' in outputs + assert 'log_vars' in outputs + assert 'num_samples' in outputs + + # Test val_step + with torch.no_grad(): + segmentor.eval() + data_batch = dict( + img=imgs, img_metas=img_metas, gt_semantic_seg=gt_semantic_seg) + outputs = segmentor.val_step(data_batch, None) + assert isinstance(outputs, dict) + assert 'loss' in outputs + assert 'log_vars' in outputs + assert 'num_samples' in outputs + + # Test forward simple test + with torch.no_grad(): + segmentor.eval() + # pack into lists + img_list = [img[None, :] for img in imgs] + img_meta_list = [[img_meta] for img_meta in img_metas] + segmentor.forward(img_list, img_meta_list, return_loss=False) + + # Test forward aug test + with torch.no_grad(): + segmentor.eval() + # pack into lists + img_list = [img[None, :] for img in imgs] + img_list = img_list + img_list + img_meta_list = [[img_meta] for img_meta in img_metas] + img_meta_list = img_meta_list + img_meta_list + segmentor.forward(img_list, img_meta_list, return_loss=False) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/__init__.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_embed.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..be20c97b0d2a368428c8383fad1b1558a6bda34a --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_embed.py @@ -0,0 +1,461 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.utils.embed import AdaptivePadding, PatchEmbed, PatchMerging + + +def test_adaptive_padding(): + + for padding in ('same', 'corner'): + kernel_size = 16 + stride = 16 + dilation = 1 + input = torch.rand(1, 1, 15, 17) + adap_pool = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + out = adap_pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + input = torch.rand(1, 1, 16, 17) + out = adap_pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + + kernel_size = (2, 2) + stride = (2, 2) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # padding to divisible by 2 + assert (out.shape[2], out.shape[3]) == (12, 14) + + kernel_size = (2, 2) + stride = (10, 10) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 10, 13) + out = adap_pad(input) + # no padding + assert (out.shape[2], out.shape[3]) == (10, 13) + + kernel_size = (11, 11) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # all padding + assert (out.shape[2], out.shape[3]) == (21, 21) + + # test padding as kernel is (7,9) + input = torch.rand(1, 1, 11, 13) + stride = (3, 4) + kernel_size = (4, 5) + dilation = (2, 2) + # actually (7, 9) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + dilation_out = adap_pad(input) + assert (dilation_out.shape[2], dilation_out.shape[3]) == (16, 21) + kernel_size = (7, 9) + dilation = (1, 1) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + kernel79_out = adap_pad(input) + assert (kernel79_out.shape[2], kernel79_out.shape[3]) == (16, 21) + assert kernel79_out.shape == dilation_out.shape + + # assert only support "same" "corner" + with pytest.raises(AssertionError): + AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=1) + + +def test_patch_embed(): + B = 2 + H = 3 + W = 4 + C = 3 + embed_dims = 10 + kernel_size = 3 + stride = 1 + dummy_input = torch.rand(B, C, H, W) + patch_merge_1 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=1, + norm_cfg=None) + + x1, shape = patch_merge_1(dummy_input) + # test out shape + assert x1.shape == (2, 2, 10) + # test outsize is correct + assert shape == (1, 2) + # test L = out_h * out_w + assert shape[0] * shape[1] == x1.shape[1] + + B = 2 + H = 10 + W = 10 + C = 3 + embed_dims = 10 + kernel_size = 5 + stride = 2 + dummy_input = torch.rand(B, C, H, W) + # test dilation + patch_merge_2 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=None, + ) + + x2, shape = patch_merge_2(dummy_input) + # test out shape + assert x2.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x2.shape[1] + + stride = 2 + input_size = (10, 10) + + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + x3, shape = patch_merge_3(dummy_input) + # test out shape + assert x3.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x3.shape[1] + + # test the init_out_size with nn.Unfold + assert patch_merge_3.init_out_size[1] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + assert patch_merge_3.init_out_size[0] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + H = 11 + W = 12 + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + # test adap padding + for padding in ('same', 'corner'): + in_c = 2 + embed_dims = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_patch_merging(): + + # Test the model with int padding + in_c = 3 + out_c = 4 + kernel_size = 3 + stride = 3 + padding = 1 + dilation = 1 + bias = False + # test the case `pad_to_stride` is False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 3 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 16, 4) + assert out_size == (4, 4) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + in_c = 4 + out_c = 5 + kernel_size = 6 + stride = 3 + padding = 2 + dilation = 2 + bias = False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 4 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 4, 5) + assert out_size == (2, 2) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + + # Test with adaptive padding + for padding in ('same', 'corner'): + in_c = 2 + out_c = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_shape_convert.py b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_shape_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..60e87f38ed8b04fb964fa187d926061357d730cb --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_models/test_utils/test_shape_convert.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.utils import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc, + nlc_to_nchw) + + +def test_nchw2nlc2nchw(): + # Test nchw2nlc2nchw function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + + def test_func(x): + assert x.shape == torch.Size(shape_nlc) + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func, x) + assert output.shape == torch.Size(shape_nchw) + + def test_func2(x, arg): + assert x.shape == torch.Size(shape_nlc) + assert arg == 100 + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func2, x, arg=100) + assert output.shape == torch.Size(shape_nchw) + + def test_func3(x): + assert x.is_contiguous() + assert x.shape == torch.Size(shape_nlc) + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func3, x, contiguous=True) + assert output.shape == torch.Size(shape_nchw) + assert output.is_contiguous() + + +def test_nlc2nchw2nlc(): + # Test nlc2nchw2nlc function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + + def test_func(x): + assert x.shape == torch.Size(shape_nchw) + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func, x, shape_nchw[2:]) + assert output.shape == torch.Size(shape_nlc) + + def test_func2(x, arg): + assert x.shape == torch.Size(shape_nchw) + assert arg == 100 + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func2, x, shape_nchw[2:], arg=100) + assert output.shape == torch.Size(shape_nlc) + + def test_func3(x): + assert x.is_contiguous() + assert x.shape == torch.Size(shape_nchw) + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func3, x, shape_nchw[2:], contiguous=True) + assert output.shape == torch.Size(shape_nlc) + assert output.is_contiguous() + + +def test_nchw_to_nlc(): + # Test nchw_to_nlc function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + x = torch.rand(*shape_nchw) + y = nchw_to_nlc(x) + assert y.shape == torch.Size(shape_nlc) + + +def test_nlc_to_nchw(): + # Test nlc_to_nchw function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + x = torch.rand(*shape_nlc) + y = nlc_to_nchw(x, (5, 5)) + assert y.shape == torch.Size(shape_nchw) diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_sampler.py b/EgoHOS/raw/script/mmsegmentation/tests/test_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..14092243f5813f151f590c40648eee37f4804d64 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_sampler.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.core import OHEMPixelSampler +from mmseg.models.decode_heads import FCNHead + + +def _context_for_ohem(): + return FCNHead(in_channels=32, channels=16, num_classes=19) + + +def _context_for_ohem_multiple_loss(): + return FCNHead( + in_channels=32, + channels=16, + num_classes=19, + loss_decode=[ + dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2') + ]) + + +def test_ohem_sampler(): + + with pytest.raises(AssertionError): + # seg_logit and seg_label must be of the same size + sampler = OHEMPixelSampler(context=_context_for_ohem()) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 89, 89)) + sampler.sample(seg_logit, seg_label) + + # test with thresh + sampler = OHEMPixelSampler( + context=_context_for_ohem(), thresh=0.7, min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() > 200 + + # test w.o thresh + sampler = OHEMPixelSampler(context=_context_for_ohem(), min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() == 200 + + # test multiple losses case + with pytest.raises(AssertionError): + # seg_logit and seg_label must be of the same size + sampler = OHEMPixelSampler(context=_context_for_ohem_multiple_loss()) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 89, 89)) + sampler.sample(seg_logit, seg_label) + + # test with thresh in multiple losses case + sampler = OHEMPixelSampler( + context=_context_for_ohem_multiple_loss(), thresh=0.7, min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() > 200 + + # test w.o thresh in multiple losses case + sampler = OHEMPixelSampler( + context=_context_for_ohem_multiple_loss(), min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() == 200 diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_misc.py b/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce1fa6145730799b6d5d8e799b20323dcd46272 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_misc.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile + +from mmseg.utils import find_latest_checkpoint + + +def test_find_latest_checkpoint(): + with tempfile.TemporaryDirectory() as tempdir: + # no checkpoints in the path + path = tempdir + latest = find_latest_checkpoint(path) + assert latest is None + + # The path doesn't exist + path = osp.join(tempdir, 'none') + latest = find_latest_checkpoint(path) + assert latest is None + + # test when latest.pth exists + with tempfile.TemporaryDirectory() as tempdir: + with open(osp.join(tempdir, 'latest.pth'), 'w') as f: + f.write('latest') + path = tempdir + latest = find_latest_checkpoint(path) + assert latest == osp.join(tempdir, 'latest.pth') + + with tempfile.TemporaryDirectory() as tempdir: + for iter in range(1600, 160001, 1600): + with open(osp.join(tempdir, f'iter_{iter}.pth'), 'w') as f: + f.write(f'iter_{iter}.pth') + latest = find_latest_checkpoint(tempdir) + assert latest == osp.join(tempdir, 'iter_160000.pth') + + with tempfile.TemporaryDirectory() as tempdir: + for epoch in range(1, 21): + with open(osp.join(tempdir, f'epoch_{epoch}.pth'), 'w') as f: + f.write(f'epoch_{epoch}.pth') + latest = find_latest_checkpoint(tempdir) + assert latest == osp.join(tempdir, 'epoch_20.pth') diff --git a/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_set_env.py b/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_set_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0af4424b1dbf0869a464ede38c1dc2fb9528ed96 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tests/test_utils/test_set_env.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import multiprocessing as mp +import os +import platform + +import cv2 +import pytest +from mmcv import Config + +from mmseg.utils import setup_multi_processes + + +@pytest.mark.parametrize('workers_per_gpu', (0, 2)) +@pytest.mark.parametrize(('valid', 'env_cfg'), [(True, + dict( + mp_start_method='fork', + opencv_num_threads=0, + omp_num_threads=1, + mkl_num_threads=1)), + (False, + dict( + mp_start_method=1, + opencv_num_threads=0.1, + omp_num_threads='s', + mkl_num_threads='1'))]) +def test_setup_multi_processes(workers_per_gpu, valid, env_cfg): + # temp save system setting + sys_start_mehod = mp.get_start_method(allow_none=True) + sys_cv_threads = cv2.getNumThreads() + # pop and temp save system env vars + sys_omp_threads = os.environ.pop('OMP_NUM_THREADS', default=None) + sys_mkl_threads = os.environ.pop('MKL_NUM_THREADS', default=None) + + config = dict(data=dict(workers_per_gpu=workers_per_gpu)) + config.update(env_cfg) + cfg = Config(config) + setup_multi_processes(cfg) + + # test when cfg is valid and workers_per_gpu > 0 + # setup_multi_processes will work + if valid and workers_per_gpu > 0: + # test config without setting env + + assert os.getenv('OMP_NUM_THREADS') == str(env_cfg['omp_num_threads']) + assert os.getenv('MKL_NUM_THREADS') == str(env_cfg['mkl_num_threads']) + # when set to 0, the num threads will be 1 + assert cv2.getNumThreads() == env_cfg[ + 'opencv_num_threads'] if env_cfg['opencv_num_threads'] > 0 else 1 + if platform.system() != 'Windows': + assert mp.get_start_method() == env_cfg['mp_start_method'] + + # revert setting to avoid affecting other programs + if sys_start_mehod: + mp.set_start_method(sys_start_mehod, force=True) + cv2.setNumThreads(sys_cv_threads) + if sys_omp_threads: + os.environ['OMP_NUM_THREADS'] = sys_omp_threads + else: + os.environ.pop('OMP_NUM_THREADS') + if sys_mkl_threads: + os.environ['MKL_NUM_THREADS'] = sys_mkl_threads + else: + os.environ.pop('MKL_NUM_THREADS') + + elif valid and workers_per_gpu == 0: + + if platform.system() != 'Windows': + assert mp.get_start_method() == env_cfg['mp_start_method'] + assert cv2.getNumThreads() == env_cfg[ + 'opencv_num_threads'] if env_cfg['opencv_num_threads'] > 0 else 1 + assert 'OMP_NUM_THREADS' not in os.environ + assert 'MKL_NUM_THREADS' not in os.environ + if sys_start_mehod: + mp.set_start_method(sys_start_mehod, force=True) + cv2.setNumThreads(sys_cv_threads) + if sys_omp_threads: + os.environ['OMP_NUM_THREADS'] = sys_omp_threads + if sys_mkl_threads: + os.environ['MKL_NUM_THREADS'] = sys_mkl_threads + + else: + assert mp.get_start_method() == sys_start_mehod + assert cv2.getNumThreads() == sys_cv_threads + assert 'OMP_NUM_THREADS' not in os.environ + assert 'MKL_NUM_THREADS' not in os.environ diff --git a/EgoHOS/raw/script/mmsegmentation/tools/analyze_logs.py b/EgoHOS/raw/script/mmsegmentation/tools/analyze_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..e2127d4d627a1044f2f2b3719c38fda7bc8c928f --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/analyze_logs.py @@ -0,0 +1,128 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/open- +mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" +import argparse +import json +from collections import defaultdict + +import matplotlib.pyplot as plt +import seaborn as sns + + +def plot_curve(log_dicts, args): + if args.backend is not None: + plt.switch_backend(args.backend) + sns.set_style(args.style) + # if legend is None, use {filename}_{key} as legend + legend = args.legend + if legend is None: + legend = [] + for json_log in args.json_logs: + for metric in args.keys: + legend.append(f'{json_log}_{metric}') + assert len(legend) == (len(args.json_logs) * len(args.keys)) + metrics = args.keys + + num_metrics = len(metrics) + for i, log_dict in enumerate(log_dicts): + epochs = list(log_dict.keys()) + for j, metric in enumerate(metrics): + print(f'plot curve of {args.json_logs[i]}, metric is {metric}') + plot_epochs = [] + plot_iters = [] + plot_values = [] + # In some log files exist lines of validation, + # `mode` list is used to only collect iter number + # of training line. + for epoch in epochs: + epoch_logs = log_dict[epoch] + if metric not in epoch_logs.keys(): + continue + if metric in ['mIoU', 'mAcc', 'aAcc']: + plot_epochs.append(epoch) + plot_values.append(epoch_logs[metric][0]) + else: + for idx in range(len(epoch_logs[metric])): + if epoch_logs['mode'][idx] == 'train': + plot_iters.append(epoch_logs['iter'][idx]) + plot_values.append(epoch_logs[metric][idx]) + ax = plt.gca() + label = legend[i * num_metrics + j] + if metric in ['mIoU', 'mAcc', 'aAcc']: + ax.set_xticks(plot_epochs) + plt.xlabel('epoch') + plt.plot(plot_epochs, plot_values, label=label, marker='o') + else: + plt.xlabel('iter') + plt.plot(plot_iters, plot_values, label=label, linewidth=0.5) + plt.legend() + if args.title is not None: + plt.title(args.title) + if args.out is None: + plt.show() + else: + print(f'save curve to: {args.out}') + plt.savefig(args.out) + plt.cla() + + +def parse_args(): + parser = argparse.ArgumentParser(description='Analyze Json Log') + parser.add_argument( + 'json_logs', + type=str, + nargs='+', + help='path of train log in json format') + parser.add_argument( + '--keys', + type=str, + nargs='+', + default=['mIoU'], + help='the metric that you want to plot') + parser.add_argument('--title', type=str, help='title of figure') + parser.add_argument( + '--legend', + type=str, + nargs='+', + default=None, + help='legend of each plot') + parser.add_argument( + '--backend', type=str, default=None, help='backend of plt') + parser.add_argument( + '--style', type=str, default='dark', help='style of plt') + parser.add_argument('--out', type=str, default=None) + args = parser.parse_args() + return args + + +def load_json_logs(json_logs): + # load and convert json_logs to log_dict, key is epoch, value is a sub dict + # keys of sub dict is different metrics + # value of sub dict is a list of corresponding values of all iterations + log_dicts = [dict() for _ in json_logs] + for json_log, log_dict in zip(json_logs, log_dicts): + with open(json_log, 'r') as log_file: + for line in log_file: + log = json.loads(line.strip()) + # skip lines without `epoch` field + if 'epoch' not in log: + continue + epoch = log.pop('epoch') + if epoch not in log_dict: + log_dict[epoch] = defaultdict(list) + for k, v in log.items(): + log_dict[epoch][k].append(v) + return log_dicts + + +def main(): + args = parse_args() + json_logs = args.json_logs + for json_log in json_logs: + assert json_log.endswith('.json') + log_dicts = load_json_logs(json_logs) + plot_curve(log_dicts, args) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/benchmark.py b/EgoHOS/raw/script/mmsegmentation/tools/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d6888482a1f389f2dbf0e6c3d4e58542229b71 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/benchmark.py @@ -0,0 +1,120 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import time + +import mmcv +import numpy as np +import torch +from mmcv import Config +from mmcv.parallel import MMDataParallel +from mmcv.runner import load_checkpoint, wrap_fp16_model + +from mmseg.datasets import build_dataloader, build_dataset +from mmseg.models import build_segmentor + + +def parse_args(): + parser = argparse.ArgumentParser(description='MMSeg benchmark a model') + parser.add_argument('config', help='test config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--log-interval', type=int, default=50, help='interval of logging') + parser.add_argument( + '--work-dir', + help=('if specified, the results will be dumped ' + 'into the directory as json')) + parser.add_argument('--repeat-times', type=int, default=1) + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + if args.work_dir is not None: + mmcv.mkdir_or_exist(osp.abspath(args.work_dir)) + json_file = osp.join(args.work_dir, f'fps_{timestamp}.json') + else: + # use config filename as default work_dir if cfg.work_dir is None + work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + mmcv.mkdir_or_exist(osp.abspath(work_dir)) + json_file = osp.join(work_dir, f'fps_{timestamp}.json') + + repeat_times = args.repeat_times + # set cudnn_benchmark + torch.backends.cudnn.benchmark = False + cfg.model.pretrained = None + cfg.data.test.test_mode = True + + benchmark_dict = dict(config=args.config, unit='img / s') + overall_fps_list = [] + for time_index in range(repeat_times): + print(f'Run {time_index + 1}:') + # build the dataloader + # TODO: support multiple images per gpu (only minor changes are needed) + dataset = build_dataset(cfg.data.test) + data_loader = build_dataloader( + dataset, + samples_per_gpu=1, + workers_per_gpu=cfg.data.workers_per_gpu, + dist=False, + shuffle=False) + + # build the model and load checkpoint + cfg.model.train_cfg = None + model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg')) + fp16_cfg = cfg.get('fp16', None) + if fp16_cfg is not None: + wrap_fp16_model(model) + if 'checkpoint' in args and osp.exists(args.checkpoint): + load_checkpoint(model, args.checkpoint, map_location='cpu') + + model = MMDataParallel(model, device_ids=[0]) + + model.eval() + + # the first several iterations may be very slow so skip them + num_warmup = 5 + pure_inf_time = 0 + total_iters = 200 + + # benchmark with 200 image and take the average + for i, data in enumerate(data_loader): + + torch.cuda.synchronize() + start_time = time.perf_counter() + + with torch.no_grad(): + model(return_loss=False, rescale=True, **data) + + torch.cuda.synchronize() + elapsed = time.perf_counter() - start_time + + if i >= num_warmup: + pure_inf_time += elapsed + if (i + 1) % args.log_interval == 0: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Done image [{i + 1:<3}/ {total_iters}], ' + f'fps: {fps:.2f} img / s') + + if (i + 1) == total_iters: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Overall fps: {fps:.2f} img / s\n') + benchmark_dict[f'overall_fps_{time_index + 1}'] = round(fps, 2) + overall_fps_list.append(fps) + break + benchmark_dict['average_fps'] = round(np.mean(overall_fps_list), 2) + benchmark_dict['fps_variance'] = round(np.var(overall_fps_list), 4) + print(f'Average fps of {repeat_times} evaluations: ' + f'{benchmark_dict["average_fps"]}') + print(f'The variance of {repeat_times} evaluations: ' + f'{benchmark_dict["fps_variance"]}') + mmcv.dump(benchmark_dict, json_file, indent=4) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/browse_dataset.py b/EgoHOS/raw/script/mmsegmentation/tools/browse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa9430ea0f8e313a9e3f7feafd7f0f544338af4 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/browse_dataset.py @@ -0,0 +1,182 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import warnings +from pathlib import Path + +import mmcv +import numpy as np +from mmcv import Config, DictAction + +from mmseg.datasets.builder import build_dataset + + +def parse_args(): + parser = argparse.ArgumentParser(description='Browse a dataset') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--show-origin', + default=False, + action='store_true', + help='if True, omit all augmentation in pipeline,' + ' show origin image and seg map') + parser.add_argument( + '--skip-type', + type=str, + nargs='+', + default=['DefaultFormatBundle', 'Normalize', 'Collect'], + help='skip some useless pipeline,if `show-origin` is true, ' + 'all pipeline except `Load` will be skipped') + parser.add_argument( + '--output-dir', + default='./output', + type=str, + help='If there is no display interface, you can save it') + parser.add_argument('--show', default=False, action='store_true') + parser.add_argument( + '--show-interval', + type=int, + default=999, + help='the interval of show (ms)') + parser.add_argument( + '--opacity', + type=float, + default=0.5, + help='the opacity of semantic map') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def imshow_semantic(img, + seg, + class_names, + palette=None, + win_name='', + show=False, + wait_time=0, + out_file=None, + opacity=0.5): + """Draw `result` over `img`. + + Args: + img (str or Tensor): The image to be displayed. + seg (Tensor): The semantic segmentation results to draw over + `img`. + class_names (list[str]): Names of each classes. + palette (list[list[int]]] | np.ndarray | None): The palette of + segmentation map. If None is given, random palette will be + generated. Default: None + win_name (str): The window name. + wait_time (int): Value of waitKey param. + Default: 0. + show (bool): Whether to show the image. + Default: False. + out_file (str or None): The filename to write the image. + Default: None. + opacity(float): Opacity of painted segmentation map. + Default 0.5. + Must be in (0, 1] range. + Returns: + img (Tensor): Only if not `show` or `out_file` + """ + img = mmcv.imread(img) + img = img.copy() + if palette is None: + palette = np.random.randint(0, 255, size=(len(class_names), 3)) + palette = np.array(palette) + assert palette.shape[0] == len(class_names) + assert palette.shape[1] == 3 + assert len(palette.shape) == 2 + assert 0 < opacity <= 1.0 + color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) + for label, color in enumerate(palette): + color_seg[seg == label, :] = color + # convert to BGR + color_seg = color_seg[..., ::-1] + + img = img * (1 - opacity) + color_seg * opacity + img = img.astype(np.uint8) + # if out_file specified, do not show image in window + if out_file is not None: + show = False + + if show: + mmcv.imshow(img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(img, out_file) + + if not (show or out_file): + warnings.warn('show==False and out_file is not specified, only ' + 'result image will be returned') + return img + + +def _retrieve_data_cfg(_data_cfg, skip_type, show_origin): + if show_origin is True: + # only keep pipeline of Loading data and ann + _data_cfg['pipeline'] = [ + x for x in _data_cfg.pipeline if 'Load' in x['type'] + ] + else: + _data_cfg['pipeline'] = [ + x for x in _data_cfg.pipeline if x['type'] not in skip_type + ] + + +def retrieve_data_cfg(config_path, skip_type, cfg_options, show_origin=False): + cfg = Config.fromfile(config_path) + if cfg_options is not None: + cfg.merge_from_dict(cfg_options) + train_data_cfg = cfg.data.train + if isinstance(train_data_cfg, list): + for _data_cfg in train_data_cfg: + while 'dataset' in _data_cfg and _data_cfg[ + 'type'] != 'MultiImageMixDataset': + _data_cfg = _data_cfg['dataset'] + if 'pipeline' in _data_cfg: + _retrieve_data_cfg(_data_cfg, skip_type, show_origin) + else: + raise ValueError + else: + while 'dataset' in train_data_cfg and train_data_cfg[ + 'type'] != 'MultiImageMixDataset': + train_data_cfg = train_data_cfg['dataset'] + _retrieve_data_cfg(train_data_cfg, skip_type, show_origin) + return cfg + + +def main(): + args = parse_args() + cfg = retrieve_data_cfg(args.config, args.skip_type, args.cfg_options, + args.show_origin) + dataset = build_dataset(cfg.data.train) + progress_bar = mmcv.ProgressBar(len(dataset)) + for item in dataset: + filename = os.path.join(args.output_dir, + Path(item['filename']).name + ) if args.output_dir is not None else None + imshow_semantic( + item['img'], + item['gt_semantic_seg'], + dataset.CLASSES, + dataset.PALETTE, + show=args.show, + wait_time=args.show_interval, + out_file=filename, + opacity=args.opacity, + ) + progress_bar.update() + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/confusion_matrix.py b/EgoHOS/raw/script/mmsegmentation/tools/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5b64cf4e8214d17a7fb4b600e97a392a3aa297 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/confusion_matrix.py @@ -0,0 +1,184 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os + +import matplotlib.pyplot as plt +import mmcv +import numpy as np +from matplotlib.ticker import MultipleLocator +from mmcv import Config, DictAction + +from mmseg.datasets import build_dataset + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Generate confusion matrix from segmentation results') + parser.add_argument('config', help='test config file path') + parser.add_argument( + 'prediction_path', help='prediction path where test .pkl result') + parser.add_argument( + 'save_dir', help='directory where confusion matrix will be saved') + parser.add_argument( + '--show', action='store_true', help='show confusion matrix') + parser.add_argument( + '--color-theme', + default='winter', + help='theme of the matrix color map') + parser.add_argument( + '--title', + default='Normalized Confusion Matrix', + help='title of the matrix color map') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def calculate_confusion_matrix(dataset, results): + """Calculate the confusion matrix. + + Args: + dataset (Dataset): Test or val dataset. + results (list[ndarray]): A list of segmentation results in each image. + """ + n = len(dataset.CLASSES) + confusion_matrix = np.zeros(shape=[n, n]) + assert len(dataset) == len(results) + prog_bar = mmcv.ProgressBar(len(results)) + for idx, per_img_res in enumerate(results): + res_segm = per_img_res + gt_segm = dataset.get_gt_seg_map_by_idx(idx) + inds = n * gt_segm + res_segm + inds = inds.flatten() + mat = np.bincount(inds, minlength=n**2).reshape(n, n) + confusion_matrix += mat + prog_bar.update() + return confusion_matrix + + +def plot_confusion_matrix(confusion_matrix, + labels, + save_dir=None, + show=True, + title='Normalized Confusion Matrix', + color_theme='winter'): + """Draw confusion matrix with matplotlib. + + Args: + confusion_matrix (ndarray): The confusion matrix. + labels (list[str]): List of class names. + save_dir (str|optional): If set, save the confusion matrix plot to the + given path. Default: None. + show (bool): Whether to show the plot. Default: True. + title (str): Title of the plot. Default: `Normalized Confusion Matrix`. + color_theme (str): Theme of the matrix color map. Default: `winter`. + """ + # normalize the confusion matrix + per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis] + confusion_matrix = \ + confusion_matrix.astype(np.float32) / per_label_sums * 100 + + num_classes = len(labels) + fig, ax = plt.subplots( + figsize=(2 * num_classes, 2 * num_classes * 0.8), dpi=180) + cmap = plt.get_cmap(color_theme) + im = ax.imshow(confusion_matrix, cmap=cmap) + plt.colorbar(mappable=im, ax=ax) + + title_font = {'weight': 'bold', 'size': 12} + ax.set_title(title, fontdict=title_font) + label_font = {'size': 10} + plt.ylabel('Ground Truth Label', fontdict=label_font) + plt.xlabel('Prediction Label', fontdict=label_font) + + # draw locator + xmajor_locator = MultipleLocator(1) + xminor_locator = MultipleLocator(0.5) + ax.xaxis.set_major_locator(xmajor_locator) + ax.xaxis.set_minor_locator(xminor_locator) + ymajor_locator = MultipleLocator(1) + yminor_locator = MultipleLocator(0.5) + ax.yaxis.set_major_locator(ymajor_locator) + ax.yaxis.set_minor_locator(yminor_locator) + + # draw grid + ax.grid(True, which='minor', linestyle='-') + + # draw label + ax.set_xticks(np.arange(num_classes)) + ax.set_yticks(np.arange(num_classes)) + ax.set_xticklabels(labels) + ax.set_yticklabels(labels) + + ax.tick_params( + axis='x', bottom=False, top=True, labelbottom=False, labeltop=True) + plt.setp( + ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor') + + # draw confusion matrix value + for i in range(num_classes): + for j in range(num_classes): + ax.text( + j, + i, + '{}%'.format( + round(confusion_matrix[i, j], 2 + ) if not np.isnan(confusion_matrix[i, j]) else -1), + ha='center', + va='center', + color='w', + size=7) + + ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1 + + fig.tight_layout() + if save_dir is not None: + plt.savefig( + os.path.join(save_dir, 'confusion_matrix.png'), format='png') + if show: + plt.show() + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + results = mmcv.load(args.prediction_path) + + assert isinstance(results, list) + if isinstance(results[0], np.ndarray): + pass + else: + raise TypeError('invalid type of prediction results') + + if isinstance(cfg.data.test, dict): + cfg.data.test.test_mode = True + elif isinstance(cfg.data.test, list): + for ds_cfg in cfg.data.test: + ds_cfg.test_mode = True + + dataset = build_dataset(cfg.data.test) + confusion_matrix = calculate_confusion_matrix(dataset, results) + plot_confusion_matrix( + confusion_matrix, + dataset.CLASSES, + save_dir=args.save_dir, + show=args.show, + title=args.title, + color_theme=args.color_theme) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/chase_db1.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/chase_db1.py new file mode 100644 index 0000000000000000000000000000000000000000..580e6e7ec518e139db4ad7f61dca057ed179efed --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/chase_db1.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv + +CHASE_DB1_LEN = 28 * 3 +TRAINING_LEN = 60 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert CHASE_DB1 dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='path of CHASEDB1.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'CHASE_DB1') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(out_dir) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting CHASEDB1.zip...') + zip_file = zipfile.ZipFile(dataset_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + + assert len(os.listdir(tmp_dir)) == CHASE_DB1_LEN, \ + 'len(os.listdir(tmp_dir)) != {}'.format(CHASE_DB1_LEN) + + for img_name in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(img_name)[0] + '.png')) + else: + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + for img_name in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(img_name)[0] + '.png')) + else: + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/cityscapes.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..17b61684787bf1e482bf912c1c988446ad320597 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/cityscapes.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmcv +from cityscapesscripts.preparation.json2labelImg import json2labelImg + + +def convert_json_to_label(json_file): + label_file = json_file.replace('_polygons.json', '_labelTrainIds.png') + json2labelImg(json_file, label_file, 'trainIds') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert Cityscapes annotations to TrainIds') + parser.add_argument('cityscapes_path', help='cityscapes data path') + parser.add_argument('--gt-dir', default='gtFine', type=str) + parser.add_argument('-o', '--out-dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cityscapes_path = args.cityscapes_path + out_dir = args.out_dir if args.out_dir else cityscapes_path + mmcv.mkdir_or_exist(out_dir) + + gt_dir = osp.join(cityscapes_path, args.gt_dir) + + poly_files = [] + for poly in mmcv.scandir(gt_dir, '_polygons.json', recursive=True): + poly_file = osp.join(gt_dir, poly) + poly_files.append(poly_file) + if args.nproc > 1: + mmcv.track_parallel_progress(convert_json_to_label, poly_files, + args.nproc) + else: + mmcv.track_progress(convert_json_to_label, poly_files) + + split_names = ['train', 'val', 'test'] + + for split in split_names: + filenames = [] + for poly in mmcv.scandir( + osp.join(gt_dir, split), '_polygons.json', recursive=True): + filenames.append(poly.replace('_gtFine_polygons.json', '')) + with open(osp.join(out_dir, f'{split}.txt'), 'w') as f: + f.writelines(f + '\n' for f in filenames) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff10k.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff10k.py new file mode 100644 index 0000000000000000000000000000000000000000..374f81970378f865a12307dedf6507ba61314e0f --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff10k.py @@ -0,0 +1,307 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial + +import mmcv +import numpy as np +from PIL import Image +from scipy.io import loadmat + +COCO_LEN = 10000 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 11: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 25: 24, + 27: 25, + 28: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 44: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 65: 60, + 67: 61, + 70: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 82: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 90: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 182: 171 +} + + +def convert_to_trainID(tuple_path, in_img_dir, in_ann_dir, out_img_dir, + out_mask_dir, is_train): + imgpath, maskpath = tuple_path + shutil.copyfile( + osp.join(in_img_dir, imgpath), + osp.join(out_img_dir, 'train2014', imgpath) if is_train else osp.join( + out_img_dir, 'test2014', imgpath)) + annotate = loadmat(osp.join(in_ann_dir, maskpath)) + mask = annotate['S'].astype(np.uint8) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join(out_mask_dir, 'train2014', + maskpath.split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'test2014', + maskpath.split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def generate_coco_list(folder): + train_list = osp.join(folder, 'imageLists', 'train.txt') + test_list = osp.join(folder, 'imageLists', 'test.txt') + train_paths = [] + test_paths = [] + + with open(train_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + train_paths.append((imgpath, maskpath)) + + with open(test_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + test_paths.append((imgpath, maskpath)) + + return train_paths, test_paths + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 10k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mmcv.mkdir_or_exist(osp.join(out_img_dir, 'train2014')) + mmcv.mkdir_or_exist(osp.join(out_img_dir, 'test2014')) + mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'train2014')) + mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'test2014')) + + train_list, test_list = generate_coco_list(coco_path) + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + mmcv.track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), + train_list, + nproc=nproc) + mmcv.track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), + test_list, + nproc=nproc) + else: + mmcv.track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), train_list) + mmcv.track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff164k.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8e2f2a315ea1bc63ec6ee1d9f37a72995330ce --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/coco_stuff164k.py @@ -0,0 +1,264 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial +from glob import glob + +import mmcv +import numpy as np +from PIL import Image + +COCO_LEN = 123287 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 12: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 26: 24, + 27: 25, + 30: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 45: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 66: 60, + 69: 61, + 71: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 83: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 91: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 255: 255 +} + + +def convert_to_trainID(maskpath, out_mask_dir, is_train): + mask = np.array(Image.open(maskpath)) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join( + out_mask_dir, 'train2017', + osp.basename(maskpath).split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'val2017', + osp.basename(maskpath).split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 164k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'train2017')) + mmcv.mkdir_or_exist(osp.join(out_mask_dir, 'val2017')) + + if out_dir != coco_path: + shutil.copytree(osp.join(coco_path, 'images'), out_img_dir) + + train_list = glob(osp.join(coco_path, 'annotations', 'train2017', '*.png')) + train_list = [file for file in train_list if '_labelTrainIds' not in file] + test_list = glob(osp.join(coco_path, 'annotations', 'val2017', '*.png')) + test_list = [file for file in test_list if '_labelTrainIds' not in file] + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + mmcv.track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list, + nproc=nproc) + mmcv.track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list, + nproc=nproc) + else: + mmcv.track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list) + mmcv.track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/drive.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/drive.py new file mode 100644 index 0000000000000000000000000000000000000000..f547579b2d9a045828559ed37acf64760fe4eed3 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/drive.py @@ -0,0 +1,113 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import cv2 +import mmcv + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert DRIVE dataset to mmsegmentation format') + parser.add_argument( + 'training_path', help='the training part of DRIVE dataset') + parser.add_argument( + 'testing_path', help='the testing part of DRIVE dataset') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + training_path = args.training_path + testing_path = args.testing_path + if args.out_dir is None: + out_dir = osp.join('data', 'DRIVE') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(out_dir) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting training.zip...') + zip_file = zipfile.ZipFile(training_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + now_dir = osp.join(tmp_dir, 'training', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'training', + osp.splitext(img_name)[0].replace('_training', '') + + '.png')) + + now_dir = osp.join(tmp_dir, 'training', '1st_manual') + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + print('Extracting test.zip...') + zip_file = zipfile.ZipFile(testing_path) + zip_file.extractall(tmp_dir) + + print('Generating validation dataset...') + now_dir = osp.join(tmp_dir, 'test', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'validation', + osp.splitext(img_name)[0].replace('_test', '') + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '1st_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '2nd_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/hrf.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/hrf.py new file mode 100644 index 0000000000000000000000000000000000000000..5e016e3caeb61afaf967e2acc082ed952c990b0c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/hrf.py @@ -0,0 +1,111 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv + +HRF_LEN = 15 +TRAINING_LEN = 5 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert HRF dataset to mmsegmentation format') + parser.add_argument('healthy_path', help='the path of healthy.zip') + parser.add_argument( + 'healthy_manualsegm_path', help='the path of healthy_manualsegm.zip') + parser.add_argument('glaucoma_path', help='the path of glaucoma.zip') + parser.add_argument( + 'glaucoma_manualsegm_path', help='the path of glaucoma_manualsegm.zip') + parser.add_argument( + 'diabetic_retinopathy_path', + help='the path of diabetic_retinopathy.zip') + parser.add_argument( + 'diabetic_retinopathy_manualsegm_path', + help='the path of diabetic_retinopathy_manualsegm.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + images_path = [ + args.healthy_path, args.glaucoma_path, args.diabetic_retinopathy_path + ] + annotations_path = [ + args.healthy_manualsegm_path, args.glaucoma_manualsegm_path, + args.diabetic_retinopathy_manualsegm_path + ] + if args.out_dir is None: + out_dir = osp.join('data', 'HRF') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(out_dir) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + print('Generating images...') + for now_path in images_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + 'len(os.listdir(tmp_dir)) != {}'.format(HRF_LEN) + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Generating annotations...') + for now_path in annotations_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + 'len(os.listdir(tmp_dir)) != {}'.format(HRF_LEN) + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/isaid.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/isaid.py new file mode 100644 index 0000000000000000000000000000000000000000..314fb894f82e724ab93384969d13cc8ea12990fe --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/isaid.py @@ -0,0 +1,245 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +import mmcv +import numpy as np +from PIL import Image + +iSAID_palette = \ + { + 0: (0, 0, 0), + 1: (0, 0, 63), + 2: (0, 63, 63), + 3: (0, 63, 0), + 4: (0, 63, 127), + 5: (0, 63, 191), + 6: (0, 63, 255), + 7: (0, 127, 63), + 8: (0, 127, 127), + 9: (0, 0, 127), + 10: (0, 0, 191), + 11: (0, 0, 255), + 12: (0, 191, 127), + 13: (0, 127, 191), + 14: (0, 127, 255), + 15: (0, 100, 155) + } + +iSAID_invert_palette = {v: k for k, v in iSAID_palette.items()} + + +def iSAID_convert_from_color(arr_3d, palette=iSAID_invert_palette): + """RGB-color encoding to grayscale labels.""" + arr_2d = np.zeros((arr_3d.shape[0], arr_3d.shape[1]), dtype=np.uint8) + + for c, i in palette.items(): + m = np.all(arr_3d == np.array(c).reshape(1, 1, 3), axis=2) + arr_2d[m] = i + + return arr_2d + + +def slide_crop_image(src_path, out_dir, mode, patch_H, patch_W, overlap): + img = np.asarray(Image.open(src_path).convert('RGB')) + + img_H, img_W, _ = img.shape + + if img_H < patch_H and img_W > patch_W: + + img = mmcv.impad(img, shape=(patch_H, img_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H > patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(img_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H < patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(patch_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + img_patch = img[y_str:y_end, x_str:x_end, :] + img_patch = Image.fromarray(img_patch.astype(np.uint8)) + image = osp.basename(src_path).split('.')[0] + '_' + str( + y_str) + '_' + str(y_end) + '_' + str(x_str) + '_' + str( + x_end) + '.png' + # print(image) + save_path_image = osp.join(out_dir, 'img_dir', mode, str(image)) + img_patch.save(save_path_image) + + +def slide_crop_label(src_path, out_dir, mode, patch_H, patch_W, overlap): + label = mmcv.imread(src_path, channel_order='rgb') + label = iSAID_convert_from_color(label) + img_H, img_W = label.shape + + if img_H < patch_H and img_W > patch_W: + + label = mmcv.impad(label, shape=(patch_H, img_W), pad_val=255) + + img_H = patch_H + + elif img_H > patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(img_H, patch_W), pad_val=255) + + img_W = patch_W + + elif img_H < patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(patch_H, patch_W), pad_val=255) + + img_H = patch_H + img_W = patch_W + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + lab_patch = label[y_str:y_end, x_str:x_end] + lab_patch = Image.fromarray(lab_patch.astype(np.uint8), mode='P') + + image = osp.basename(src_path).split('.')[0].split( + '_')[0] + '_' + str(y_str) + '_' + str(y_end) + '_' + str( + x_str) + '_' + str(x_end) + '_instance_color_RGB' + '.png' + lab_patch.save(osp.join(out_dir, 'ann_dir', mode, str(image))) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert iSAID dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='iSAID folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + + parser.add_argument( + '--patch_width', + default=896, + type=int, + help='Width of the cropped image patch') + parser.add_argument( + '--patch_height', + default=896, + type=int, + help='Height of the cropped image patch') + parser.add_argument( + '--overlap_area', default=384, type=int, help='Overlap area') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + # image patch width and height + patch_H, patch_W = args.patch_width, args.patch_height + + overlap = args.overlap_area # overlap area + + if args.out_dir is None: + out_dir = osp.join('data', 'iSAID') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'test')) + + assert os.path.exists(os.path.join(dataset_path, 'train')), \ + 'train is not in {}'.format(dataset_path) + assert os.path.exists(os.path.join(dataset_path, 'val')), \ + 'val is not in {}'.format(dataset_path) + assert os.path.exists(os.path.join(dataset_path, 'test')), \ + 'test is not in {}'.format(dataset_path) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset_mode in ['train', 'val', 'test']: + + # for dataset_mode in [ 'test']: + print('Extracting {}ing.zip...'.format(dataset_mode)) + img_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'images', '*.zip')) + print('Find the data', img_zipp_list) + for img_zipp in img_zipp_list: + zip_file = zipfile.ZipFile(img_zipp) + zip_file.extractall(os.path.join(tmp_dir, dataset_mode, 'img')) + src_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'img', 'images', '*.png')) + + src_prog_bar = mmcv.ProgressBar(len(src_path_list)) + for i, img_path in enumerate(src_path_list): + if dataset_mode != 'test': + slide_crop_image(img_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + + else: + shutil.move(img_path, + os.path.join(out_dir, 'img_dir', dataset_mode)) + src_prog_bar.update() + + if dataset_mode != 'test': + label_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'Semantic_masks', + '*.zip')) + for label_zipp in label_zipp_list: + zip_file = zipfile.ZipFile(label_zipp) + zip_file.extractall( + os.path.join(tmp_dir, dataset_mode, 'lab')) + + lab_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'lab', 'images', + '*.png')) + lab_prog_bar = mmcv.ProgressBar(len(lab_path_list)) + for i, lab_path in enumerate(lab_path_list): + slide_crop_label(lab_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + lab_prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/loveda.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/loveda.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0626837b3121b854ba2fb92a32e839bb28c4b0 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/loveda.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +import mmcv + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert LoveDA dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='LoveDA folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'loveDA') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(out_dir) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + assert 'Train.zip' in os.listdir(dataset_path), \ + 'Train.zip is not in {}'.format(dataset_path) + assert 'Val.zip' in os.listdir(dataset_path), \ + 'Val.zip is not in {}'.format(dataset_path) + assert 'Test.zip' in os.listdir(dataset_path), \ + 'Test.zip is not in {}'.format(dataset_path) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset in ['Train', 'Val', 'Test']: + zip_file = zipfile.ZipFile( + os.path.join(dataset_path, dataset + '.zip')) + zip_file.extractall(tmp_dir) + data_type = dataset.lower() + for location in ['Rural', 'Urban']: + for image_type in ['images_png', 'masks_png']: + if image_type == 'images_png': + dst = osp.join(out_dir, 'img_dir', data_type) + else: + dst = osp.join(out_dir, 'ann_dir', data_type) + if dataset == 'Test' and image_type == 'masks_png': + continue + else: + src_dir = osp.join(tmp_dir, dataset, location, + image_type) + src_lst = os.listdir(src_dir) + for file in src_lst: + shutil.move(osp.join(src_dir, file), dst) + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/pascal_context.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/pascal_context.py new file mode 100644 index 0000000000000000000000000000000000000000..03b79d51869d5c675b750e2b901c820af907de0c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/pascal_context.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import mmcv +import numpy as np +from detail import Detail +from PIL import Image + +_mapping = np.sort( + np.array([ + 0, 2, 259, 260, 415, 324, 9, 258, 144, 18, 19, 22, 23, 397, 25, 284, + 158, 159, 416, 33, 162, 420, 454, 295, 296, 427, 44, 45, 46, 308, 59, + 440, 445, 31, 232, 65, 354, 424, 68, 326, 72, 458, 34, 207, 80, 355, + 85, 347, 220, 349, 360, 98, 187, 104, 105, 366, 189, 368, 113, 115 + ])) +_key = np.array(range(len(_mapping))).astype('uint8') + + +def generate_labels(img_id, detail, out_dir): + + def _class_to_index(mask, _mapping, _key): + # assert the values + values = np.unique(mask) + for i in range(len(values)): + assert (values[i] in _mapping) + index = np.digitize(mask.ravel(), _mapping, right=True) + return _key[index].reshape(mask.shape) + + mask = Image.fromarray( + _class_to_index(detail.getMask(img_id), _mapping=_mapping, _key=_key)) + filename = img_id['file_name'] + mask.save(osp.join(out_dir, filename.replace('jpg', 'png'))) + return osp.splitext(osp.basename(filename))[0] + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('json_path', help='annoation json filepath') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2010', 'SegmentationClassContext') + else: + out_dir = args.out_dir + json_path = args.json_path + mmcv.mkdir_or_exist(out_dir) + img_dir = osp.join(devkit_path, 'VOC2010', 'JPEGImages') + + train_detail = Detail(json_path, img_dir, 'train') + train_ids = train_detail.getImgs() + + val_detail = Detail(json_path, img_dir, 'val') + val_ids = val_detail.getImgs() + + mmcv.mkdir_or_exist( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext')) + + train_list = mmcv.track_progress( + partial(generate_labels, detail=train_detail, out_dir=out_dir), + train_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'train.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(train_list)) + + val_list = mmcv.track_progress( + partial(generate_labels, detail=val_detail, out_dir=out_dir), val_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'val.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(val_list)) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/potsdam.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/potsdam.py new file mode 100644 index 0000000000000000000000000000000000000000..87e67d5f17a9cc2e09852a7d498781225965ad7b --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/potsdam.py @@ -0,0 +1,157 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert potsdam dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='potsdam folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, args, to_label=False): + # Original image of Potsdam dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + clip_size = args.clip_size + stride_size = args.stride_size + + num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil( + (h - clip_size) / + stride_size) * stride_size + clip_size >= h else math.ceil( + (h - clip_size) / stride_size) + 1 + num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil( + (w - clip_size) / + stride_size) * stride_size + clip_size >= w else math.ceil( + (w - clip_size) / stride_size) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * clip_size + ymin = y * clip_size + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size, + np.zeros_like(xmin)) + ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size, + np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + clip_size, w), + np.minimum(ymin + clip_size, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + idx_i, idx_j = osp.basename(image_path).split('_')[2:4] + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join( + clip_save_dir, + f'{idx_i}_{idx_j}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + args = parse_args() + splits = { + 'train': [ + '2_10', '2_11', '2_12', '3_10', '3_11', '3_12', '4_10', '4_11', + '4_12', '5_10', '5_11', '5_12', '6_10', '6_11', '6_12', '6_7', + '6_8', '6_9', '7_10', '7_11', '7_12', '7_7', '7_8', '7_9' + ], + 'val': [ + '5_15', '6_15', '6_13', '3_13', '4_14', '6_14', '5_14', '2_13', + '4_15', '2_14', '5_13', '4_13', '3_14', '7_13' + ] + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'potsdam') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + for zipp in zipp_list: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if not len(src_path_list): + sub_tmp_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0]) + src_path_list = glob.glob(os.path.join(sub_tmp_dir, '*.tif')) + + prog_bar = mmcv.ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + idx_i, idx_j = osp.basename(src_path).split('_')[2:4] + data_type = 'train' if f'{idx_i}_{idx_j}' in splits[ + 'train'] else 'val' + if 'label' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/stare.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/stare.py new file mode 100644 index 0000000000000000000000000000000000000000..29b78c00037e4a2de40aa492490fdbac2c3f78f6 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/stare.py @@ -0,0 +1,166 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import gzip +import os +import os.path as osp +import tarfile +import tempfile + +import mmcv + +STARE_LEN = 20 +TRAINING_LEN = 10 + + +def un_gz(src, dst): + g_file = gzip.GzipFile(src) + with open(dst, 'wb+') as f: + f.write(g_file.read()) + g_file.close() + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert STARE dataset to mmsegmentation format') + parser.add_argument('image_path', help='the path of stare-images.tar') + parser.add_argument('labels_ah', help='the path of labels-ah.tar') + parser.add_argument('labels_vk', help='the path of labels-vk.tar') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + image_path = args.image_path + labels_ah = args.labels_ah + labels_vk = args.labels_vk + if args.out_dir is None: + out_dir = osp.join('data', 'STARE') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(out_dir) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting stare-images.tar...') + with tarfile.open(image_path) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + 'len(os.listdir(now_dir)) != {}'.format(STARE_LEN) + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-ah.tar...') + with tarfile.open(labels_ah) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + 'len(os.listdir(now_dir)) != {}'.format(STARE_LEN) + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a threshold + # to convert the nonstandard annotation imgs. The value divided by + # 128 equivalent to '1 if value >= 128 else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mmcv.mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-vk.tar...') + with tarfile.open(labels_vk) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + 'len(os.listdir(now_dir)) != {}'.format(STARE_LEN) + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/vaihingen.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/vaihingen.py new file mode 100644 index 0000000000000000000000000000000000000000..b025ae5a8982aa58efafbc6f10eeac2e359a1fda --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/vaihingen.py @@ -0,0 +1,155 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert vaihingen dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='vaihingen folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, to_label=False): + # Original image of Vaihingen dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + cs = args.clip_size + ss = args.stride_size + + num_rows = math.ceil((h - cs) / ss) if math.ceil( + (h - cs) / ss) * ss + cs >= h else math.ceil((h - cs) / ss) + 1 + num_cols = math.ceil((w - cs) / ss) if math.ceil( + (w - cs) / ss) * ss + cs >= w else math.ceil((w - cs) / ss) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * cs + ymin = y * cs + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + cs > w, w - xmin - cs, np.zeros_like(xmin)) + ymin_offset = np.where(ymin + cs > h, h - ymin - cs, np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + cs, w), + np.minimum(ymin + cs, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + area_idx = osp.basename(image_path).split('_')[3].strip('.tif') + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join(clip_save_dir, + f'{area_idx}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + splits = { + 'train': [ + 'area1', 'area11', 'area13', 'area15', 'area17', 'area21', + 'area23', 'area26', 'area28', 'area3', 'area30', 'area32', + 'area34', 'area37', 'area5', 'area7' + ], + 'val': [ + 'area6', 'area24', 'area35', 'area16', 'area14', 'area22', + 'area10', 'area4', 'area2', 'area20', 'area8', 'area31', 'area33', + 'area27', 'area38', 'area12', 'area29' + ], + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'vaihingen') + else: + out_dir = args.out_dir + + print('Making directories...') + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mmcv.mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for zipp in zipp_list: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen' in zipp: + src_path_list = glob.glob( + os.path.join(os.path.join(tmp_dir, 'top'), '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen_ground_truth_eroded_COMPLETE' in zipp: # noqa + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + # delete unused area9 ground truth + for area_ann in src_path_list: + if 'area9' in area_ann: + src_path_list.remove(area_ann) + prog_bar = mmcv.ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + area_idx = osp.basename(src_path).split('_')[3].strip('.tif') + data_type = 'train' if area_idx in splits['train'] else 'val' + if 'noBoundary' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + args = parse_args() + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/voc_aug.py b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/voc_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..1d42c2704703356b059873ad4904d9681ed9cce8 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/convert_datasets/voc_aug.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import mmcv +import numpy as np +from PIL import Image +from scipy.io import loadmat + +AUG_LEN = 10582 + + +def convert_mat(mat_file, in_dir, out_dir): + data = loadmat(osp.join(in_dir, mat_file)) + mask = data['GTcls'][0]['Segmentation'][0].astype(np.uint8) + seg_filename = osp.join(out_dir, mat_file.replace('.mat', '.png')) + Image.fromarray(mask).save(seg_filename, 'PNG') + + +def generate_aug_list(merged_list, excluded_list): + return list(set(merged_list) - set(excluded_list)) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('aug_path', help='pascal voc aug path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + aug_path = args.aug_path + nproc = args.nproc + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2012', 'SegmentationClassAug') + else: + out_dir = args.out_dir + mmcv.mkdir_or_exist(out_dir) + in_dir = osp.join(aug_path, 'dataset', 'cls') + + mmcv.track_parallel_progress( + partial(convert_mat, in_dir=in_dir, out_dir=out_dir), + list(mmcv.scandir(in_dir, suffix='.mat')), + nproc=nproc) + + full_aug_list = [] + with open(osp.join(aug_path, 'dataset', 'train.txt')) as f: + full_aug_list += [line.strip() for line in f] + with open(osp.join(aug_path, 'dataset', 'val.txt')) as f: + full_aug_list += [line.strip() for line in f] + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'train.txt')) as f: + ori_train_list = [line.strip() for line in f] + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'val.txt')) as f: + val_list = [line.strip() for line in f] + + aug_train_list = generate_aug_list(ori_train_list + full_aug_list, + val_list) + assert len(aug_train_list) == AUG_LEN, 'len(aug_train_list) != {}'.format( + AUG_LEN) + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'trainaug.txt'), 'w') as f: + f.writelines(line + '\n' for line in aug_train_list) + + aug_list = generate_aug_list(full_aug_list, ori_train_list + val_list) + assert len(aug_list) == AUG_LEN - len( + ori_train_list), 'len(aug_list) != {}'.format(AUG_LEN - + len(ori_train_list)) + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', 'aug.txt'), + 'w') as f: + f.writelines(line + '\n' for line in aug_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/deploy_test.py b/EgoHOS/raw/script/mmsegmentation/tools/deploy_test.py new file mode 100644 index 0000000000000000000000000000000000000000..eca54304762f3ad50f35d7d72180abf54d66b2e1 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/deploy_test.py @@ -0,0 +1,338 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import shutil +import warnings +from typing import Any, Iterable + +import mmcv +import numpy as np +import torch +from mmcv.parallel import MMDataParallel +from mmcv.runner import get_dist_info +from mmcv.utils import DictAction + +from mmseg.apis import single_gpu_test +from mmseg.datasets import build_dataloader, build_dataset +from mmseg.models.segmentors.base import BaseSegmentor +from mmseg.ops import resize + + +class ONNXRuntimeSegmentor(BaseSegmentor): + + def __init__(self, onnx_file: str, cfg: Any, device_id: int): + super(ONNXRuntimeSegmentor, self).__init__() + import onnxruntime as ort + + # get the custom op path + ort_custom_op_path = '' + try: + from mmcv.ops import get_onnxruntime_op_path + ort_custom_op_path = get_onnxruntime_op_path() + except (ImportError, ModuleNotFoundError): + warnings.warn('If input model has custom op from mmcv, \ + you may have to build mmcv with ONNXRuntime from source.') + session_options = ort.SessionOptions() + # register custom op for onnxruntime + if osp.exists(ort_custom_op_path): + session_options.register_custom_ops_library(ort_custom_op_path) + sess = ort.InferenceSession(onnx_file, session_options) + providers = ['CPUExecutionProvider'] + options = [{}] + is_cuda_available = ort.get_device() == 'GPU' + if is_cuda_available: + providers.insert(0, 'CUDAExecutionProvider') + options.insert(0, {'device_id': device_id}) + + sess.set_providers(providers, options) + + self.sess = sess + self.device_id = device_id + self.io_binding = sess.io_binding() + self.output_names = [_.name for _ in sess.get_outputs()] + for name in self.output_names: + self.io_binding.bind_output(name) + self.cfg = cfg + self.test_mode = cfg.model.test_cfg.mode + self.is_cuda_available = is_cuda_available + + def extract_feat(self, imgs): + raise NotImplementedError('This method is not implemented.') + + def encode_decode(self, img, img_metas): + raise NotImplementedError('This method is not implemented.') + + def forward_train(self, imgs, img_metas, **kwargs): + raise NotImplementedError('This method is not implemented.') + + def simple_test(self, img: torch.Tensor, img_meta: Iterable, + **kwargs) -> list: + if not self.is_cuda_available: + img = img.detach().cpu() + elif self.device_id >= 0: + img = img.cuda(self.device_id) + device_type = img.device.type + self.io_binding.bind_input( + name='input', + device_type=device_type, + device_id=self.device_id, + element_type=np.float32, + shape=img.shape, + buffer_ptr=img.data_ptr()) + self.sess.run_with_iobinding(self.io_binding) + seg_pred = self.io_binding.copy_outputs_to_cpu()[0] + # whole might support dynamic reshape + ori_shape = img_meta[0]['ori_shape'] + if not (ori_shape[0] == seg_pred.shape[-2] + and ori_shape[1] == seg_pred.shape[-1]): + seg_pred = torch.from_numpy(seg_pred).float() + seg_pred = resize( + seg_pred, size=tuple(ori_shape[:2]), mode='nearest') + seg_pred = seg_pred.long().detach().cpu().numpy() + seg_pred = seg_pred[0] + seg_pred = list(seg_pred) + return seg_pred + + def aug_test(self, imgs, img_metas, **kwargs): + raise NotImplementedError('This method is not implemented.') + + +class TensorRTSegmentor(BaseSegmentor): + + def __init__(self, trt_file: str, cfg: Any, device_id: int): + super(TensorRTSegmentor, self).__init__() + from mmcv.tensorrt import TRTWraper, load_tensorrt_plugin + try: + load_tensorrt_plugin() + except (ImportError, ModuleNotFoundError): + warnings.warn('If input model has custom op from mmcv, \ + you may have to build mmcv with TensorRT from source.') + model = TRTWraper( + trt_file, input_names=['input'], output_names=['output']) + + self.model = model + self.device_id = device_id + self.cfg = cfg + self.test_mode = cfg.model.test_cfg.mode + + def extract_feat(self, imgs): + raise NotImplementedError('This method is not implemented.') + + def encode_decode(self, img, img_metas): + raise NotImplementedError('This method is not implemented.') + + def forward_train(self, imgs, img_metas, **kwargs): + raise NotImplementedError('This method is not implemented.') + + def simple_test(self, img: torch.Tensor, img_meta: Iterable, + **kwargs) -> list: + with torch.cuda.device(self.device_id), torch.no_grad(): + seg_pred = self.model({'input': img})['output'] + seg_pred = seg_pred.detach().cpu().numpy() + # whole might support dynamic reshape + ori_shape = img_meta[0]['ori_shape'] + if not (ori_shape[0] == seg_pred.shape[-2] + and ori_shape[1] == seg_pred.shape[-1]): + seg_pred = torch.from_numpy(seg_pred).float() + seg_pred = resize( + seg_pred, size=tuple(ori_shape[:2]), mode='nearest') + seg_pred = seg_pred.long().detach().cpu().numpy() + seg_pred = seg_pred[0] + seg_pred = list(seg_pred) + return seg_pred + + def aug_test(self, imgs, img_metas, **kwargs): + raise NotImplementedError('This method is not implemented.') + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description='mmseg backend test (and eval)') + parser.add_argument('config', help='test config file path') + parser.add_argument('model', help='Input model file') + parser.add_argument( + '--backend', + help='Backend of the model.', + choices=['onnxruntime', 'tensorrt']) + parser.add_argument('--out', help='output result file in pickle format') + parser.add_argument( + '--format-only', + action='store_true', + help='Format the output results without perform evaluation. It is' + 'useful when you want to format the result to a specific format and ' + 'submit it to the test server') + parser.add_argument( + '--eval', + type=str, + nargs='+', + help='evaluation metrics, which depends on the dataset, e.g., "mIoU"' + ' for generic datasets, and "cityscapes" for Cityscapes') + parser.add_argument('--show', action='store_true', help='show results') + parser.add_argument( + '--show-dir', help='directory where painted images will be saved') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--eval-options', + nargs='+', + action=DictAction, + help='custom options for evaluation') + parser.add_argument( + '--opacity', + type=float, + default=0.5, + help='Opacity of painted segmentation map. In (0, 1] range.') + parser.add_argument('--local_rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + + assert args.out or args.eval or args.format_only or args.show \ + or args.show_dir, \ + ('Please specify at least one operation (save/eval/format/show the ' + 'results / save the results) with the argument "--out", "--eval"' + ', "--format-only", "--show" or "--show-dir"') + + if args.eval and args.format_only: + raise ValueError('--eval and --format_only cannot be both specified') + + if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): + raise ValueError('The output file must be a pkl file.') + + cfg = mmcv.Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + cfg.model.pretrained = None + cfg.data.test.test_mode = True + + # init distributed env first, since logger depends on the dist info. + distributed = False + + # build the dataloader + # TODO: support multiple images per gpu (only minor changes are needed) + dataset = build_dataset(cfg.data.test) + data_loader = build_dataloader( + dataset, + samples_per_gpu=1, + workers_per_gpu=cfg.data.workers_per_gpu, + dist=distributed, + shuffle=False) + + # load onnx config and meta + cfg.model.train_cfg = None + + if args.backend == 'onnxruntime': + model = ONNXRuntimeSegmentor(args.model, cfg=cfg, device_id=0) + elif args.backend == 'tensorrt': + model = TensorRTSegmentor(args.model, cfg=cfg, device_id=0) + + model.CLASSES = dataset.CLASSES + model.PALETTE = dataset.PALETTE + + # clean gpu memory when starting a new evaluation. + torch.cuda.empty_cache() + eval_kwargs = {} if args.eval_options is None else args.eval_options + + # Deprecated + efficient_test = eval_kwargs.get('efficient_test', False) + if efficient_test: + warnings.warn( + '``efficient_test=True`` does not have effect in tools/test.py, ' + 'the evaluation and format results are CPU memory efficient by ' + 'default') + + eval_on_format_results = ( + args.eval is not None and 'cityscapes' in args.eval) + if eval_on_format_results: + assert len(args.eval) == 1, 'eval on format results is not ' \ + 'applicable for metrics other than ' \ + 'cityscapes' + if args.format_only or eval_on_format_results: + if 'imgfile_prefix' in eval_kwargs: + tmpdir = eval_kwargs['imgfile_prefix'] + else: + tmpdir = '.format_cityscapes' + eval_kwargs.setdefault('imgfile_prefix', tmpdir) + mmcv.mkdir_or_exist(tmpdir) + else: + tmpdir = None + + model = MMDataParallel(model, device_ids=[0]) + results = single_gpu_test( + model, + data_loader, + args.show, + args.show_dir, + False, + args.opacity, + pre_eval=args.eval is not None and not eval_on_format_results, + format_only=args.format_only or eval_on_format_results, + format_args=eval_kwargs) + + rank, _ = get_dist_info() + if rank == 0: + if args.out: + warnings.warn( + 'The behavior of ``args.out`` has been changed since MMSeg ' + 'v0.16, the pickled outputs could be seg map as type of ' + 'np.array, pre-eval results or file paths for ' + '``dataset.format_results()``.') + print(f'\nwriting results to {args.out}') + mmcv.dump(results, args.out) + if args.eval: + dataset.evaluate(results, args.eval, **eval_kwargs) + if tmpdir is not None and eval_on_format_results: + # remove tmp dir when cityscapes evaluation + shutil.rmtree(tmpdir) + + +if __name__ == '__main__': + main() + + # Following strings of text style are from colorama package + bright_style, reset_style = '\x1b[1m', '\x1b[0m' + red_text, blue_text = '\x1b[31m', '\x1b[34m' + white_background = '\x1b[107m' + + msg = white_background + bright_style + red_text + msg += 'DeprecationWarning: This tool will be deprecated in future. ' + msg += blue_text + 'Welcome to use the unified model deployment toolbox ' + msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy' + msg += reset_style + warnings.warn(msg) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/dist_test.sh b/EgoHOS/raw/script/mmsegmentation/tools/dist_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..89711fd5c02cfc1f0386e5354506d4b74ecac251 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/dist_test.sh @@ -0,0 +1,20 @@ +CONFIG=$1 +CHECKPOINT=$2 +GPUS=$3 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/test.py \ + $CONFIG \ + $CHECKPOINT \ + --launcher pytorch \ + ${@:4} diff --git a/EgoHOS/raw/script/mmsegmentation/tools/dist_train.sh b/EgoHOS/raw/script/mmsegmentation/tools/dist_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..a857df78788edb8841b6f67d74dd0e6cfb77d8ab --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/dist_train.sh @@ -0,0 +1,17 @@ +CONFIG=$1 +GPUS=$2 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/train.py \ + $CONFIG \ + --launcher pytorch ${@:3} diff --git a/EgoHOS/raw/script/mmsegmentation/tools/get_flops.py b/EgoHOS/raw/script/mmsegmentation/tools/get_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..e30c36fdfc603bb247047088660a4966b5e2330b --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/get_flops.py @@ -0,0 +1,60 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse + +from mmcv import Config +from mmcv.cnn import get_model_complexity_info + +from mmseg.models import build_segmentor + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Get the FLOPs of a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[2048, 1024], + help='input image size') + args = parser.parse_args() + return args + + +def main(): + + args = parse_args() + + if len(args.shape) == 1: + input_shape = (3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = (3, ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + + cfg = Config.fromfile(args.config) + cfg.model.pretrained = None + model = build_segmentor( + cfg.model, + train_cfg=cfg.get('train_cfg'), + test_cfg=cfg.get('test_cfg')).cuda() + model.eval() + + if hasattr(model, 'forward_dummy'): + model.forward = model.forward_dummy + else: + raise NotImplementedError( + 'FLOPs counter is currently not currently supported with {}'. + format(model.__class__.__name__)) + + flops, params = get_model_complexity_info(model, input_shape) + split_line = '=' * 30 + print('{0}\nInput shape: {1}\nFlops: {2}\nParams: {3}\n{0}'.format( + split_line, input_shape, flops, params)) + print('!!!Please be cautious if you use the results in papers. ' + 'You may need to check if all ops are supported and verify that the ' + 'flops computation is correct.') + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/beit2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/beit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..d23cfdb0b31a6ccef3c9a48d8509c843a6bc0913 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/beit2mmseg.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_beit(ckpt): + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('patch_embed'): + new_key = k.replace('patch_embed.proj', 'patch_embed.projection') + new_ckpt[new_key] = v + if k.startswith('blocks'): + new_key = k.replace('blocks', 'layers') + if 'norm' in new_key: + new_key = new_key.replace('norm', 'ln') + elif 'mlp.fc1' in new_key: + new_key = new_key.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in new_key: + new_key = new_key.replace('mlp.fc2', 'ffn.layers.1') + new_ckpt[new_key] = v + else: + new_key = k + new_ckpt[new_key] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained beit models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_beit(state_dict) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/mit2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/mit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..2eff1f7b7a3381b2a712b9862de0d9d9f781e609 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/mit2mmseg.py @@ -0,0 +1,82 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_mit(ckpt): + new_ckpt = OrderedDict() + # Process the concat between q linear weights and kv linear weights + for k, v in ckpt.items(): + if k.startswith('head'): + continue + # patch embedding conversion + elif k.startswith('patch_embed'): + stage_i = int(k.split('.')[0].replace('patch_embed', '')) + new_k = k.replace(f'patch_embed{stage_i}', f'layers.{stage_i-1}.0') + new_v = v + if 'proj.' in new_k: + new_k = new_k.replace('proj.', 'projection.') + # transformer encoder layer conversion + elif k.startswith('block'): + stage_i = int(k.split('.')[0].replace('block', '')) + new_k = k.replace(f'block{stage_i}', f'layers.{stage_i-1}.1') + new_v = v + if 'attn.q.' in new_k: + sub_item_k = k.replace('q.', 'kv.') + new_k = new_k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[sub_item_k]], dim=0) + elif 'attn.kv.' in new_k: + continue + elif 'attn.proj.' in new_k: + new_k = new_k.replace('proj.', 'attn.out_proj.') + elif 'attn.sr.' in new_k: + new_k = new_k.replace('sr.', 'sr.') + elif 'mlp.' in new_k: + string = f'{new_k}-' + new_k = new_k.replace('mlp.', 'ffn.layers.') + if 'fc1.weight' in new_k or 'fc2.weight' in new_k: + new_v = v.reshape((*v.shape, 1, 1)) + new_k = new_k.replace('fc1.', '0.') + new_k = new_k.replace('dwconv.dwconv.', '1.') + new_k = new_k.replace('fc2.', '4.') + string += f'{new_k} {v.shape}-{new_v.shape}' + # norm layer conversion + elif k.startswith('norm'): + stage_i = int(k.split('.')[0].replace('norm', '')) + new_k = k.replace(f'norm{stage_i}', f'layers.{stage_i-1}.2') + new_v = v + else: + new_k = k + new_v = v + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained segformer to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_mit(state_dict) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/stdc2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/stdc2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..9241f86a15a59a2df1a1d12a40930b58952c207d --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/stdc2mmseg.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_stdc(ckpt, stdc_type): + new_state_dict = {} + if stdc_type == 'STDC1': + stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1'] + else: + stage_lst = [ + '0', '1', '2.0', '2.1', '2.2', '2.3', '3.0', '3.1', '3.2', '3.3', + '3.4', '4.0', '4.1', '4.2' + ] + for k, v in ckpt.items(): + ori_k = k + flag = False + if 'cp.' in k: + k = k.replace('cp.', '') + if 'features.' in k: + num_layer = int(k.split('.')[1]) + feature_key_lst = 'features.' + str(num_layer) + '.' + stages_key_lst = 'stages.' + stage_lst[num_layer] + '.' + k = k.replace(feature_key_lst, stages_key_lst) + flag = True + if 'conv_list' in k: + k = k.replace('conv_list', 'layers') + flag = True + if 'avd_layer.' in k: + if 'avd_layer.0' in k: + k = k.replace('avd_layer.0', 'downsample.conv') + elif 'avd_layer.1' in k: + k = k.replace('avd_layer.1', 'downsample.bn') + flag = True + if flag: + new_state_dict[k] = ckpt[ori_k] + + return new_state_dict + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained STDC1/2 to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('type', help='model type: STDC1 or STDC2') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + + assert args.type in ['STDC1', + 'STDC2'], 'STD type should be STDC1 or STDC2!' + weight = convert_stdc(state_dict, args.type) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/swin2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/swin2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..03b24ceaa4e737217803ae7651aaab52a7cc3a38 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/swin2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_swin(ckpt): + new_ckpt = OrderedDict() + + def correct_unfold_reduction_order(x): + out_channel, in_channel = x.shape + x = x.reshape(out_channel, 4, in_channel // 4) + x = x[:, [0, 2, 1, 3], :].transpose(1, + 2).reshape(out_channel, in_channel) + return x + + def correct_unfold_norm_order(x): + in_channel = x.shape[0] + x = x.reshape(4, in_channel // 4) + x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel) + return x + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + elif k.startswith('layers'): + new_v = v + if 'attn.' in k: + new_k = k.replace('attn.', 'attn.w_msa.') + elif 'mlp.' in k: + if 'mlp.fc1.' in k: + new_k = k.replace('mlp.fc1.', 'ffn.layers.0.0.') + elif 'mlp.fc2.' in k: + new_k = k.replace('mlp.fc2.', 'ffn.layers.1.') + else: + new_k = k.replace('mlp.', 'ffn.') + elif 'downsample' in k: + new_k = k + if 'reduction.' in k: + new_v = correct_unfold_reduction_order(v) + elif 'norm.' in k: + new_v = correct_unfold_norm_order(v) + else: + new_k = k + new_k = new_k.replace('layers', 'stages', 1) + elif k.startswith('patch_embed'): + new_v = v + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + else: + new_v = v + new_k = k + + new_ckpt[new_k] = new_v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained swin models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_swin(state_dict) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/twins2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/twins2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..ab64aa526e89f934d3765e74e9a1dd98a41a073c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/twins2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_twins(args, ckpt): + + new_ckpt = OrderedDict() + + for k, v in list(ckpt.items()): + new_v = v + if k.startswith('head'): + continue + elif k.startswith('patch_embeds'): + if 'proj.' in k: + new_k = k.replace('proj.', 'projection.') + else: + new_k = k + elif k.startswith('blocks'): + # Union + if 'attn.q.' in k: + new_k = k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[k.replace('attn.q.', 'attn.kv.')]], + dim=0) + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + # Only pcpvt + elif args.model == 'pcpvt': + if 'attn.proj.' in k: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + + # Only svt + else: + if 'attn.proj.' in k: + k_lst = k.split('.') + if int(k_lst[2]) % 2 == 1: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + elif k.startswith('pos_block'): + new_k = k.replace('pos_block', 'position_encodings') + if 'proj.0.' in new_k: + new_k = new_k.replace('proj.0.', 'proj.') + else: + new_k = k + if 'attn.kv.' not in k: + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('model', help='model: pcpvt or svt') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + weight = convert_twins(args, state_dict) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vit2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..bc18ebed88485b7c92fdc78f76165db8cb295df1 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vit2mmseg.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmcv +import torch +from mmcv.runner import CheckpointLoader + + +def convert_vit(ckpt): + + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + if k.startswith('norm'): + new_k = k.replace('norm.', 'ln1.') + elif k.startswith('patch_embed'): + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + elif k.startswith('blocks'): + if 'norm' in k: + new_k = k.replace('norm', 'ln') + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + elif 'attn.qkv' in k: + new_k = k.replace('attn.qkv.', 'attn.attn.in_proj_') + elif 'attn.proj' in k: + new_k = k.replace('attn.proj', 'attn.attn.out_proj') + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + else: + new_k = k + new_ckpt[new_k] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_vit(state_dict) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vitjax2mmseg.py b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vitjax2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..585f408368aea77e1beacaf9cf83c5c9c415de98 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/model_converters/vitjax2mmseg.py @@ -0,0 +1,123 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmcv +import numpy as np +import torch + + +def vit_jax_to_torch(jax_weights, num_layer=12): + torch_weights = dict() + + # patch embedding + conv_filters = jax_weights['embedding/kernel'] + conv_filters = conv_filters.permute(3, 2, 0, 1) + torch_weights['patch_embed.projection.weight'] = conv_filters + torch_weights['patch_embed.projection.bias'] = jax_weights[ + 'embedding/bias'] + + # pos embedding + torch_weights['pos_embed'] = jax_weights[ + 'Transformer/posembed_input/pos_embedding'] + + # cls token + torch_weights['cls_token'] = jax_weights['cls'] + + # head + torch_weights['ln1.weight'] = jax_weights['Transformer/encoder_norm/scale'] + torch_weights['ln1.bias'] = jax_weights['Transformer/encoder_norm/bias'] + + # transformer blocks + for i in range(num_layer): + jax_block = f'Transformer/encoderblock_{i}' + torch_block = f'layers.{i}' + + # attention norm + torch_weights[f'{torch_block}.ln1.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_0/scale'] + torch_weights[f'{torch_block}.ln1.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_0/bias'] + + # attention + query_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/kernel'] + query_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/bias'] + key_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/kernel'] + key_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/bias'] + value_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/kernel'] + value_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/bias'] + + qkv_weight = torch.from_numpy( + np.stack((query_weight, key_weight, value_weight), 1)) + qkv_weight = torch.flatten(qkv_weight, start_dim=1) + qkv_bias = torch.from_numpy( + np.stack((query_bias, key_bias, value_bias), 0)) + qkv_bias = torch.flatten(qkv_bias, start_dim=0) + + torch_weights[f'{torch_block}.attn.attn.in_proj_weight'] = qkv_weight + torch_weights[f'{torch_block}.attn.attn.in_proj_bias'] = qkv_bias + to_out_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/kernel'] + to_out_weight = torch.flatten(to_out_weight, start_dim=0, end_dim=1) + torch_weights[ + f'{torch_block}.attn.attn.out_proj.weight'] = to_out_weight + torch_weights[f'{torch_block}.attn.attn.out_proj.bias'] = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/bias'] + + # mlp norm + torch_weights[f'{torch_block}.ln2.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_2/scale'] + torch_weights[f'{torch_block}.ln2.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_2/bias'] + + # mlp + torch_weights[f'{torch_block}.ffn.layers.0.0.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/kernel'] + torch_weights[f'{torch_block}.ffn.layers.0.0.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/bias'] + torch_weights[f'{torch_block}.ffn.layers.1.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/kernel'] + torch_weights[f'{torch_block}.ffn.layers.1.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/bias'] + + # transpose weights + for k, v in torch_weights.items(): + if 'weight' in k and 'patch_embed' not in k and 'ln' not in k: + v = v.permute(1, 0) + torch_weights[k] = v + + return torch_weights + + +def main(): + # stole refactoring code from Robin Strudel, thanks + parser = argparse.ArgumentParser( + description='Convert keys from jax official pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + jax_weights = np.load(args.src) + jax_weights_tensor = {} + for key in jax_weights.files: + value = torch.from_numpy(jax_weights[key]) + jax_weights_tensor[key] = value + if 'L_16-i21k' in args.src: + num_layer = 24 + else: + num_layer = 12 + torch_weights = vit_jax_to_torch(jax_weights_tensor, num_layer) + mmcv.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(torch_weights, args.dst) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/onnx2tensorrt.py b/EgoHOS/raw/script/mmsegmentation/tools/onnx2tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..0f60dce20d77d4642ad349ba2250d368237c9962 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/onnx2tensorrt.py @@ -0,0 +1,289 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import warnings +from typing import Iterable, Optional, Union + +import matplotlib.pyplot as plt +import mmcv +import numpy as np +import onnxruntime as ort +import torch +from mmcv.ops import get_onnxruntime_op_path +from mmcv.tensorrt import (TRTWraper, is_tensorrt_plugin_loaded, onnx2trt, + save_trt_engine) + +from mmseg.apis.inference import LoadImage +from mmseg.datasets import DATASETS +from mmseg.datasets.pipelines import Compose + + +def get_GiB(x: int): + """return x GiB.""" + return x * (1 << 30) + + +def _prepare_input_img(img_path: str, + test_pipeline: Iterable[dict], + shape: Optional[Iterable] = None, + rescale_shape: Optional[Iterable] = None) -> dict: + # build the data pipeline + if shape is not None: + test_pipeline[1]['img_scale'] = (shape[1], shape[0]) + test_pipeline[1]['transforms'][0]['keep_ratio'] = False + test_pipeline = [LoadImage()] + test_pipeline[1:] + test_pipeline = Compose(test_pipeline) + # prepare data + data = dict(img=img_path) + data = test_pipeline(data) + imgs = data['img'] + img_metas = [i.data for i in data['img_metas']] + + if rescale_shape is not None: + for img_meta in img_metas: + img_meta['ori_shape'] = tuple(rescale_shape) + (3, ) + + mm_inputs = {'imgs': imgs, 'img_metas': img_metas} + + return mm_inputs + + +def _update_input_img(img_list: Iterable, img_meta_list: Iterable): + # update img and its meta list + N = img_list[0].size(0) + img_meta = img_meta_list[0][0] + img_shape = img_meta['img_shape'] + ori_shape = img_meta['ori_shape'] + pad_shape = img_meta['pad_shape'] + new_img_meta_list = [[{ + 'img_shape': + img_shape, + 'ori_shape': + ori_shape, + 'pad_shape': + pad_shape, + 'filename': + img_meta['filename'], + 'scale_factor': + (img_shape[1] / ori_shape[1], img_shape[0] / ori_shape[0]) * 2, + 'flip': + False, + } for _ in range(N)]] + + return img_list, new_img_meta_list + + +def show_result_pyplot(img: Union[str, np.ndarray], + result: np.ndarray, + palette: Optional[Iterable] = None, + fig_size: Iterable[int] = (15, 10), + opacity: float = 0.5, + title: str = '', + block: bool = True): + img = mmcv.imread(img) + img = img.copy() + seg = result[0] + seg = mmcv.imresize(seg, img.shape[:2][::-1]) + palette = np.array(palette) + assert palette.shape[1] == 3 + assert len(palette.shape) == 2 + assert 0 < opacity <= 1.0 + color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) + for label, color in enumerate(palette): + color_seg[seg == label, :] = color + # convert to BGR + color_seg = color_seg[..., ::-1] + + img = img * (1 - opacity) + color_seg * opacity + img = img.astype(np.uint8) + + plt.figure(figsize=fig_size) + plt.imshow(mmcv.bgr2rgb(img)) + plt.title(title) + plt.tight_layout() + plt.show(block=block) + + +def onnx2tensorrt(onnx_file: str, + trt_file: str, + config: dict, + input_config: dict, + fp16: bool = False, + verify: bool = False, + show: bool = False, + dataset: str = 'CityscapesDataset', + workspace_size: int = 1, + verbose: bool = False): + import tensorrt as trt + min_shape = input_config['min_shape'] + max_shape = input_config['max_shape'] + # create trt engine and wrapper + opt_shape_dict = {'input': [min_shape, min_shape, max_shape]} + max_workspace_size = get_GiB(workspace_size) + trt_engine = onnx2trt( + onnx_file, + opt_shape_dict, + log_level=trt.Logger.VERBOSE if verbose else trt.Logger.ERROR, + fp16_mode=fp16, + max_workspace_size=max_workspace_size) + save_dir, _ = osp.split(trt_file) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + save_trt_engine(trt_engine, trt_file) + print(f'Successfully created TensorRT engine: {trt_file}') + + if verify: + inputs = _prepare_input_img( + input_config['input_path'], + config.data.test.pipeline, + shape=min_shape[2:]) + + imgs = inputs['imgs'] + img_metas = inputs['img_metas'] + img_list = [img[None, :] for img in imgs] + img_meta_list = [[img_meta] for img_meta in img_metas] + # update img_meta + img_list, img_meta_list = _update_input_img(img_list, img_meta_list) + + if max_shape[0] > 1: + # concate flip image for batch test + flip_img_list = [_.flip(-1) for _ in img_list] + img_list = [ + torch.cat((ori_img, flip_img), 0) + for ori_img, flip_img in zip(img_list, flip_img_list) + ] + + # Get results from ONNXRuntime + ort_custom_op_path = get_onnxruntime_op_path() + session_options = ort.SessionOptions() + if osp.exists(ort_custom_op_path): + session_options.register_custom_ops_library(ort_custom_op_path) + sess = ort.InferenceSession(onnx_file, session_options) + sess.set_providers(['CPUExecutionProvider'], [{}]) # use cpu mode + onnx_output = sess.run(['output'], + {'input': img_list[0].detach().numpy()})[0][0] + + # Get results from TensorRT + trt_model = TRTWraper(trt_file, ['input'], ['output']) + with torch.no_grad(): + trt_outputs = trt_model({'input': img_list[0].contiguous().cuda()}) + trt_output = trt_outputs['output'][0].cpu().detach().numpy() + + if show: + dataset = DATASETS.get(dataset) + assert dataset is not None + palette = dataset.PALETTE + + show_result_pyplot( + input_config['input_path'], + (onnx_output[0].astype(np.uint8), ), + palette=palette, + title='ONNXRuntime', + block=False) + show_result_pyplot( + input_config['input_path'], (trt_output[0].astype(np.uint8), ), + palette=palette, + title='TensorRT') + + np.testing.assert_allclose( + onnx_output, trt_output, rtol=1e-03, atol=1e-05) + print('TensorRT and ONNXRuntime output all close.') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert MMSegmentation models from ONNX to TensorRT') + parser.add_argument('config', help='Config file of the model') + parser.add_argument('model', help='Path to the input ONNX model') + parser.add_argument( + '--trt-file', type=str, help='Path to the output TensorRT engine') + parser.add_argument( + '--max-shape', + type=int, + nargs=4, + default=[1, 3, 400, 600], + help='Maximum shape of model input.') + parser.add_argument( + '--min-shape', + type=int, + nargs=4, + default=[1, 3, 400, 600], + help='Minimum shape of model input.') + parser.add_argument('--fp16', action='store_true', help='Enable fp16 mode') + parser.add_argument( + '--workspace-size', + type=int, + default=1, + help='Max workspace size in GiB') + parser.add_argument( + '--input-img', type=str, default='', help='Image for test') + parser.add_argument( + '--show', action='store_true', help='Whether to show output results') + parser.add_argument( + '--dataset', + type=str, + default='CityscapesDataset', + help='Dataset name') + parser.add_argument( + '--verify', + action='store_true', + help='Verify the outputs of ONNXRuntime and TensorRT') + parser.add_argument( + '--verbose', + action='store_true', + help='Whether to verbose logging messages while creating \ + TensorRT engine.') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + + assert is_tensorrt_plugin_loaded(), 'TensorRT plugin should be compiled.' + args = parse_args() + + if not args.input_img: + args.input_img = osp.join(osp.dirname(__file__), '../demo/demo.png') + + # check arguments + assert osp.exists(args.config), 'Config {} not found.'.format(args.config) + assert osp.exists(args.model), \ + 'ONNX model {} not found.'.format(args.model) + assert args.workspace_size >= 0, 'Workspace size less than 0.' + assert DATASETS.get(args.dataset) is not None, \ + 'Dataset {} does not found.'.format(args.dataset) + for max_value, min_value in zip(args.max_shape, args.min_shape): + assert max_value >= min_value, \ + 'max_shape should be larger than min shape' + + input_config = { + 'min_shape': args.min_shape, + 'max_shape': args.max_shape, + 'input_path': args.input_img + } + + cfg = mmcv.Config.fromfile(args.config) + onnx2tensorrt( + args.model, + args.trt_file, + cfg, + input_config, + fp16=args.fp16, + verify=args.verify, + show=args.show, + dataset=args.dataset, + workspace_size=args.workspace_size, + verbose=args.verbose) + + # Following strings of text style are from colorama package + bright_style, reset_style = '\x1b[1m', '\x1b[0m' + red_text, blue_text = '\x1b[31m', '\x1b[34m' + white_background = '\x1b[107m' + + msg = white_background + bright_style + red_text + msg += 'DeprecationWarning: This tool will be deprecated in future. ' + msg += blue_text + 'Welcome to use the unified model deployment toolbox ' + msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy' + msg += reset_style + warnings.warn(msg) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/print_config.py b/EgoHOS/raw/script/mmsegmentation/tools/print_config.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9c08dd968535e14cd653b7fb9562e51bb482cf --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/print_config.py @@ -0,0 +1,69 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import warnings + +from mmcv import Config, DictAction + +from mmseg.apis import init_segmentor + + +def parse_args(): + parser = argparse.ArgumentParser(description='Print the whole config') + parser.add_argument('config', help='config file path') + parser.add_argument( + '--graph', action='store_true', help='print the models graph') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options, ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + print(f'Config:\n{cfg.pretty_text}') + # dump config + cfg.dump('example.py') + # dump models graph + if args.graph: + model = init_segmentor(args.config, device='cpu') + print(f'Model graph:\n{str(model)}') + with open('example-graph.txt', 'w') as f: + f.writelines(str(model)) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/publish_model.py b/EgoHOS/raw/script/mmsegmentation/tools/publish_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e2660578af83fe99954cff32729a0e0c2d75e005 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/publish_model.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import subprocess + +import torch + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Process a checkpoint to be published') + parser.add_argument('in_file', help='input checkpoint filename') + parser.add_argument('out_file', help='output checkpoint filename') + args = parser.parse_args() + return args + + +def process_checkpoint(in_file, out_file): + checkpoint = torch.load(in_file, map_location='cpu') + # remove optimizer for smaller file size + if 'optimizer' in checkpoint: + del checkpoint['optimizer'] + # if it is necessary to remove some sensitive data in checkpoint['meta'], + # add the code here. + torch.save(checkpoint, out_file) + sha = subprocess.check_output(['sha256sum', out_file]).decode() + final_file = out_file.rstrip('.pth') + '-{}.pth'.format(sha[:8]) + subprocess.Popen(['mv', out_file, final_file]) + + +def main(): + args = parse_args() + process_checkpoint(args.in_file, args.out_file) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/pytorch2onnx.py b/EgoHOS/raw/script/mmsegmentation/tools/pytorch2onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..060d1873ea0e5c43cd503ac89505bb168c859398 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/pytorch2onnx.py @@ -0,0 +1,405 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import warnings +from functools import partial + +import mmcv +import numpy as np +import onnxruntime as rt +import torch +import torch._C +import torch.serialization +from mmcv import DictAction +from mmcv.onnx import register_extra_symbolics +from mmcv.runner import load_checkpoint +from torch import nn + +from mmseg.apis import show_result_pyplot +from mmseg.apis.inference import LoadImage +from mmseg.datasets.pipelines import Compose +from mmseg.models import build_segmentor +from mmseg.ops import resize + +torch.manual_seed(3) + + +def _convert_batchnorm(module): + module_output = module + if isinstance(module, torch.nn.SyncBatchNorm): + module_output = torch.nn.BatchNorm2d(module.num_features, module.eps, + module.momentum, module.affine, + module.track_running_stats) + if module.affine: + module_output.weight.data = module.weight.data.clone().detach() + module_output.bias.data = module.bias.data.clone().detach() + # keep requires_grad unchanged + module_output.weight.requires_grad = module.weight.requires_grad + module_output.bias.requires_grad = module.bias.requires_grad + module_output.running_mean = module.running_mean + module_output.running_var = module.running_var + module_output.num_batches_tracked = module.num_batches_tracked + for name, child in module.named_children(): + module_output.add_module(name, _convert_batchnorm(child)) + del module + return module_output + + +def _demo_mm_inputs(input_shape, num_classes): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + rng = np.random.RandomState(0) + imgs = rng.rand(*input_shape) + segs = rng.randint( + low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8) + img_metas = [{ + 'img_shape': (H, W, C), + 'ori_shape': (H, W, C), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + } for _ in range(N)] + mm_inputs = { + 'imgs': torch.FloatTensor(imgs).requires_grad_(True), + 'img_metas': img_metas, + 'gt_semantic_seg': torch.LongTensor(segs) + } + return mm_inputs + + +def _prepare_input_img(img_path, + test_pipeline, + shape=None, + rescale_shape=None): + # build the data pipeline + if shape is not None: + test_pipeline[1]['img_scale'] = (shape[1], shape[0]) + test_pipeline[1]['transforms'][0]['keep_ratio'] = False + test_pipeline = [LoadImage()] + test_pipeline[1:] + test_pipeline = Compose(test_pipeline) + # prepare data + data = dict(img=img_path) + data = test_pipeline(data) + imgs = data['img'] + img_metas = [i.data for i in data['img_metas']] + + if rescale_shape is not None: + for img_meta in img_metas: + img_meta['ori_shape'] = tuple(rescale_shape) + (3, ) + + mm_inputs = {'imgs': imgs, 'img_metas': img_metas} + + return mm_inputs + + +def _update_input_img(img_list, img_meta_list, update_ori_shape=False): + # update img and its meta list + N, C, H, W = img_list[0].shape + img_meta = img_meta_list[0][0] + img_shape = (H, W, C) + if update_ori_shape: + ori_shape = img_shape + else: + ori_shape = img_meta['ori_shape'] + pad_shape = img_shape + new_img_meta_list = [[{ + 'img_shape': + img_shape, + 'ori_shape': + ori_shape, + 'pad_shape': + pad_shape, + 'filename': + img_meta['filename'], + 'scale_factor': + (img_shape[1] / ori_shape[1], img_shape[0] / ori_shape[0]) * 2, + 'flip': + False, + } for _ in range(N)]] + + return img_list, new_img_meta_list + + +def pytorch2onnx(model, + mm_inputs, + opset_version=11, + show=False, + output_file='tmp.onnx', + verify=False, + dynamic_export=False): + """Export Pytorch model to ONNX model and verify the outputs are same + between Pytorch and ONNX. + + Args: + model (nn.Module): Pytorch model we want to export. + mm_inputs (dict): Contain the input tensors and img_metas information. + opset_version (int): The onnx op version. Default: 11. + show (bool): Whether print the computation graph. Default: False. + output_file (string): The path to where we store the output ONNX model. + Default: `tmp.onnx`. + verify (bool): Whether compare the outputs between Pytorch and ONNX. + Default: False. + dynamic_export (bool): Whether to export ONNX with dynamic axis. + Default: False. + """ + model.cpu().eval() + test_mode = model.test_cfg.mode + + if isinstance(model.decode_head, nn.ModuleList): + num_classes = model.decode_head[-1].num_classes + else: + num_classes = model.decode_head.num_classes + + imgs = mm_inputs.pop('imgs') + img_metas = mm_inputs.pop('img_metas') + + img_list = [img[None, :] for img in imgs] + img_meta_list = [[img_meta] for img_meta in img_metas] + # update img_meta + img_list, img_meta_list = _update_input_img(img_list, img_meta_list) + + # replace original forward function + origin_forward = model.forward + model.forward = partial( + model.forward, + img_metas=img_meta_list, + return_loss=False, + rescale=True) + dynamic_axes = None + if dynamic_export: + if test_mode == 'slide': + dynamic_axes = {'input': {0: 'batch'}, 'output': {1: 'batch'}} + else: + dynamic_axes = { + 'input': { + 0: 'batch', + 2: 'height', + 3: 'width' + }, + 'output': { + 1: 'batch', + 2: 'height', + 3: 'width' + } + } + + register_extra_symbolics(opset_version) + with torch.no_grad(): + torch.onnx.export( + model, (img_list, ), + output_file, + input_names=['input'], + output_names=['output'], + export_params=True, + keep_initializers_as_inputs=False, + verbose=show, + opset_version=opset_version, + dynamic_axes=dynamic_axes) + print(f'Successfully exported ONNX model: {output_file}') + model.forward = origin_forward + + if verify: + # check by onnx + import onnx + onnx_model = onnx.load(output_file) + onnx.checker.check_model(onnx_model) + + if dynamic_export and test_mode == 'whole': + # scale image for dynamic shape test + img_list = [resize(_, scale_factor=1.5) for _ in img_list] + # concate flip image for batch test + flip_img_list = [_.flip(-1) for _ in img_list] + img_list = [ + torch.cat((ori_img, flip_img), 0) + for ori_img, flip_img in zip(img_list, flip_img_list) + ] + + # update img_meta + img_list, img_meta_list = _update_input_img( + img_list, img_meta_list, test_mode == 'whole') + + # check the numerical value + # get pytorch output + with torch.no_grad(): + pytorch_result = model(img_list, img_meta_list, return_loss=False) + pytorch_result = np.stack(pytorch_result, 0) + + # get onnx output + input_all = [node.name for node in onnx_model.graph.input] + input_initializer = [ + node.name for node in onnx_model.graph.initializer + ] + net_feed_input = list(set(input_all) - set(input_initializer)) + assert (len(net_feed_input) == 1) + sess = rt.InferenceSession(output_file) + onnx_result = sess.run( + None, {net_feed_input[0]: img_list[0].detach().numpy()})[0][0] + # show segmentation results + if show: + import os.path as osp + + import cv2 + img = img_meta_list[0][0]['filename'] + if not osp.exists(img): + img = imgs[0][:3, ...].permute(1, 2, 0) * 255 + img = img.detach().numpy().astype(np.uint8) + ori_shape = img.shape[:2] + else: + ori_shape = LoadImage()({'img': img})['ori_shape'] + + # resize onnx_result to ori_shape + onnx_result_ = cv2.resize(onnx_result[0].astype(np.uint8), + (ori_shape[1], ori_shape[0])) + show_result_pyplot( + model, + img, (onnx_result_, ), + palette=model.PALETTE, + block=False, + title='ONNXRuntime', + opacity=0.5) + + # resize pytorch_result to ori_shape + pytorch_result_ = cv2.resize(pytorch_result[0].astype(np.uint8), + (ori_shape[1], ori_shape[0])) + show_result_pyplot( + model, + img, (pytorch_result_, ), + title='PyTorch', + palette=model.PALETTE, + opacity=0.5) + # compare results + np.testing.assert_allclose( + pytorch_result.astype(np.float32) / num_classes, + onnx_result.astype(np.float32) / num_classes, + rtol=1e-5, + atol=1e-5, + err_msg='The outputs are different between Pytorch and ONNX') + print('The outputs are same between Pytorch and ONNX') + + +def parse_args(): + parser = argparse.ArgumentParser(description='Convert MMSeg to ONNX') + parser.add_argument('config', help='test config file path') + parser.add_argument('--checkpoint', help='checkpoint file', default=None) + parser.add_argument( + '--input-img', type=str, help='Images for input', default=None) + parser.add_argument( + '--show', + action='store_true', + help='show onnx graph and segmentation results') + parser.add_argument( + '--verify', action='store_true', help='verify the onnx model') + parser.add_argument('--output-file', type=str, default='tmp.onnx') + parser.add_argument('--opset-version', type=int, default=11) + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=None, + help='input image height and width.') + parser.add_argument( + '--rescale_shape', + type=int, + nargs='+', + default=None, + help='output image rescale height and width, work for slide mode.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='Override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--dynamic-export', + action='store_true', + help='Whether to export onnx with dynamic axis.') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = parse_args() + + cfg = mmcv.Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + cfg.model.pretrained = None + + if args.shape is None: + img_scale = cfg.test_pipeline[1]['img_scale'] + input_shape = (1, 3, img_scale[1], img_scale[0]) + elif len(args.shape) == 1: + input_shape = (1, 3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = ( + 1, + 3, + ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + + test_mode = cfg.model.test_cfg.mode + + # build the model and load checkpoint + cfg.model.train_cfg = None + segmentor = build_segmentor( + cfg.model, train_cfg=None, test_cfg=cfg.get('test_cfg')) + # convert SyncBN to BN + segmentor = _convert_batchnorm(segmentor) + + if args.checkpoint: + checkpoint = load_checkpoint( + segmentor, args.checkpoint, map_location='cpu') + segmentor.CLASSES = checkpoint['meta']['CLASSES'] + segmentor.PALETTE = checkpoint['meta']['PALETTE'] + + # read input or create dummpy input + if args.input_img is not None: + preprocess_shape = (input_shape[2], input_shape[3]) + rescale_shape = None + if args.rescale_shape is not None: + rescale_shape = [args.rescale_shape[0], args.rescale_shape[1]] + mm_inputs = _prepare_input_img( + args.input_img, + cfg.data.test.pipeline, + shape=preprocess_shape, + rescale_shape=rescale_shape) + else: + if isinstance(segmentor.decode_head, nn.ModuleList): + num_classes = segmentor.decode_head[-1].num_classes + else: + num_classes = segmentor.decode_head.num_classes + mm_inputs = _demo_mm_inputs(input_shape, num_classes) + + # convert model to onnx file + pytorch2onnx( + segmentor, + mm_inputs, + opset_version=args.opset_version, + show=args.show, + output_file=args.output_file, + verify=args.verify, + dynamic_export=args.dynamic_export) + + # Following strings of text style are from colorama package + bright_style, reset_style = '\x1b[1m', '\x1b[0m' + red_text, blue_text = '\x1b[31m', '\x1b[34m' + white_background = '\x1b[107m' + + msg = white_background + bright_style + red_text + msg += 'DeprecationWarning: This tool will be deprecated in future. ' + msg += blue_text + 'Welcome to use the unified model deployment toolbox ' + msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy' + msg += reset_style + warnings.warn(msg) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/pytorch2torchscript.py b/EgoHOS/raw/script/mmsegmentation/tools/pytorch2torchscript.py new file mode 100644 index 0000000000000000000000000000000000000000..d76f5ecb95c65483454ce16f87d70a6c281e344c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/pytorch2torchscript.py @@ -0,0 +1,185 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse + +import mmcv +import numpy as np +import torch +import torch._C +import torch.serialization +from mmcv.runner import load_checkpoint +from torch import nn + +from mmseg.models import build_segmentor + +torch.manual_seed(3) + + +def digit_version(version_str): + digit_version = [] + for x in version_str.split('.'): + if x.isdigit(): + digit_version.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + digit_version.append(int(patch_version[0]) - 1) + digit_version.append(int(patch_version[1])) + return digit_version + + +def check_torch_version(): + torch_minimum_version = '1.8.0' + torch_version = digit_version(torch.__version__) + + assert (torch_version >= digit_version(torch_minimum_version)), \ + f'Torch=={torch.__version__} is not support for converting to ' \ + f'torchscript. Please install pytorch>={torch_minimum_version}.' + + +def _convert_batchnorm(module): + module_output = module + if isinstance(module, torch.nn.SyncBatchNorm): + module_output = torch.nn.BatchNorm2d(module.num_features, module.eps, + module.momentum, module.affine, + module.track_running_stats) + if module.affine: + module_output.weight.data = module.weight.data.clone().detach() + module_output.bias.data = module.bias.data.clone().detach() + # keep requires_grad unchanged + module_output.weight.requires_grad = module.weight.requires_grad + module_output.bias.requires_grad = module.bias.requires_grad + module_output.running_mean = module.running_mean + module_output.running_var = module.running_var + module_output.num_batches_tracked = module.num_batches_tracked + for name, child in module.named_children(): + module_output.add_module(name, _convert_batchnorm(child)) + del module + return module_output + + +def _demo_mm_inputs(input_shape, num_classes): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + rng = np.random.RandomState(0) + imgs = rng.rand(*input_shape) + segs = rng.randint( + low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8) + img_metas = [{ + 'img_shape': (H, W, C), + 'ori_shape': (H, W, C), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + } for _ in range(N)] + mm_inputs = { + 'imgs': torch.FloatTensor(imgs).requires_grad_(True), + 'img_metas': img_metas, + 'gt_semantic_seg': torch.LongTensor(segs) + } + return mm_inputs + + +def pytorch2libtorch(model, + input_shape, + show=False, + output_file='tmp.pt', + verify=False): + """Export Pytorch model to TorchScript model and verify the outputs are + same between Pytorch and TorchScript. + + Args: + model (nn.Module): Pytorch model we want to export. + input_shape (tuple): Use this input shape to construct + the corresponding dummy input and execute the model. + show (bool): Whether print the computation graph. Default: False. + output_file (string): The path to where we store the + output TorchScript model. Default: `tmp.pt`. + verify (bool): Whether compare the outputs between + Pytorch and TorchScript. Default: False. + """ + if isinstance(model.decode_head, nn.ModuleList): + num_classes = model.decode_head[-1].num_classes + else: + num_classes = model.decode_head.num_classes + + mm_inputs = _demo_mm_inputs(input_shape, num_classes) + + imgs = mm_inputs.pop('imgs') + + # replace the original forword with forward_dummy + model.forward = model.forward_dummy + model.eval() + traced_model = torch.jit.trace( + model, + example_inputs=imgs, + check_trace=verify, + ) + + if show: + print(traced_model.graph) + + traced_model.save(output_file) + print('Successfully exported TorchScript model: {}'.format(output_file)) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert MMSeg to TorchScript') + parser.add_argument('config', help='test config file path') + parser.add_argument('--checkpoint', help='checkpoint file', default=None) + parser.add_argument( + '--show', action='store_true', help='show TorchScript graph') + parser.add_argument( + '--verify', action='store_true', help='verify the TorchScript model') + parser.add_argument('--output-file', type=str, default='tmp.pt') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[512, 512], + help='input image size (height, width)') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = parse_args() + check_torch_version() + + if len(args.shape) == 1: + input_shape = (1, 3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = ( + 1, + 3, + ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + + cfg = mmcv.Config.fromfile(args.config) + cfg.model.pretrained = None + + # build the model and load checkpoint + cfg.model.train_cfg = None + segmentor = build_segmentor( + cfg.model, train_cfg=None, test_cfg=cfg.get('test_cfg')) + # convert SyncBN to BN + segmentor = _convert_batchnorm(segmentor) + + if args.checkpoint: + load_checkpoint(segmentor, args.checkpoint, map_location='cpu') + + # convert the PyTorch model to LibTorch model + pytorch2libtorch( + segmentor, + input_shape, + show=args.show, + output_file=args.output_file, + verify=args.verify) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/slurm_test.sh b/EgoHOS/raw/script/mmsegmentation/tools/slurm_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e6f7bf4e33267f269cf0f455924cb70166ccd4b --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/slurm_test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +CHECKPOINT=$4 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +PY_ARGS=${@:5} +SRUN_ARGS=${SRUN_ARGS:-""} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/test.py ${CONFIG} ${CHECKPOINT} --launcher="slurm" ${PY_ARGS} diff --git a/EgoHOS/raw/script/mmsegmentation/tools/slurm_train.sh b/EgoHOS/raw/script/mmsegmentation/tools/slurm_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab232105f0309c720ed81a522eca14b6fbd64afd --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/slurm_train.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +SRUN_ARGS=${SRUN_ARGS:-""} +PY_ARGS=${@:4} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/train.py ${CONFIG} --launcher="slurm" ${PY_ARGS} diff --git a/EgoHOS/raw/script/mmsegmentation/tools/test.py b/EgoHOS/raw/script/mmsegmentation/tools/test.py new file mode 100644 index 0000000000000000000000000000000000000000..12892ec9b164554b856065637b7f5621783ff21f --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/test.py @@ -0,0 +1,319 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import shutil +import time +import warnings + +import mmcv +import torch +from mmcv.cnn.utils import revert_sync_batchnorm +from mmcv.parallel import MMDataParallel, MMDistributedDataParallel +from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, + wrap_fp16_model) +from mmcv.utils import DictAction + +from mmseg import digit_version +from mmseg.apis import multi_gpu_test, single_gpu_test +from mmseg.datasets import build_dataloader, build_dataset +from mmseg.models import build_segmentor +from mmseg.utils import setup_multi_processes + + +def parse_args(): + parser = argparse.ArgumentParser( + description='mmseg test (and eval) a model') + parser.add_argument('config', help='test config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--work-dir', + help=('if specified, the evaluation metric results will be dumped' + 'into the directory as json')) + parser.add_argument( + '--aug-test', action='store_true', help='Use Flip and Multi scale aug') + parser.add_argument('--out', help='output result file in pickle format') + parser.add_argument( + '--format-only', + action='store_true', + help='Format the output results without perform evaluation. It is' + 'useful when you want to format the result to a specific format and ' + 'submit it to the test server') + parser.add_argument( + '--eval', + type=str, + nargs='+', + help='evaluation metrics, which depends on the dataset, e.g., "mIoU"' + ' for generic datasets, and "cityscapes" for Cityscapes') + parser.add_argument('--show', action='store_true', help='show results') + parser.add_argument( + '--show-dir', help='directory where painted images will be saved') + parser.add_argument( + '--gpu-collect', + action='store_true', + help='whether to use gpu to collect results.') + parser.add_argument( + '--gpu-id', + type=int, + default=0, + help='id of gpu to use ' + '(only applicable to non-distributed testing)') + parser.add_argument( + '--tmpdir', + help='tmp directory used for collecting results from multiple ' + 'workers, available when gpu_collect is not specified') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--eval-options', + nargs='+', + action=DictAction, + help='custom options for evaluation') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + parser.add_argument( + '--opacity', + type=float, + default=0.5, + help='Opacity of painted segmentation map. In (0, 1] range.') + parser.add_argument('--local_rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + assert args.out or args.eval or args.format_only or args.show \ + or args.show_dir, \ + ('Please specify at least one operation (save/eval/format/show the ' + 'results / save the results) with the argument "--out", "--eval"' + ', "--format-only", "--show" or "--show-dir"') + + if args.eval and args.format_only: + raise ValueError('--eval and --format_only cannot be both specified') + + if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): + raise ValueError('The output file must be a pkl file.') + + cfg = mmcv.Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # set multi-process settings + setup_multi_processes(cfg) + + # set cudnn_benchmark + if cfg.get('cudnn_benchmark', False): + torch.backends.cudnn.benchmark = True + if args.aug_test: + # hard code index + cfg.data.test.pipeline[1].img_ratios = [ + 0.5, 0.75, 1.0, 1.25, 1.5, 1.75 + ] + cfg.data.test.pipeline[1].flip = True + cfg.model.pretrained = None + cfg.data.test.test_mode = True + + if args.gpu_id is not None: + cfg.gpu_ids = [args.gpu_id] + + # init distributed env first, since logger depends on the dist info. + if args.launcher == 'none': + cfg.gpu_ids = [args.gpu_id] + distributed = False + if len(cfg.gpu_ids) > 1: + warnings.warn(f'The gpu-ids is reset from {cfg.gpu_ids} to ' + f'{cfg.gpu_ids[0:1]} to avoid potential error in ' + 'non-distribute testing time.') + cfg.gpu_ids = cfg.gpu_ids[0:1] + else: + distributed = True + init_dist(args.launcher, **cfg.dist_params) + + rank, _ = get_dist_info() + # allows not to create + if args.work_dir is not None and rank == 0: + mmcv.mkdir_or_exist(osp.abspath(args.work_dir)) + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + if args.aug_test: + json_file = osp.join(args.work_dir, + f'eval_multi_scale_{timestamp}.json') + else: + json_file = osp.join(args.work_dir, + f'eval_single_scale_{timestamp}.json') + elif rank == 0: + work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + mmcv.mkdir_or_exist(osp.abspath(work_dir)) + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + if args.aug_test: + json_file = osp.join(work_dir, + f'eval_multi_scale_{timestamp}.json') + else: + json_file = osp.join(work_dir, + f'eval_single_scale_{timestamp}.json') + + # build the dataloader + # TODO: support multiple images per gpu (only minor changes are needed) + dataset = build_dataset(cfg.data.test) + # The default loader config + loader_cfg = dict( + # cfg.gpus will be ignored if distributed + num_gpus=len(cfg.gpu_ids), + dist=distributed, + shuffle=False) + # The overall dataloader settings + loader_cfg.update({ + k: v + for k, v in cfg.data.items() if k not in [ + 'train', 'val', 'test', 'train_dataloader', 'val_dataloader', + 'test_dataloader' + ] + }) + test_loader_cfg = { + **loader_cfg, + 'samples_per_gpu': 1, + 'shuffle': False, # Not shuffle by default + **cfg.data.get('test_dataloader', {}) + } + # build the dataloader + data_loader = build_dataloader(dataset, **test_loader_cfg) + + # build the model and load checkpoint + cfg.model.train_cfg = None + model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg')) + fp16_cfg = cfg.get('fp16', None) + if fp16_cfg is not None: + wrap_fp16_model(model) + checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu') + if 'CLASSES' in checkpoint.get('meta', {}): + model.CLASSES = checkpoint['meta']['CLASSES'] + else: + print('"CLASSES" not found in meta, use dataset.CLASSES instead') + model.CLASSES = dataset.CLASSES + if 'PALETTE' in checkpoint.get('meta', {}): + model.PALETTE = checkpoint['meta']['PALETTE'] + else: + print('"PALETTE" not found in meta, use dataset.PALETTE instead') + model.PALETTE = dataset.PALETTE + + # clean gpu memory when starting a new evaluation. + torch.cuda.empty_cache() + eval_kwargs = {} if args.eval_options is None else args.eval_options + + # Deprecated + efficient_test = eval_kwargs.get('efficient_test', False) + if efficient_test: + warnings.warn( + '``efficient_test=True`` does not have effect in tools/test.py, ' + 'the evaluation and format results are CPU memory efficient by ' + 'default') + + eval_on_format_results = ( + args.eval is not None and 'cityscapes' in args.eval) + if eval_on_format_results: + assert len(args.eval) == 1, 'eval on format results is not ' \ + 'applicable for metrics other than ' \ + 'cityscapes' + if args.format_only or eval_on_format_results: + if 'imgfile_prefix' in eval_kwargs: + tmpdir = eval_kwargs['imgfile_prefix'] + else: + tmpdir = '.format_cityscapes' + eval_kwargs.setdefault('imgfile_prefix', tmpdir) + mmcv.mkdir_or_exist(tmpdir) + else: + tmpdir = None + + if not distributed: + warnings.warn( + 'SyncBN is only supported with DDP. To be compatible with DP, ' + 'we convert SyncBN to BN. Please use dist_train.sh which can ' + 'avoid this error.') + if not torch.cuda.is_available(): + assert digit_version(mmcv.__version__) >= digit_version('1.4.4'), \ + 'Please use MMCV >= 1.4.4 for CPU training!' + model = revert_sync_batchnorm(model) + model = MMDataParallel(model, device_ids=cfg.gpu_ids) + results = single_gpu_test( + model, + data_loader, + args.show, + args.show_dir, + False, + args.opacity, + pre_eval=args.eval is not None and not eval_on_format_results, + format_only=args.format_only or eval_on_format_results, + format_args=eval_kwargs) + else: + model = MMDistributedDataParallel( + model.cuda(), + device_ids=[torch.cuda.current_device()], + broadcast_buffers=False) + results = multi_gpu_test( + model, + data_loader, + args.tmpdir, + args.gpu_collect, + False, + pre_eval=args.eval is not None and not eval_on_format_results, + format_only=args.format_only or eval_on_format_results, + format_args=eval_kwargs) + + rank, _ = get_dist_info() + if rank == 0: + if args.out: + warnings.warn( + 'The behavior of ``args.out`` has been changed since MMSeg ' + 'v0.16, the pickled outputs could be seg map as type of ' + 'np.array, pre-eval results or file paths for ' + '``dataset.format_results()``.') + print(f'\nwriting results to {args.out}') + mmcv.dump(results, args.out) + if args.eval: + eval_kwargs.update(metric=args.eval) + metric = dataset.evaluate(results, **eval_kwargs) + metric_dict = dict(config=args.config, metric=metric) + mmcv.dump(metric_dict, json_file, indent=4) + if tmpdir is not None and eval_on_format_results: + # remove tmp dir when cityscapes evaluation + shutil.rmtree(tmpdir) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg2torchserve.py b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg2torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..9063634845a548b63acbed4034f09ead0d5c7ce4 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg2torchserve.py @@ -0,0 +1,111 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser, Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + +import mmcv + +try: + from model_archiver.model_packaging import package_model + from model_archiver.model_packaging_utils import ModelExportUtils +except ImportError: + package_model = None + + +def mmseg2torchserve( + config_file: str, + checkpoint_file: str, + output_folder: str, + model_name: str, + model_version: str = '1.0', + force: bool = False, +): + """Converts mmsegmentation model (config + checkpoint) to TorchServe + `.mar`. + + Args: + config_file: + In MMSegmentation config format. + The contents vary for each task repository. + checkpoint_file: + In MMSegmentation checkpoint format. + The contents vary for each task repository. + output_folder: + Folder where `{model_name}.mar` will be created. + The file created will be in TorchServe archive format. + model_name: + If not None, used for naming the `{model_name}.mar` file + that will be created under `output_folder`. + If None, `{Path(checkpoint_file).stem}` will be used. + model_version: + Model's version. + force: + If True, if there is an existing `{model_name}.mar` + file under `output_folder` it will be overwritten. + """ + mmcv.mkdir_or_exist(output_folder) + + config = mmcv.Config.fromfile(config_file) + + with TemporaryDirectory() as tmpdir: + config.dump(f'{tmpdir}/config.py') + + args = Namespace( + **{ + 'model_file': f'{tmpdir}/config.py', + 'serialized_file': checkpoint_file, + 'handler': f'{Path(__file__).parent}/mmseg_handler.py', + 'model_name': model_name or Path(checkpoint_file).stem, + 'version': model_version, + 'export_path': output_folder, + 'force': force, + 'requirements_file': None, + 'extra_files': None, + 'runtime': 'python', + 'archive_format': 'default' + }) + manifest = ModelExportUtils.generate_manifest_json(args) + package_model(args, manifest) + + +def parse_args(): + parser = ArgumentParser( + description='Convert mmseg models to TorchServe `.mar` format.') + parser.add_argument('config', type=str, help='config file path') + parser.add_argument('checkpoint', type=str, help='checkpoint file path') + parser.add_argument( + '--output-folder', + type=str, + required=True, + help='Folder where `{model_name}.mar` will be created.') + parser.add_argument( + '--model-name', + type=str, + default=None, + help='If not None, used for naming the `{model_name}.mar`' + 'file that will be created under `output_folder`.' + 'If None, `{Path(checkpoint_file).stem}` will be used.') + parser.add_argument( + '--model-version', + type=str, + default='1.0', + help='Number used for versioning.') + parser.add_argument( + '-f', + '--force', + action='store_true', + help='overwrite the existing `{model_name}.mar`') + args = parser.parse_args() + + return args + + +if __name__ == '__main__': + args = parse_args() + + if package_model is None: + raise ImportError('`torch-model-archiver` is required.' + 'Try: pip install torch-model-archiver') + + mmseg2torchserve(args.config, args.checkpoint, args.output_folder, + args.model_name, args.model_version, args.force) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg_handler.py b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..28fe5016f8c9c50c1c93f22376b919dc481b53da --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/mmseg_handler.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import base64 +import os + +import cv2 +import mmcv +import torch +from mmcv.cnn.utils.sync_bn import revert_sync_batchnorm +from ts.torch_handler.base_handler import BaseHandler + +from mmseg.apis import inference_segmentor, init_segmentor + + +class MMsegHandler(BaseHandler): + + def initialize(self, context): + properties = context.system_properties + self.map_location = 'cuda' if torch.cuda.is_available() else 'cpu' + self.device = torch.device(self.map_location + ':' + + str(properties.get('gpu_id')) if torch.cuda. + is_available() else self.map_location) + self.manifest = context.manifest + + model_dir = properties.get('model_dir') + serialized_file = self.manifest['model']['serializedFile'] + checkpoint = os.path.join(model_dir, serialized_file) + self.config_file = os.path.join(model_dir, 'config.py') + + self.model = init_segmentor(self.config_file, checkpoint, self.device) + self.model = revert_sync_batchnorm(self.model) + self.initialized = True + + def preprocess(self, data): + images = [] + + for row in data: + image = row.get('data') or row.get('body') + if isinstance(image, str): + image = base64.b64decode(image) + image = mmcv.imfrombytes(image) + images.append(image) + + return images + + def inference(self, data, *args, **kwargs): + results = [inference_segmentor(self.model, img) for img in data] + return results + + def postprocess(self, data): + output = [] + + for image_result in data: + _, buffer = cv2.imencode('.png', image_result[0].astype('uint8')) + content = buffer.tobytes() + output.append(content) + return output diff --git a/EgoHOS/raw/script/mmsegmentation/tools/torchserve/test_torchserve.py b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/test_torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..432834a8d40c703215506761b03366d7dd15adec --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/torchserve/test_torchserve.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser +from io import BytesIO + +import matplotlib.pyplot as plt +import mmcv +import requests + +from mmseg.apis import inference_segmentor, init_segmentor + + +def parse_args(): + parser = ArgumentParser( + description='Compare result of torchserve and pytorch,' + 'and visualize them.') + parser.add_argument('img', help='Image file') + parser.add_argument('config', help='Config file') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument('model_name', help='The model name in the server') + parser.add_argument( + '--inference-addr', + default='127.0.0.1:8080', + help='Address and port of the inference server') + parser.add_argument( + '--result-image', + type=str, + default=None, + help='save server output in result-image') + parser.add_argument( + '--device', default='cuda:0', help='Device used for inference') + + args = parser.parse_args() + return args + + +def main(args): + url = 'http://' + args.inference_addr + '/predictions/' + args.model_name + with open(args.img, 'rb') as image: + tmp_res = requests.post(url, image) + content = tmp_res.content + if args.result_image: + with open(args.result_image, 'wb') as out_image: + out_image.write(content) + plt.imshow(mmcv.imread(args.result_image, 'grayscale')) + plt.show() + else: + plt.imshow(plt.imread(BytesIO(content))) + plt.show() + model = init_segmentor(args.config, args.checkpoint, args.device) + image = mmcv.imread(args.img) + result = inference_segmentor(model, image) + plt.imshow(result[0]) + plt.show() + + +if __name__ == '__main__': + args = parse_args() + main(args) diff --git a/EgoHOS/raw/script/mmsegmentation/tools/train.py b/EgoHOS/raw/script/mmsegmentation/tools/train.py new file mode 100644 index 0000000000000000000000000000000000000000..4adf90e1a366e3dcffa8907cfdc0a68d37c9df9c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/tools/train.py @@ -0,0 +1,241 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import copy +import os +import os.path as osp +import time +import warnings + +import mmcv +import torch +import torch.distributed as dist +from mmcv.cnn.utils import revert_sync_batchnorm +from mmcv.runner import get_dist_info, init_dist +from mmcv.utils import Config, DictAction, get_git_hash + +from mmseg import __version__ +from mmseg.apis import init_random_seed, set_random_seed, train_segmentor +from mmseg.datasets import build_dataset +from mmseg.models import build_segmentor +from mmseg.utils import collect_env, get_root_logger, setup_multi_processes + +torch.backends.cudnn.deterministic = True + +def parse_args(): + parser = argparse.ArgumentParser(description='Train a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument('--work-dir', help='the dir to save logs and models') + parser.add_argument( + '--load-from', help='the checkpoint file to load weights from') + parser.add_argument( + '--resume-from', help='the checkpoint file to resume from') + parser.add_argument( + '--no-validate', + action='store_true', + help='whether not to evaluate the checkpoint during training') + group_gpus = parser.add_mutually_exclusive_group() + group_gpus.add_argument( + '--gpus', + type=int, + help='(Deprecated, please use --gpu-id) number of gpus to use ' + '(only applicable to non-distributed training)') + group_gpus.add_argument( + '--gpu-ids', + type=int, + nargs='+', + help='(Deprecated, please use --gpu-id) ids of gpus to use ' + '(only applicable to non-distributed training)') + group_gpus.add_argument( + '--gpu-id', + type=int, + default=0, + help='id of gpu to use ' + '(only applicable to non-distributed training)') + parser.add_argument('--seed', type=int, default=None, help='random seed') + parser.add_argument( + '--diff_seed', + action='store_true', + help='Whether or not set different seeds for different ranks') + parser.add_argument( + '--deterministic', + action='store_true', + help='whether to set deterministic options for CUDNN backend.') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + parser.add_argument('--local_rank', type=int, default=0) + parser.add_argument( + '--auto-resume', + action='store_true', + help='resume from the latest checkpoint automatically.') + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # set cudnn_benchmark + if cfg.get('cudnn_benchmark', False): + torch.backends.cudnn.benchmark = True + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + if args.load_from is not None: + cfg.load_from = args.load_from + if args.resume_from is not None: + cfg.resume_from = args.resume_from + if args.gpus is not None: + cfg.gpu_ids = range(1) + warnings.warn('`--gpus` is deprecated because we only support ' + 'single GPU mode in non-distributed training. ' + 'Use `gpus=1` now.') + if args.gpu_ids is not None: + cfg.gpu_ids = args.gpu_ids[0:1] + warnings.warn('`--gpu-ids` is deprecated, please use `--gpu-id`. ' + 'Because we only support single GPU mode in ' + 'non-distributed training. Use the first GPU ' + 'in `gpu_ids` now.') + if args.gpus is None and args.gpu_ids is None: + cfg.gpu_ids = [args.gpu_id] + + cfg.auto_resume = args.auto_resume + + # init distributed env first, since logger depends on the dist info. + if args.launcher == 'none': + distributed = False + else: + distributed = True + init_dist(args.launcher, **cfg.dist_params) + # gpu_ids is used to calculate iter when resuming checkpoint + _, world_size = get_dist_info() + cfg.gpu_ids = range(world_size) + + # create work_dir + mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) + # dump config + cfg.dump(osp.join(cfg.work_dir, osp.basename(args.config))) + # init the logger before other steps + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + log_file = osp.join(cfg.work_dir, f'{timestamp}.log') + logger = get_root_logger(log_file=log_file, log_level=cfg.log_level) + + # set multi-process settings + setup_multi_processes(cfg) + + # init the meta dict to record some important information such as + # environment info and seed, which will be logged + meta = dict() + # log env info + env_info_dict = collect_env() + env_info = '\n'.join([f'{k}: {v}' for k, v in env_info_dict.items()]) + dash_line = '-' * 60 + '\n' + logger.info('Environment info:\n' + dash_line + env_info + '\n' + + dash_line) + meta['env_info'] = env_info + + # log some basic info + logger.info(f'Distributed training: {distributed}') + logger.info(f'Config:\n{cfg.pretty_text}') + + # set random seeds + seed = init_random_seed(args.seed) + seed = seed + dist.get_rank() if args.diff_seed else seed + logger.info(f'Set random seed to {seed}, ' + f'deterministic: {args.deterministic}') + set_random_seed(seed, deterministic=args.deterministic) + cfg.seed = seed + meta['seed'] = seed + meta['exp_name'] = osp.basename(args.config) + + model = build_segmentor( + cfg.model, + train_cfg=cfg.get('train_cfg'), + test_cfg=cfg.get('test_cfg')) + model.init_weights() + + # SyncBN is not support for DP + if not distributed: + warnings.warn( + 'SyncBN is only supported with DDP. To be compatible with DP, ' + 'we convert SyncBN to BN. Please use dist_train.sh which can ' + 'avoid this error.') + model = revert_sync_batchnorm(model) + + logger.info(model) + + datasets = [build_dataset(cfg.data.train)] + if len(cfg.workflow) == 2: + val_dataset = copy.deepcopy(cfg.data.val) + val_dataset.pipeline = cfg.data.train.pipeline + datasets.append(build_dataset(val_dataset)) + if cfg.checkpoint_config is not None: + # save mmseg version, config file content and class names in + # checkpoints as meta data + cfg.checkpoint_config.meta = dict( + mmseg_version=f'{__version__}+{get_git_hash()[:7]}', + config=cfg.pretty_text, + CLASSES=datasets[0].CLASSES, + PALETTE=datasets[0].PALETTE) + # add an attribute for visualization convenience + model.CLASSES = datasets[0].CLASSES + # passing checkpoint meta for saving best checkpoint + meta.update(cfg.checkpoint_config.meta) + train_segmentor( + model, + datasets, + cfg, + distributed=distributed, + validate=(not args.no_validate), + timestamp=timestamp, + meta=meta) + + +if __name__ == '__main__': + main() diff --git a/EgoHOS/raw/script/mmsegmentation/train.sh b/EgoHOS/raw/script/mmsegmentation/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1f91923b6e1160dbfe7565ac9f1117389f91e1c --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/train.sh @@ -0,0 +1,83 @@ +####### Basic Experiments ####### + + + +### Parallel Model ### + +# Test original +# ./tools/dist_train.sh ./configs/swin/seg_handobj2.py 8 --work-dir ./work_dirs/seg_handobj2_new + +# Test train on 512 resolution +# ./tools/dist_train.sh ./configs/swin/seg_handobj2_512.py 8 + + +# rgb -> handobj2 +# python tools/train.py ./configs/swin/seg_handobj2_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/seg_handobj2_ccda.py 8 + + +# rgb -> handobj1 +# python tools/train.py ./configs/swin/seg_handobj1.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/seg_handobj1.py 8 + + +# rgb -> handobj1 (ccda) +# python tools/train.py ./configs/swin/seg_handobj1_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/seg_handobj1_ccda.py 8 + + +# rgb -> twohands +# python tools/train.py ./configs/swin/seg_twohands_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/seg_twohands.py 8 +# ./tools/dist_train.sh ./configs/swin/seg_twohands_ccda.py 8 + + +### Sequential Model ### + +# rgb -> twohands [Finished] + + +# rgb + twohands -> obj2 [Done] +# python tools/train.py ./configs/swin/twohands_to_obj2.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_to_obj2.py 8 + +# rgb + twohands -> obj1 [Done] +# python tools/train.py ./configs/swin/twohands_to_obj1.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_to_obj1.py 8 + +# rgb + twohands -> cb [Done] +# python tools/train.py ./configs/swin/twohands_to_cb.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_to_cb_ccda.py 8 + +# rgb + twohands + cb -> obj2 [*] +# python tools/train.py ./configs/swin/twohands_cb_to_obj2.py # single gpu test + +# rgb + twohands + cb -> obj2 (CCDA) [*] +# python tools/train.py ./configs/swin/twohands_cb_to_obj2_ccda.py # single gpu test +./tools/dist_train.sh ./configs/swin/twohands_cb_to_obj2_ccda.py 8 + +# rgb + twohands + cb -> obj1 [TODO] +# python tools/train.py ./configs/swin/twohands_cb_to_obj1.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_cb_to_obj1.py 8 + +# rgb + twohands -> obj2 (CCDA) [*] +# python tools/train.py ./configs/swin/twohands_to_obj2_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_to_obj2_ccda.py 8 + +# rgb + twohands -> obj1 (CCDA) [RUNING] +# python tools/train.py ./configs/swin/twohands_to_obj1_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_cb_to_obj1_ccda.py 8 + +# rgb + twohands -> cb (CCDA) [RUNING] +# python tools/train.py ./configs/swin/twohands_to_cb_ccda.py # single gpu test +# ./tools/dist_train.sh ./configs/swin/twohands_to_cb_ccda.py 8 + +# rgb + twohands + cb -> obj2 (CCDA) [*] + + +# rgb + twohands + cb -> obj1 (CCDA) [TODO] + + + + + diff --git a/EgoHOS/raw/script/mmsegmentation/visualize.py b/EgoHOS/raw/script/mmsegmentation/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3f729b1e6956d37d3593a08295c1cf0dd1d978 --- /dev/null +++ b/EgoHOS/raw/script/mmsegmentation/visualize.py @@ -0,0 +1,105 @@ +from PIL import Image +import numpy as np +import argparse +import glob +import pdb +import os +from skimage.io import imsave + +def visualize_twohands(img, seg_result, alpha = 0.4): + seg_color = np.zeros((img.shape)) + seg_color[seg_result == 0] = (0, 0, 0) # background + seg_color[seg_result == 1] = (255, 0, 0) # left_hand + seg_color[seg_result == 2] = (0, 0, 255) # right_hand + vis = img * (1 - alpha) + seg_color * alpha + return vis + +def visualize_cb(img, seg_result, alpha = 0.4): + seg_color = np.zeros((img.shape)) + seg_color[seg_result == 0] = (0, 0, 0) # background + seg_color[seg_result == 1] = (255, 0, 0) # contact + vis = img * (1 - alpha) + seg_color * alpha + return vis + +def visualize_twohands_obj1(img, seg_result, alpha = 0.4): + seg_color = np.zeros((img.shape)) + seg_color[seg_result == 0] = (0, 0, 0) # background + seg_color[seg_result == 1] = (255, 0, 0) # left_hand + seg_color[seg_result == 2] = (0, 0, 255) # right_hand + seg_color[seg_result == 3] = (255, 0, 255) # left_object1 + seg_color[seg_result == 4] = (0, 255, 255) # right_object1 + seg_color[seg_result == 5] = (0, 255, 0) # two_object1 + vis = img * (1 - alpha) + seg_color * alpha + return vis + +def visualize_twohands_obj2(img, seg_result, alpha = 0.4): + seg_color = np.zeros((img.shape)) + seg_color[seg_result == 0] = (0, 0, 0) # background + seg_color[seg_result == 1] = (255, 0, 0) # left_hand + seg_color[seg_result == 2] = (0, 0, 255) # right_hand + seg_color[seg_result == 3] = (255, 0, 255) # left_object1 + seg_color[seg_result == 4] = (0, 255, 255) # right_object1 + seg_color[seg_result == 5] = (0, 255, 0) # two_object1 + seg_color[seg_result == 6] = (255, 204, 255) # left_object2 + seg_color[seg_result == 7] = (204, 255, 255) # right_object2 + seg_color[seg_result == 8] = (204, 255, 204) # two_object2 + vis = img * (1 - alpha) + seg_color * alpha + return vis + + + +if __name__ == '__main__': + + parser = argparse.ArgumentParser(description="") + parser.add_argument("--mode", default='twohands_obj1', type=str, help='options: twohands, cb, twohands_obj1, twohands_obj2') + parser.add_argument("--img_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/images', type=str) + parser.add_argument("--twohands_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/pred_twohands', type=str) + parser.add_argument("--cb_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/pred_cb', type=str) + parser.add_argument("--obj1_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/pred_obj1', type=str) + parser.add_argument("--obj2_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/pred_obj2', type=str) + parser.add_argument("--vis_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/testimages/pred_obj1_vis', type=str) + args = parser.parse_args() + + os.makedirs(args.vis_dir, exist_ok = True) + + for img_file in glob.glob(args.img_dir + '/*'): + fname = os.path.basename(img_file).split('.')[0] + img = np.array(Image.open(img_file)) + + if args.mode == 'twohands': + twohands = np.array(Image.open(os.path.join(args.twohands_dir, fname + '.png'))) + twohands_vis = visualize_twohands(img, twohands) + imsave(os.path.join(args.vis_dir, fname + '.jpg'), twohands_vis) + + elif args.mode == 'cb': + cb = np.array(Image.open(os.path.join(args.cb_dir, fname + '.png'))) + cb_vis = visualize_cb(img, cb) + imsave(os.path.join(args.vis_dir, fname + '.jpg'), cb_vis) + + elif args.mode == 'twohands_obj1': + twohands = np.array(Image.open(os.path.join(args.twohands_dir, fname + '.png'))) + obj1 = np.array(Image.open(os.path.join(args.obj1_dir, fname + '.png'))) + twohands_obj1 = twohands.copy() + twohands_obj1[obj1 == 1] = 3 + twohands_obj1[obj1 == 2] = 4 + twohands_obj1[obj1 == 3] = 5 + twohands_obj1_vis = visualize_twohands_obj1(img, twohands_obj1) + imsave(os.path.join(args.vis_dir, fname + '.jpg'), twohands_obj1_vis) + + elif args.mode == 'twohands_obj2': + twohands = np.array(Image.open(os.path.join(args.twohands_dir, fname + '.png'))) + obj2 = np.array(Image.open(os.path.join(args.obj2_dir, fname + '.png'))) + twohands_obj2 = twohands.copy() + twohands_obj2[obj2 == 1] = 3 + twohands_obj2[obj2 == 2] = 4 + twohands_obj2[obj2 == 3] = 5 + twohands_obj2[obj2 == 4] = 6 + twohands_obj2[obj2 == 5] = 7 + twohands_obj2[obj2 == 6] = 8 + twohands_obj2_vis = visualize_twohands_obj2(img, twohands_obj2) + imsave(os.path.join(args.vis_dir, fname + '.jpg'), twohands_obj2_vis) + + else: + raise NotImplementedError + + diff --git a/EgoHOS/raw/script/preprocess_script/Label_Map.txt b/EgoHOS/raw/script/preprocess_script/Label_Map.txt new file mode 100644 index 0000000000000000000000000000000000000000..a3ddff9888e8cca0aae5b76e54c97769d0eca6ec --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/Label_Map.txt @@ -0,0 +1,9 @@ +# # Label Mapping +# LEFT_HAND = 61 -> 1 +# RIGHT_HAND = 71 -> 2 +# LEFT_OBJ1 = 1 -> 3 +# LEFT_OBJ2 = 11 -> 6 +# RIGHT_OBJ1 = 21 -> 4 +# RIGHT_OBJ2 = 31 -> 7 +# TWO_OBJ1 = 41 -> 5 +# TWO_OBJ2 = 51 -> 8 diff --git a/EgoHOS/raw/script/preprocess_script/check_label.py b/EgoHOS/raw/script/preprocess_script/check_label.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd907e38a4e0717fe619be35f42ec8bc63f48e4 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/check_label.py @@ -0,0 +1,41 @@ +""" + This script checks unique values in label +""" +from PIL import Image +import numpy as np +import glob +import pdb +import os +from tqdm import tqdm + +lbl_type_list = ['train', 'val', 'test_indomain', 'test_outdomain'] + +for lbl_type in lbl_type_list: + + image_dir = '../data/'+lbl_type+'/image' + label_dir = '../data/'+lbl_type+'/label' + + for lbl_file in tqdm(glob.glob(label_dir + '/*.png')): + + fname = os.path.basename(lbl_file).split('.')[0] + lbl = np.array(Image.open(lbl_file)) + img_file = os.path.join(image_dir, fname + '.jpg') + img = np.array(Image.open(img_file)) + unique_vals = np.unique(lbl) + + if min(unique_vals) < 0 or max(unique_vals) > 8: + print('label out of bound!') + + if lbl.shape[0] != img.shape[0] or lbl.shape[1] != img.shape[1]: + print('size mismatch!') + + if len(lbl.shape) != 2 or len(img.shape) != 3: + print('chanel mismatch!') + print(fname, lbl.shape, img.shape) + + os.remove(img_file) + os.remove(lbl_file) + + + + diff --git a/EgoHOS/raw/script/preprocess_script/cleanup_lama_fname.py b/EgoHOS/raw/script/preprocess_script/cleanup_lama_fname.py new file mode 100644 index 0000000000000000000000000000000000000000..d2896db0d28768b9d125dbf651d034e33f256367 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/cleanup_lama_fname.py @@ -0,0 +1,32 @@ +import os +import glob +import pdb +from tqdm import tqdm +import argparse + + + +parser = argparse.ArgumentParser(description="resize image using bicubic upsampling") +parser.add_argument("--img_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/lama_512_pad', type=str) +args = parser.parse_args() + + + +for file in tqdm(glob.glob(args.img_dir + '/*')): + ext = file.split('.')[-1] + val_list = (file.split('/')[-1].split('.')[0] + '.' + file.split('/')[-1].split('.')[1]).split('_') + + # pdb.set_trace() + + if 'mask.png' in val_list: + + fname = val_list[0] + for i in range(1,len(val_list)-1): + fname = fname + '_' + val_list[i] + + dst_file = os.path.join(args.img_dir, fname + '.' + ext) + + os.rename(file, dst_file) + + # pdb.set_trace() + diff --git a/EgoHOS/raw/script/preprocess_script/convert_label.py b/EgoHOS/raw/script/preprocess_script/convert_label.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffb4c7c099b73de5e211a6b8542be755a18db44 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/convert_label.py @@ -0,0 +1,97 @@ +""" + This script converts label into different version, depending + on the task (allhands, twohands, handobj1, etc.) +""" +from PIL import Image +import numpy as np +import glob +import pdb +import os +from skimage.io import imsave +from tqdm import tqdm + + + +def cvt_lbl(src_lbl_dir, dst_lbl_dir, mode): + + if os.path.exists(dst_lbl_dir): + os.system('rm -rf ' + dst_lbl_dir) + os.makedirs(dst_lbl_dir, exist_ok = True) + + for file in tqdm(glob.glob(src_lbl_dir + '/*.png')): + + fname = os.path.basename(file) + lbl = np.array(Image.open(file)) + + if mode == 'allhands': + lbl_out = np.zeros((lbl.shape)) + lbl_out[lbl == 1] = 1 + lbl_out[lbl == 2] = 1 + elif mode == 'twohands': + lbl_out = lbl.copy() + lbl_out[lbl_out > 2] = 0 + elif mode == 'handobj1': + lbl_out = lbl.copy() + lbl_out[lbl_out > 5] = 0 + elif mode == 'obj1': + lbl_out = lbl.copy() + lbl_out[lbl_out > 5] = 0 + lbl_out[lbl_out == 1] = 0 + lbl_out[lbl_out == 2] = 0 + lbl_out[lbl_out == 3] = 1 + lbl_out[lbl_out == 4] = 2 + lbl_out[lbl_out == 5] = 3 + elif mode == 'obj2': + lbl_out = lbl.copy() + lbl_out[lbl_out == 1] = 0 + lbl_out[lbl_out == 2] = 0 + lbl_out[lbl_out == 3] = 1 + lbl_out[lbl_out == 4] = 2 + lbl_out[lbl_out == 5] = 3 + lbl_out[lbl_out == 6] = 4 + lbl_out[lbl_out == 7] = 5 + lbl_out[lbl_out == 8] = 6 + elif mode == 'foreground': + lbl_out = lbl.copy() + lbl_out[lbl_out > 0] = 1 + + # print(np.unique(lbl_out)) + # pdb.set_trace() + + # lbl_out[lbl_out == 3] = 1 + # lbl_out[lbl_out == 4] = 2 + + imsave(os.path.join(dst_lbl_dir, fname), lbl_out) + + + +if __name__ == '__main__': + + # lbl_type_list = ['train', 'val', 'test_indomain', 'test_outdomain'] + lbl_type_list = ['train'] + + for lbl_type in lbl_type_list: + + lbl_dir = '../data/'+lbl_type+'/label_ccda' + + lbl_twohands_dir = '../data/'+lbl_type+'/label_twohands_ccda' + cvt_lbl(lbl_dir, lbl_twohands_dir, 'twohands') + + lbl_handobj1_dir = '../data/'+lbl_type+'/label_handobj1_ccda' + cvt_lbl(lbl_dir, lbl_handobj1_dir, 'handobj1') + + lbl_handobj1_dir = '../data/'+lbl_type+'/label_obj1_ccda' + cvt_lbl(lbl_dir, lbl_handobj1_dir, 'obj1') + + lbl_handobj1_dir = '../data/'+lbl_type+'/label_obj2_ccda' + cvt_lbl(lbl_dir, lbl_handobj1_dir, 'obj2') + + lbl_allhands_dir = '../data/'+lbl_type+'/label_allhands_ccda' + cvt_lbl(lbl_dir, lbl_allhands_dir, 'allhands') + + # lbl_handobj1_dir = '../data/'+lbl_type+'/label_foreground' + # cvt_lbl(lbl_dir, lbl_handobj1_dir, 'foreground') + + + + diff --git a/EgoHOS/raw/script/preprocess_script/convert_raw_data.py b/EgoHOS/raw/script/preprocess_script/convert_raw_data.py new file mode 100644 index 0000000000000000000000000000000000000000..de7b2364a5b0f4649913945ad4bbf70041f882fb --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/convert_raw_data.py @@ -0,0 +1,79 @@ +from pathlib import Path +from tkinter import RIGHT +from PIL import Image +import numpy as np +import matplotlib.pyplot as plt +import shutil +import cv2 +import tqdm + +LEFT_HAND = 61 +RIGHT_HAND = 71 +LEFT_OBJ1 = 1 +LEFT_OBJ2 = 11 +RIGHT_OBJ1 = 21 +RIGHT_OBJ2 = 31 +TWO_OBJ1 = 41 +TWO_OBJ2 = 51 # FIXME, if it is 31, it is overlapping with RIGHT_OBJ2 +# all_classes = [LEFT_HAND, RIGHT_HAND, LEFT_OBJ1, LEFT_OBJ2, RIGHT_OBJ1, RIGHT_OBJ2, TWO_OBJ1, TWO_OBJ2] +# all_classes = [LEFT_HAND, RIGHT_HAND, LEFT_OBJ1, RIGHT_OBJ1, TWO_OBJ1] +all_classes = [LEFT_HAND, RIGHT_HAND, LEFT_OBJ1, RIGHT_OBJ1, TWO_OBJ1] + +def load_ann(ann_path): + ann = Image.open(ann_path).convert('P') + return np.array(ann) + +def load_img(img_path): + img = Image.open(img_path) + return np.array(img) + +def split_data(all_img_lst, train_frac, test_frac): + """Given the list of all images, randomly sample a portion of index as training, + validation and test set. The weight is specified as train_frac, val_frac, test_frac + """ + leng = len(all_img_lst) + permuted_img = np.array(all_img_lst)[np.random.permutation(leng)] + train_idx = int(leng * train_frac) + test_idx = int(leng * test_frac) + return permuted_img[:train_idx], permuted_img[train_idx + test_idx:], permuted_img[train_idx:train_idx + test_idx] + +def convert_ann(ann): + new_ann = np.zeros_like(ann) + new_ann[ann > 0] = 255 # for all objects + for i, cls in enumerate(all_classes): + new_ann[ann == cls] = i + 1 # (cls // 10) + 1 + # new_ann[new_ann == 255] = len(all_classes) + 1 # for all objects + new_ann[new_ann == 255] = 0 # for all objects + return new_ann + +def cv2_imsave(path, img): + if img.shape[-1] == 3: + img = img[...,::-1] + cv2.imwrite(str(path), img) + +def convert_and_save(vis_paths, save_path): + save_img_path = save_path.joinpath('img') + save_img_path.mkdir(exist_ok=True, parents=True) + save_anno_path = save_path.joinpath('anno') + save_anno_path.mkdir(exist_ok=True) + for vis_path in tqdm.tqdm(vis_paths): + vis_path = str(vis_path) + img_path = vis_path.replace('_draw', '') + ann_path = img_path.replace('jpg', 'png') + img = load_img(img_path) + ann = load_ann(ann_path) + new_ann = convert_ann(ann) + cv2_imsave(str(save_anno_path.joinpath(Path(ann_path).name)), new_ann) + cv2_imsave(str(save_img_path.joinpath(Path(img_path).name)), img) + + + +if __name__ == "__main__": + + vis_paths = list(Path('all_raw').glob('*_draw.jpg')) + train_paths, val_paths, test_paths = split_data(vis_paths, 0.8, 0.1) + save_path = Path('/mnt/volume2/Data/zlz/EgoHandObject/data/epic/obj1_hand_2k') + convert_and_save(train_paths, save_path.joinpath('train')) + convert_and_save(val_paths, save_path.joinpath('val')) + convert_and_save(test_paths, save_path.joinpath('test')) + diff --git a/EgoHOS/raw/script/preprocess_script/count_hands_objects.py b/EgoHOS/raw/script/preprocess_script/count_hands_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..637da8a781b767849015d8298cc2d0e3e0766773 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/count_hands_objects.py @@ -0,0 +1,29 @@ +from PIL import Image +import numpy as np +import glob +import pdb +import os +from tqdm import tqdm + +train_dir = '../data/train/label' +val_dir = '../data/val/label' +test_dir = '../data/test_indomain/label' + +dir_list = [train_dir, val_dir, test_dir] + +hand_cnt = 0; obj_cnt = 0 +for dir in dir_list: + for file in tqdm(glob.glob(dir + '/*')): + + lbl = np.array(Image.open(file)) + unique_vals = np.unique(lbl) + + for unique_val in unique_vals: + if unique_val == 1 or unique_val == 2: + hand_cnt += 1 + elif unique_val > 2: + obj_cnt += 1 + +print(hand_cnt, obj_cnt) +pdb.set_trace() + diff --git a/EgoHOS/raw/script/preprocess_script/cut.py b/EgoHOS/raw/script/preprocess_script/cut.py new file mode 100644 index 0000000000000000000000000000000000000000..71ce558d78a82df352152c88914fc9790942bfac --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/cut.py @@ -0,0 +1,39 @@ +from PIL import Image +from tqdm import tqdm +import numpy as np +import argparse +import glob +import pdb +import os + +parser = argparse.ArgumentParser(description="resize image using bicubic upsampling") +parser.add_argument("--in_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/lama_512_pad', type=str) +parser.add_argument("--out_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/lama_512', type=str) +parser.add_argument("--ict_tf", default=False, type=bool) +parser.add_argument("--medfe_tf", default=False, type=bool) +parser.add_argument("--pad_info_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/image_512_pad_info', type=str) +parser.add_argument("--size", default=512, type=int) +args = parser.parse_args() + +os.makedirs(args.out_dir, exist_ok=True) + +for img_file in tqdm(glob.glob(args.in_dir + '/*')): + + fname = img_file.split('/')[-1].split('.')[0] + img = np.array(Image.open(img_file)) + cut_info = np.load(os.path.join(args.pad_info_dir, fname+'.npy')) + + if args.ict_tf or args.medfe_tf: + cut_info = cut_info/2 + # pdb.set_trace() + + if cut_info[0,0] == 0: + img_cut = img[args.size - int(cut_info[0,1]):,:,:] + else: + img_cut = img[:,:int(cut_info[0,1]),:] + + img_cut = Image.fromarray(img_cut.astype('uint8')) + img_cut.save(os.path.join(args.out_dir, fname+'.jpg')) + + + diff --git a/EgoHOS/raw/script/preprocess_script/dilate.py b/EgoHOS/raw/script/preprocess_script/dilate.py new file mode 100644 index 0000000000000000000000000000000000000000..af5297d1d3c34acdc94a5f794a3f1ca492e7a5cb --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/dilate.py @@ -0,0 +1,29 @@ + + +from skimage.io import imsave +from tqdm import tqdm +from PIL import Image +import numpy as np +import glob +import cv2 +import pdb +import os + +dilate_iter = 3 +msk_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_foreground_512_pad' +msk_dilate_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_foreground_512_pad_d' + +msk_dilate_dir = msk_dilate_dir + str(dilate_iter) +os.makedirs(msk_dilate_dir, exist_ok = True) + +kernel = np.ones((5,5), np.uint8) + +for file in tqdm(glob.glob(msk_dir + '/*')): + fname = os.path.basename(file) + mask = np.array(Image.open(file).convert('RGB')); mask[mask > 0] = 1 + mask_dilate = cv2.dilate(mask, kernel, iterations=dilate_iter) + imsave(os.path.join(msk_dilate_dir, fname), mask_dilate) + + + + diff --git a/EgoHOS/raw/script/preprocess_script/downsize.py b/EgoHOS/raw/script/preprocess_script/downsize.py new file mode 100644 index 0000000000000000000000000000000000000000..850bbe076f3cfa504f4861868cfa9d13fbb71cf9 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/downsize.py @@ -0,0 +1,41 @@ +import numpy as np +from PIL import Image +from tqdm import tqdm +import torch +import glob +import pdb +import os +from skimage.io import imsave +import argparse + +parser = argparse.ArgumentParser(description="resize image using nearest-neighbor upsampling") +parser.add_argument("--img_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/label', type=str) +parser.add_argument("--mask_tf", default=True, type=bool) +parser.add_argument("--max_scale", default=512, type=int) +args = parser.parse_args() + +save_dir = args.img_dir+'_'+str(args.max_scale) +os.makedirs(save_dir, exist_ok = True) + +for file in tqdm(glob.glob(args.img_dir + '/*')): + fname = file.split('/')[-1] + img = Image.open(file); w, h = img.size + + if w > h: + aspect_ratio = h/w + if args.mask_tf: + img_resize = Image.open(file).resize((args.max_scale, int(args.max_scale * aspect_ratio)), resample = Image.NEAREST) + else: + img_resize = Image.open(file).resize((args.max_scale, int(args.max_scale * aspect_ratio)), resample = Image.BICUBIC) + else: + aspect_ratio = w/h + if args.mask_tf: + img_resize = Image.open(file).resize((int(args.max_scale * aspect_ratio), args.max_scale), resample = Image.NEAREST) + else: + img_resize = Image.open(file).resize((int(args.max_scale * aspect_ratio), args.max_scale), resample = Image.BICUBIC) + + + # if not fname.startswith('20210619'): + # img_resize = Image.fromarray(np.array(np.rot90(img_resize, 3))) + + img_resize.save(os.path.join(save_dir, fname)) \ No newline at end of file diff --git a/EgoHOS/raw/script/preprocess_script/generate_contact_boundary.py b/EgoHOS/raw/script/preprocess_script/generate_contact_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..33efca201b12d291e40c0edbd89f81de9f9d1e03 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/generate_contact_boundary.py @@ -0,0 +1,70 @@ +from PIL import Image +import numpy as np +import glob +import pdb +import os +from skimage.io import imsave +import cv2 +from tqdm import tqdm + +alpha = 0.9 +kernel = np.ones((5,5), np.uint8) + +lbl_type_list = ['train', 'val', 'test_indomain', 'test_outdomain'] + +for lbl_type in lbl_type_list: + + all_img_dir = '../data/'+lbl_type+'/image' + all_label_dir = '../data/'+lbl_type+'/label' + + vis_contact_boundary_dir = '../data/'+lbl_type+'/vis_contact' + contact_boundary_dir = '../data/'+lbl_type+'/label_contact' + os.makedirs(vis_contact_boundary_dir, exist_ok = True) + os.makedirs(contact_boundary_dir, exist_ok = True) + + for file in tqdm(glob.glob(all_label_dir + '/*')): + + fname = os.path.basename(file) + + img = np.array(Image.open(os.path.join(all_img_dir, fname.split('.')[0]+'.jpg'))) + label = np.array(Image.open(file)) + + hand_msk = np.zeros((label.shape)) + obj_msk = np.zeros((label.shape)) + + hand_msk[label==1] = 1 + hand_msk[label==2] = 1 + obj_msk[label==3] = 1 + obj_msk[label==4] = 1 + obj_msk[label==5] = 1 + + hand_msk_dialte = cv2.dilate(hand_msk, kernel, iterations=int(img.shape[1]/456)) + obj_msk_dialte = cv2.dilate(obj_msk, kernel, iterations=int(img.shape[1]/456)) + merge_hand_obj = hand_msk_dialte + obj_msk_dialte + contact_boundary = np.zeros((hand_msk.shape)) + contact_boundary[merge_hand_obj == 2] = 1 + + imsave(os.path.join(contact_boundary_dir, fname), contact_boundary.astype(np.uint8)) + + ''' + red = np.zeros((img.shape)); red[:,:,0] = 255 + blue = np.zeros((img.shape)); blue[:,:,2] = 255 + yellow = np.zeros((img.shape)); yellow[:,:,0] = 255; yellow[:,:,1] = 255; yellow[:,:,2] = 0 + contact_boundary_rgb = np.repeat(np.expand_dims(contact_boundary, 2), 3, 2) + img_contact_boundary = img * (1 - contact_boundary_rgb) + \ + yellow * contact_boundary_rgb * alpha + \ + img * contact_boundary_rgb * (1 - alpha) + + hand_msk_rgb = np.repeat(np.expand_dims(hand_msk, 2), 3, 2) + obj_msk_rgb = np.repeat(np.expand_dims(obj_msk, 2), 3, 2) + merge_hand_obj_rgb = np.repeat(np.expand_dims(merge_hand_obj, 2), 3, 2) + vis_merge_hand_obj = red * hand_msk_rgb + blue * obj_msk_rgb + # imsave('vis_merge_hand_obj.png', vis_merge_hand_obj) + + vis_merge_hand_obj = vis_merge_hand_obj * (1 - contact_boundary_rgb) + yellow * contact_boundary_rgb + imsave(os.path.join(vis_contact_boundary_dir, fname.split('.')[0]+'_lbl.jpg'), vis_merge_hand_obj) + imsave(os.path.join(vis_contact_boundary_dir, fname.split('.')[0]+'.jpg'), img_contact_boundary) + + # pdb.set_trace() + ''' + diff --git a/EgoHOS/raw/script/preprocess_script/pad.py b/EgoHOS/raw/script/preprocess_script/pad.py new file mode 100644 index 0000000000000000000000000000000000000000..fe736711a87ff76dccfd8ad26c611eb458bb7518 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/pad.py @@ -0,0 +1,60 @@ +from PIL import Image +from tqdm import tqdm +import numpy as np +import argparse +import glob +import pdb +import os + +parser = argparse.ArgumentParser(description="resize image using bicubic upsampling") +parser.add_argument("--in_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_foreground_512', type=str) +parser.add_argument("--out_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_foreground_512_pad', type=str) +parser.add_argument("--pad_info_dir", default='/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_foreground_512_pad_info', type=str) +parser.add_argument("--size", default=512, type=int) +args = parser.parse_args() + +os.makedirs(args.out_dir, exist_ok=True) +os.makedirs(args.pad_info_dir, exist_ok=True) + +i = 0 +for img_file in tqdm(glob.glob(args.in_dir+'/*')): + + fname = img_file.split('/')[-1] + + img = np.array(Image.open(img_file)) + w, h = img.shape[0], img.shape[1] + + if len(img.shape) == 3: + img_pad = np.zeros((args.size, args.size, img.shape[2])) + else: + img_pad = np.zeros((args.size, args.size)) + + pad_info = np.zeros((1,2)) + + if w < h: + if len(img.shape) == 3: + img_pad[args.size - w:, :, :] = img + else: + img_pad[args.size - w:, :] = img + pad_info[0, 0] = 0 + pad_info[0, 1] = w + else: + if len(img.shape) == 3: + img_pad[:, :h, :] = img + else: + img_pad[:, :h] = img + pad_info[0, 0] = 1 + pad_info[0, 1] = h + + img_pad = Image.fromarray(img_pad.astype('uint8')) + img_pad.save(os.path.join(args.out_dir, fname)) + + np.save(os.path.join(args.pad_info_dir, str(fname.split('.')[0])+'.npy'), pad_info) + + i += 1 + + # pdb.set_trace() + + + + \ No newline at end of file diff --git a/EgoHOS/raw/script/preprocess_script/png2jpg.py b/EgoHOS/raw/script/preprocess_script/png2jpg.py new file mode 100644 index 0000000000000000000000000000000000000000..d602c6933eac7fc1893ee7794d36785ff8367909 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/png2jpg.py @@ -0,0 +1,14 @@ +from PIL import Image +import glob +import pdb +import os +from tqdm import tqdm + +img_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/lama_512' + +for file in tqdm(glob.glob(img_dir + '/*.png')): + fname = os.path.basename(file).split('.')[0] + img = Image.open(file) + img.save(os.path.join(img_dir, fname + '.jpg')) + os.remove(file) + diff --git a/EgoHOS/raw/script/preprocess_script/resize_image_label.py b/EgoHOS/raw/script/preprocess_script/resize_image_label.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e7e6d2f31df058d103af118567d103e665777e --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/resize_image_label.py @@ -0,0 +1,60 @@ +""" + This script converts label into different version, depending + on the task (allhands, twohands, handobj1, etc.) +""" +from PIL import Image +import numpy as np +import glob +import pdb +import os +from skimage.io import imsave +from tqdm import tqdm + + + +if __name__ == '__main__': + + lbl_type_list = ['train', 'val', 'test_indomain', 'test_outdomain'] + + for lbl_type in lbl_type_list: + + print('processing: ' + lbl_type) + + img_dir = '../data/'+lbl_type+'/image' + lbl_dir = '../data/'+lbl_type+'/label' + lbl_allhands_dir = '../data/'+lbl_type+'/label_allhands' + lbl_twohands_dir = '../data/'+lbl_type+'/label_twohands' + lbl_handobj1_dir = '../data/'+lbl_type+'/label_handobj1' + + dst_img_dir = img_dir + '_downsize'; os.makedirs(dst_img_dir, exist_ok = True) + dst_lbl_dir = lbl_dir + '_downsize'; os.makedirs(dst_lbl_dir, exist_ok = True) + dst_lbl_allhands_dir = lbl_allhands_dir + '_downsize'; os.makedirs(dst_lbl_allhands_dir, exist_ok = True) + dst_lbl_twohands_dir = lbl_twohands_dir + '_downsize'; os.makedirs(dst_lbl_twohands_dir, exist_ok = True) + dst_lbl_handobj1_dir = lbl_handobj1_dir + '_downsize'; os.makedirs(dst_lbl_handobj1_dir, exist_ok = True) + + for img_file in tqdm(glob.glob(img_dir + '/*')): + + fname = os.path.basename(img_file).split('.')[0] + lbl_file = os.path.join(lbl_dir, fname + '.png') + lbl_allhands_file = os.path.join(lbl_allhands_dir, fname + '.png') + lbl_twohands_file = os.path.join(lbl_twohands_dir, fname + '.png') + lbl_handobj1_file = os.path.join(lbl_handobj1_dir, fname + '.png') + + img = Image.open(img_file).resize((480, 360)) + lbl = Image.open(lbl_file).resize((480, 360)) + lbl_allhands = Image.open(lbl_allhands_file).resize((480, 360)) + lbl_twohands = Image.open(lbl_twohands_file).resize((480, 360)) + lbl_handobj1 = Image.open(lbl_handobj1_file).resize((480, 360)) + + img.save(os.path.join(dst_img_dir, fname + '.jpg')) + lbl.save(os.path.join(dst_lbl_dir, fname + '.png')) + lbl_allhands.save(os.path.join(dst_lbl_allhands_dir, fname + '.png')) + lbl_twohands.save(os.path.join(dst_lbl_twohands_dir, fname + '.png')) + lbl_handobj1.save(os.path.join(dst_lbl_handobj1_dir, fname + '.png')) + + + # pdb.set_trace() + + + + diff --git a/EgoHOS/raw/script/preprocess_script/sample_subset.py b/EgoHOS/raw/script/preprocess_script/sample_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..ee87143b31efaaa75cb63e2e5eb1efefab696dbc --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/sample_subset.py @@ -0,0 +1,39 @@ +from shutil import copyfile +import glob +import pdb +import os +import random +from tqdm import tqdm + +img_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/image' +lbl_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/label' + +sub_k_list = [200] +# ,500,1000] + +fname_list = [] +for file in glob.glob(img_dir + '/*'): + fname = os.path.basename(file) + fname_list.append(fname) + +for sub_k in sub_k_list: + + sub_img_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/image_' + str(sub_k); os.makedirs(sub_img_dir, exist_ok = True) + sub_lbl_dir = '/mnt/session_space/home/lingzzha/EgoHOS/data/train/label_' + str(sub_k); os.makedirs(sub_lbl_dir, exist_ok = True) + + print('Processing: ', sub_k) + sub_fname_list = random.sample(fname_list, sub_k) + for fname in tqdm(sub_fname_list): + + src_img_file = os.path.join(img_dir, fname) + dst_img_file = os.path.join(sub_img_dir, fname) + copyfile(src_img_file, dst_img_file) + + src_lbl_file = os.path.join(lbl_dir, fname.split('.')[0] + '.png') + dst_lbl_file = os.path.join(sub_lbl_dir, fname.split('.')[0] + '.png') + copyfile(src_lbl_file, dst_lbl_file) + + + + + diff --git a/EgoHOS/raw/script/preprocess_script/sample_testimages.py b/EgoHOS/raw/script/preprocess_script/sample_testimages.py new file mode 100644 index 0000000000000000000000000000000000000000..17b9a49ea9aaa2c1ec3a9b24a1239757b9d53d81 --- /dev/null +++ b/EgoHOS/raw/script/preprocess_script/sample_testimages.py @@ -0,0 +1,24 @@ +from shutil import copyfile +from tqdm import tqdm +import random +import glob +import pdb +import os + +indomain_test_dir = '../data/test_indomain/image' +outdomain_test_dir = '../data/test_outdomain/image' +sample_test_dir = '../testimages' +os.makedirs(sample_test_dir, exist_ok = True) + +indomain_test_files = glob.glob(indomain_test_dir + '/*') +outdomain_test_files = glob.glob(outdomain_test_dir + '/*') + +sample_test_files = random.sample(indomain_test_files, 10) + random.sample(outdomain_test_files, 10) + +for sample_test_file in tqdm(sample_test_files): + fname = os.path.basename(sample_test_file) + dst_file = os.path.join(sample_test_dir, fname) + copyfile(sample_test_file, dst_file) + + # pdb.set_trace() + diff --git a/EgoHOS/raw/script/requirements.txt b/EgoHOS/raw/script/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e677c388de7578e19707446d133e97ba1bccb14f --- /dev/null +++ b/EgoHOS/raw/script/requirements.txt @@ -0,0 +1,4 @@ +torch==1.11.0 +torchvision +scikit-image +imageio-ffmpeg \ No newline at end of file