第14章コンピュータビジョン
14.12.3. Preprocessing and Postprocessing14.12.3 前処理と後処理
Below, we define two functions for preprocessing and postprocessing images. The
preprocess function standardizes each of the three RGB channels of the input image and transforms the results into the CNN input format. The postprocess function restores the pixel values in the output image to their original values before standardization. Since the image printing function requires that each pixel has a floating point value from 0 to 1, we replace any value smaller than 0 or greater than 1 with 0 or 1, respectively.英語のヒント
下では、画像の前処理と後処理のための二つの関数を定義する。
preprocess関数は、入力画像の三つのRGBチャネルのそれぞれを標準化し、その結果をCNNの入力形式に変換する。postprocess関数は、出力画像の画素値を、標準化する前の元の値に戻す。画像を出力する関数では各画素が0から1の浮動小数点の値をもつ必要があるので、0より小さい値や1より大きい値は、それぞれ0か1に置き換える。rgb_mean = torch.tensor([0.485, 0.456, 0.406])
rgb_std = torch.tensor([0.229, 0.224, 0.225])
def preprocess(img, image_shape):
transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize(image_shape),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=rgb_mean, std=rgb_std)])
return transforms(img).unsqueeze(0)
def postprocess(img):
img = img[0].to(rgb_std.device)
img = torch.clamp(img.permute(1, 2, 0) * rgb_std + rgb_mean, 0, 1)
return torchvision.transforms.ToPILImage()(img.permute(2, 0, 1))