Torch.nn.Pytorchのアップサンプル



Torch Nn Upsample Pytorch



Torch.nn.Pytorchのアップサンプル

最近、deeplabシリーズのセマンティックセグメンテーション実験を再現しました。 torch.nn.Upsampleに遭遇しました。この関数を読んだ後、そのネットワーク分析を理解できませんでした。私は自分でいくつかのテストを実施しました。



公式ノート

def upsample(input、size = None、scale_factor = None、mode = ‘nearest’、align_corners = None):
r '' '指定された:attr:sizeのいずれかに入力をアップサンプリングします。または与えられた
:attr:scale_factor



The algorithm used for upsampling is determined by :attr:`mode`. Currently temporal, spatial and volumetric upsampling are supported, i.e. expected inputs are 3-D, 4-D or 5-D in shape. The input dimensions are interpreted in the form: `mini-batch x channels x [optional depth] x [optional height] x width`. The modes available for upsampling are: `nearest`, `linear` (3D-only), `bilinear` (4D-only), `trilinear` (5D-only) Args: input (Tensor): the input tensor size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]): output spatial size. scale_factor (int): multiplier for spatial size. Has to be an integer. mode (string): algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' | 'trilinear'. Default: 'nearest' align_corners (bool, optional): if True, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels. This only has effect when :attr:`mode` is `linear`, `bilinear`, or `trilinear`. Default: False

nn.Upsampleは、アップサンプリング操作に使用されます。定義の観点から、Upsampleには次の4つのパラメーターがあります。
(1)サイズ:サイズは出力のサイズを決定し、出力のタイプは入力と一致します
(2)scale_factor:出力を入力の倍数として指定するために使用されます。出力タイプも入力と一致します。
(3)モード:モードパラメータは、アップサンプリングに使用されるアルゴリズムを決定します。これには、「最も近い」、「線形」、「双一次」、「双一次」、「三線形」の5種類の方法が含まれ、デフォルトは「最も近い」です。
(4)align_corners:Trueの場合、入力コーナーピクセルは出力テンソルと位置合わせされるため、これらのピクセルの値が保存されます。使用するアルゴリズムが「線形」、「双線形」、または「三線形」の場合にのみ使用できます。デフォルト設定はFalseです

テスト

アップサンプル関数に遭遇すると、グラウンドトゥルース画像でアップサンプリングを実行するために使用されるため、関数の効果をテストするためにラベル画像が選択されます。
元の画像は次のとおりです。
画像



dir='data/VOCdevkit/VOC2012/SegmentationClass/2007_000042.png' i = Image.open(dir).convert('P') i= np.asarray(i, np.int32) i[i== 255] = 0 plt.imshow(i)

上記のコードはラベル画像を処理するために使用され、最後にImage.open()関数によって開かれた4チャンネル画像をシングルチャンネル画像に変換できます。画像のピクセル値はオブジェクトカテゴリのラベル値であり、範囲は0〜20です(voc背景を含む21のカテゴリのデータがあります)。
上記のコードの結果を以下に示します。

画像

i = cv2.resize(i, (321, 321), interpolation=cv2.INTER_NEAREST) plt.imshow(i)

次に、cv2モジュールを使用して画像を321 * 321サイズにトリミングすると、結果は次のようになります。 画像
次のアップサンプリング操作であるモードは、バイリニアとして選択されます

import torch i = torch.Tensor(torch.from_numpy(i[None, None, :, :].astype(np.float32()))) size1=math.ceil(321/8.) interp = nn.Upsample(size=(size1, size1), mode='bilinear', align_corners=True) gt1 = interp(i).data.numpy()[0, 0, :, :] plt.imshow(gt1)


上記は、2次元画像に対するアップサンプルの効果を確認できます。画像のサイズは縮小されますが、詳細は保存できます。