SoFunction
Updated on 2024-11-13

Example of python, PyTorch image reading and numpy conversion

Tensor to numpy

(Tensor)

numpy to Tensor conversion

()

Convert to numpy

()

numpy to

()

The first thing you need to do is make sure to convert to np.uint8.

(np.uint8), pixel value [0,255].

Also the grayscale image is guaranteed to be (H,W) and no channels can appear

Required here (). The color image is guaranteed to be (H,W,3)

later ()

Convert to Tensor

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

import  as transforms trans=([()])

a=trans(img)

Tensor is transformed into

Convert first to numpy, then to

gray-scale image

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

import  as transforms
trans=([()])

a=trans(img)
b=(a) # (1,64,64)
maxi=()
b=b*255./maxi
b=(1,2,0).astype(np.uint8)
b=(b,axis=2)
xx=(b)
xx

color image

img2=('00381fa010_940422.tif').convert('RGB')
import  as transforms
trans=([()])
a=trans(img2)
a=(a)
maxi=()
a=a/maxi*255
a=(1,2,0).astype(np.uint8)
b=(a)
b

python-opencv

import cv2
a=('00381fa010_940422.tif') # (64,64,3)
('',a)
(a)
b=('00381fa010_940422.tif',0)# (64,64)
(b)

() returns, after reading the grayscale image shape is (64,64), RGB image shape is (64,64,3), can be directly converted to Image with ().

When cv writes an image, the grayscale image shape can be (H,W) or (H,W,1). Color image (H,W,3)

To get from, the grayscale map must have a shape of (H,W) and a color of (H,W,3)

For Variable type can not be converted directly, you need to use .data conversion

()

Above this python, PyTorch image reading and numpy conversion example is all I have shared with you, I hope to give you a reference, and I hope you support me more.