0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PyTorch】torchvision入門

Last updated at Posted at 2025-05-24

torchvision.transforms

transforms.ToTensor

torchvision.transforms.ToTensorは画像ファイルから読み込んだNumPyPillow形式の配列をPyTorch形式に変換するtorchvisionのクラスです。torchvision.transforms.ToTensorの処理は下記のようなプログラムを動かすことで確認することができます。

from PIL import Image
import numpy as np 

import torch
import torchvision.transforms as transforms

file_path = "images/plane.jpg"

img = Image.open(file_path).convert("RGB")
img_numpy = np.array(img)
img_transformed = transforms.ToTensor()(img)


print(type(img))
print(type(img_numpy))
print(type(img_transformed))

print("=====")

print(np.min(img_numpy), np.max(img_numpy))
print(img_transformed.min().item(), img_transformed.max().item())

・実行結果

<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
<class 'torch.Tensor'>
=====
0 255
0.0 1.0

実行結果より、torchvision.transforms.ToTensorによって0〜255の整数が0.0〜1.0の小数に変換されることが確認できます。値の変換にあたっての対応については下記のプログラムを実行することで確認できます。

from PIL import Image
import numpy as np 

import torch
import torchvision.transforms as transforms

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_theme()


file_path = "images/plane.jpg"
output_path = "figure/hist.png"

img = Image.open(file_path).convert("RGB")
img_numpy = np.array(img)
img_transformed = transforms.ToTensor()(img)

fig, ax= plt.subplots(1, 2, figsize=(10, 5))

ax[0].hist(img_numpy.reshape([-1, 1]), bins=20)
ax[1].hist(img_transformed.numpy().reshape([-1, 1]), bins=20)

plt.savefig(output_path)

・実行結果
hist.png

実行結果よりtorchvision.transforms.ToTensorを用いた処理では値の正規化などは行われていないことが確認できます。

transforms.Resize

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?