图像常规变换之归一化/反归一化变换,RGB通道变换

万地高楼平地起,啥事都得靠自己~

在训练的时候,我们经常对图像进行归一化变换,RGB通道变换,然后预测的时候,又要变换回来,记录一下如何还原的;

Talk is cheap,show me the code!

import torch
import torch.nn as nn
from torchvision import transforms
from PIL import Image
import numpy as np

# Image open方式读取图像,读取出来的顺序是RGB格式;
image_path = './test.jpeg'
imgs = Image.open(image_path)
# 展示图像
imgs.show()

# 转化为tensor,主要是做了 /255 操作;
# Normalize , 主要是做了 (img - mean)/std 的操作;
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
transforms = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean,  # 归一化
                         std)
])

##图像经过transformer的转换
output_images = transforms(imgs)
##输出images的大小shape;
print('output shape is :', output_images.size())

#反归一化----
for i in range(len(mean)):
    output_images[i] = output_images[i] * std[i] + mean[i]

import cv2
# 乘以255变换
output_images = output_images * 255

# HWC --> CHW通道变换;tensor变换为numpy;
output = np.array(np.transpose(output_images, (1, 2, 0)))
# 将图像的RGB通道 转换为BGR通道;
aaa = output[:, :, (2, 1, 0)]
# 将图像保存opencv方式;
cv2.imwrite('output.jpg', np.uint8(aaa))
# 将图像保存pillow方式;
# output1 = Image.fromarray(np.uint8(output))
# output1.save('11.jpg')

测试图片:

图像常规变换之归一化/反归一化变换,RGB通道变换_第1张图片

output图片:

图像常规变换之归一化/反归一化变换,RGB通道变换_第2张图片

可以看到前后一致,记录一下,为后人乘凉;

有问题随时交流,欢迎一键三连!

你可能感兴趣的:(基础算法,计算机视觉,深度学习,python)