7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Tensor Numpy PIL image 相互変換【PyTorch】

Posted at

目的

PyTorchで画像等を扱っていると、Tensor、Numpy、PIL imageのそれぞれの形式に変換したい場合が多々ある。
ここでは、備忘録としてそれぞれの形式に対する相互変換方法を示す。

各データ形式の特徴

  • Tensor:学習モデルへの入力や中間層での計算に用いる。torchvisionを用いると各種画像処理が楽に行える。
  • Numpy:Numpyの機能はほぼTensorでも使用可能だが、matplotlibでデータを扱いたい場合に変換が必要。
  • PIL:画像の読み込みや書き出し、簡単な画像処理などを行える。

各種変換方法

Tensor ↔ Numpy

import torch
import numpy as np

# tensor -> numpy
t = torch.zeros(3,128,128)
n = t.to('cpu').detach().numpy()

# numpy -> tensor
n = np.zeros((3,128,128))
t = torch.from_numpy(n)

Numpy ↔ PIL image

from PIL import Image
import numpy as np

# numpy -> PIL image
n = np.zeros((128,128,3))
p = Image.fromarray(np.uint8(n))

# PIL image -> numpy
p = Image.open('sample.jpg')
n = np.array(p)

PIL image ↔ Tensor

from PIL import Image
import torch
import torchvision

# PIL image -> tensor
p = Image.open('sample.jpg')
t = torchvision.transforms.functional.to_tensor(p)

# tensor -> PIL image
t = torch.zeros(3,128,128)
p = torchvision.transforms.functional.to_pil_image(t)

参考

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?