tensor的分块与还原
代码
from PIL import Image
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import SimpleITK as stk
import torch
# 读取图像并转为tensor
def readImage(path='D:\微信图片_20200304231857.jpg', size=1000):#这里可以替换成自己的图片
mode = Image.open(path)
mode = mode.convert('L')
transform1 = transforms.Compose([
transforms.Scale(size),
transforms.CenterCrop((size, size)),
transforms.ToTensor()
])
mode = transform1(mode)
return mode
# 显示图片
def showTorchImage(image):
mode = transforms.ToPILImage()(image)
plt.imshow(mode)
plt.show()
# 图像分块
def tensor_spilt(munber: int, image):
c, h, w = asdw.shape
# image = image.copy()
image = torch.chunk(image, munber, -1)
result = torch.cat(image, 0)
image = torch.chunk(result, munber, -2)
result = torch.cat(image, 0)
return result
# 图像还原
def tensor_cat(number: int, image):
result = torch.cat([torch.cat([image[2*ii+i] for i in range(number)], -1)
for ii in range(number)], -2)
return result
# 主代码
asdw = readImage('C:\\Users\\HZH\\Desktop\\1.png')
c, h, w = asdw.shape
a = asdw[0].unsqueeze(0)
showTorchImage(a)
a2 = tensor_spilt(2, a)
for i in a2:
showTorchImage(i)
a3 = tensor_cat(2, a2)
showTorchImage(a3)
原图
分割后的图片
还原后的图片
参考: https://blog.csdn.net/sinat_42239797/article/details/104666149.