Examples of python, pytorch image reading and numpy conversion

Time:2021-2-15

Tensor to numpy

np.array(Tensor)

Numpy to tensor

torch.Tensor(numpy.darray)

PIL.Image.Image Convert to numpy

np.array(PIL.Image.Image)

Numpy to PIL.Image.Image

Image.fromarray(numpy.ndarray)

First of all, it needs to be guaranteed numpy.ndarray convert to np.uint8 type

numpy.astype ( np.uint8 ), pixel value [0255].

At the same time, the gray image is guaranteed numpy.shape Is (h, w), channels cannot appear

We need it here np.squeeze ()。 Color image assurance numpy.shape Is (h, W, 3)

after Image.fromarray ( numpy.ndarray )

PIL.Image.Image Convert to tensor

torchvision.transfrom


img=Image.open('00381fa010_940422.tif').convert('L')

import torchvision.transforms as transforms trans=transforms.Compose([transforms.ToTensor()])

a=trans(img)

Tensor to PIL.Image.Image

First to numpy, then to PIL.Image.Image

Grayscale image


img=Image.open('00381fa010_940422.tif').convert('L')

import torchvision.transforms as transforms
trans=transforms.Compose([transforms.ToTensor()])

a=trans(img)
b=np.array(a) #b.shape (1,64,64)
maxi=b.max()
b=b*255./maxi
b=b.transpose(1,2,0).astype(np.uint8)
b=np.squeeze(b,axis=2)
xx=Image.fromarray(b)
xx

Color image


img2=Image.open('00381fa010_940422.tif').convert('RGB')
import torchvision.transforms as transforms
trans=transforms.Compose([transforms.ToTensor()])
a=trans(img2)
a=np.array(a)
maxi=a.max()
a=a/maxi*255
a=a.transpose(1,2,0).astype(np.uint8)
b=Image.fromarray(a)
b

python-opencv


import cv2
a=cv2.imread('00381fa010_940422.tif') #a.shape (64,64,3)
cv2.imwrite('asd.jpg',a)
Image.fromarray(a)
b=cv2.imread('00381fa010_940422.tif',0)#b.shape (64,64)
Image.fromarray(b)

CV2. Imread() returns numpy.darray After reading the gray image, the shape is (64,64), and the shape of RGB image is (64,64,3) Image.fromarray () to image.

When CV is used to write an image, the gray image shape can be (h, w) or (h, W, 1). Color image (h, W, 3)

To start with numpy.ndarray obtain PIL.Image.Image , the shape of gray image must be (h, w), and the color must be (h, W, 3)

The variable type cannot be directly converted to numpy.ndarray , which needs to be converted with. Data

np.array(a.data)

The above example of Python and pytorch image reading and numpy conversion is the whole content shared by Xiaobian. I hope it can give you a reference and support developer.