当前位置:网站首页>Readimg: read picture to variable variable variable

Readimg: read picture to variable variable variable

2022-06-23 16:15:00 Growth of code Xiaobai

from PIL import Image
from torch.autograd import Variable
from torchvision import transforms

transform = transforms.Compose(
    [ 
     #  Function acceptance PIL Image or numpy.ndarray, Put it first by HWC Transpose to CHW Format , And then to float Then divide each pixel by 255
     transforms.ToTensor(), 
     #  Standardize data by channel to [-1,1], If the data is distributed in (0,1) Between , Network last bias It may be relatively large , When the model is initialized b=0 Of , This will lead to slow network convergence , after Normalize after , It can speed up the convergence of the model 
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
     # transforms.Normalize((0.5), (0.5))])
	
def readImg(opt,imgPath):
    img = Image.open(imgPath)  # RGB, h*w*c
    # img = img.convert('L') # L = R * 0.299 + G * 0.587+ B * 0.114
    # img.show()
    
    # resize/crop
    height = width = opt.input_size
    img = img.resize((height, width), Image.BILINEAR)
	
	#  from PIL turn Tensor type 
	t_img = transform(img) 
	
	# tensor It's not back propagation ,variable It can be propagated back .Varibale There are three properties {data:tensor, grad:  preservation data Gradient of , grad_fn:  Point to Function object , For gradient calculation of back propagation }
    img = Variable(img)
    return img

After the above conversion tensor turn PIL The process is as follows :

image = im_tensor.cpu().clone()
image = image.squeeze(0) #  Compress one dimension 
image = transforms.ToPILImage(image) #  Automatic conversion to 0-255
原网站

版权声明
本文为[Growth of code Xiaobai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231508506618.html

随机推荐