numpy PIL tensor之间的相互转换

图片的读取通常有两种格式,一种是PIL,一种是opencv。两种读取方式存在一些区别

  1. 图片格式不同,Image读入的是“RGB”,Opencv读入的是“BGR”
  2. 读入图片的尺寸不同,Image读入的是 w h,Opencv读入的是h w c。其中w是宽,h是高,c是通道数。
  3. Image读入是Image类无法直接显示其像素点的值(可以转换成numpy显示),Opencv读入的直接是numpy的格式。可以直接显示其像素值。

PIL和opencv读取图片 

import os.path
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

##Image 读取图片
image = Image.open("1.jpg").convert("RGB")
##opencv 读取图片
image2 = cv2.imread("1.jpg")
print("Image read",image.size)  # w h
print("Opencv read",image2.shape)  # h w c

PIL 读取的图片是PIL格式,需要转换为numpy或者tensor格式进行数据处理。opencv读取的图片直接就是numpy格式。

PIL与tensor的相互转换

可以利用torchvision中的transforms类中ToTensor()和ToPILImage()两个函数将PIL的格式和tensor格式互相转换。注意,转换后的像素点发生的变化..。

这里opencv像素点范围是0-255,tensor像素点范围是0-1

import os.path
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

image = Image.open("1.jpg").convert("RGB")
image2 = cv2.imread("1.jpg")
image_tensor = transforms.ToTensor()(image)
image_recover = transforms.ToPILImage()(image_tensor)
image_tensor_add = image_tensor.unsqueeze(0)  ##增加一维
print("Image read",image.size)  # w h
print("Opencv read",image2.shape)  # h w c
print("tensor",image_tensor.size()) #c h w
print("tensor recover to Image",image_recover.size)
print("tensor add ",image_tensor_add.size())

numpy 和 tensor 相互转换

注意:numpy格式的图片是numpy.uint8,tensor格式的图片的数据类型是torch.float32。

import os.path
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

#方法一:直接转换
image_tensor_from_numpy = transforms.ToTensor()(image)
print("image_tensor_from_numpy: ",image_tensor_from_numpy.shape)
#方法二
image_tensor_from_numpy2 = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) #先将 BGR 变为 RGB
image_tensor_from_numpy2 = torch.from_numpy(image_tensor_from_numpy2.transpose((2, 0, 1)))
# 将 (h,w,c)转换为 (c,h,w)
image_tensor_from_numpy2 = image_tensor_from_numpy2.float().div(255) #归一化到[0,1]
print("image_tensor_from_numpy2 :",image_tensor_from_numpy2.size())
image_numpy_form_Image = np.array(image)
image_numpy_form_Image = cv2.cvtColor(image_numpy_form_Image,cv2.COLOR_RGB2BGR)
print("image_numpy_form_Image ",image_numpy_form_Image.shape)

 注意:PIL和opencv读取的图片格式不同,因此通常进行格式转换

参考文献:

pytorch中图片类型的转换——PIL、tensor、numpy_长歌丶采薇的博客-CSDN博客_pil转numpy

Pytorch中Tensor与各种图像格式(PIL 和 Numpy)的相互转化_Phoenixtree_DongZhao的博客-CSDN博客_pil 转化为numpy

你可能感兴趣的:(python,opencv,python,numpy)