基础
- opencv读取RBG的图像后,会存为BGR矩阵,像素范围0~255 ,uint8;
- PIL.Image 读取RGB图像后会存储为对象,需要手动转化格式,像素范围0~1;
- opencv读取图像后可以当作np的ndarray操作。
代码
from PIL import Image
import numpy as np
im_pth = '1603115.jpg'
im = Image.open(im_pth).convert('RGB')
im.save('test.jpg')
# PIL 转化为numpy
im_np = np.asarray(im) # 0~255
# numpy 转化为 PIL
data_img = Image.fromarray(im_np)
# or
data_img = np.uint8(im_np)
data_img = Image.fromarray(data_img) # 0~255
# RGB2BGR
r, g, b = data_img.split()
data_img = Image.merge("RGB", (b, g, r))
im_bgr = cv2.imread(im_pth) # RGB图像,默认转化为BGR矩阵 0~255
cv2.imwrite('test4.jpg',im_bgr)# 默认BGR矩阵,最终存为RGB图像
# 转化为RGB
img_rgb = cv2.cvtColor(im_bgr, cv2.COLOR_BGR2RGB)
# opencv转PIL
img_rgb = Image.fromarray(img_rgb)
img_rgb.save('test5.jpg')
# 转化为tensor格式,whc-> cwh
# opencv读取的图像可以直接用np操作
img_tensor = np.transpose(im_BGR/255., (2,0,1))