import
from PIL import Image
from torchvision.transforms import ToTensor,ToPILImage
三种图片与tensor互转
# 1 pil
# img_ceshi = Image.open('./data/images/zidane.jpg')
# 2 plt
# img_ceshi = plt.imread('./data/images/zidane.jpg')
# 3 opencv
img_ceshi = cv2.imread('./data/images/zidane.jpg')
img_ceshi=Image.fromarray(cv2.cvtColor(img_ceshi,cv2.COLOR_BGR2RGB))
plt.imshow(img_ceshi)
plt.show()
img_ceshi_tensor=ToTensor()(img_ceshi)
print(img_ceshi_tensor.shape)
img_ceshi_plt=ToPILImage()(img_ceshi_tensor)
plt.imshow(img_ceshi_plt)
plt.show()
t_img_part=img_ceshi_tensor[:,:-500,100:1000]
plt.imshow(ToPILImage()(t_img_part))
plt.show()
三种图片互转
pil和plt格式完全一样
实际上只有opencv与pil互转
cv转pil
img_pil=Image.fromarray(cv2.cvtColor(img_cv,cv2.COLOR_BGR2RGB))
pil转cv
img_cv= np.array(img_pil)[...,::-1]