Pytorch中的variable, tensor与numpy相互转化的方法

1.加载需要用到的模块

import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

2.显示图片与图片中的一部分区域

test_img = mpimg.imread('example1.jpg')
i_x = 20
i_y = 85
sub_img = test_img[i_y:i_y + 100,i_x:i_x + 100,:] #numpy类型

3.numpy矩阵转换为Tensor张量

sub_ts = torch.from_numpy(sub_img)   #sub_img为numpy类型

4.Tensor张量转化为numpy矩阵

sub_np1 = sub_ts.numpy()             #sub_ts为tensor张量

5.numpy转换为Variable

sub_va = Variable(torch.from_numpy(sub_img))

6.Variable张量转化为numpy

sub_np2 = sub_va.data.numpy()

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/82498229