Deeplearning中常用转换速查
1、numpy和PIL互转
from PIL import Image import numpy as np import cv2 img = cv2.imread('image.jpg') np.size(img,0) #0,1,2 print(type(img)) #numpy to PIL pil_img= Image.fromarray(img) print(type(pil_img)) #PIL to numpy np_img= np.array(pil_img) print(type(np_img))
2、tensor(pytorch)和numpy互转
import torch import numpy as np #tensor to numpy torch_img = torch.ones(5) print(torch_img) torch_img+=1 np_img = torch_img.numpy() print(torch_img, np_img) #numpy to tensor np_img = np.ones(9) print(np_img) torch_img = torch.from_numpy(np_img) np_img+=1 print(np_img, torch_img)
#tensor to numpy