【opencv和PIL打开图片的格式区别】

【opencv和PIL打开图片的格式区别】

打开图片:
在这里插入图片描述
注:以下代码由Jupyter notebook编写

1、opencv读取的图片,形状为(高,宽,通道)

import cv2
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np

import torchvision.transforms as transforms

img_cv2 = cv2.imread('mountain.jpg')
print(img_cv2 .shape)    # (高,宽,通道)
print(img_cv2 .shape[1])
print(type(img_cv2 ))
plt.imshow(img_cv2 )
plt.show()

输出为:

(975, 650, 3)
650
<class 'numpy.ndarray'>

Alt

2、numpy.ndarray转为PIL的格式(宽,高)

img_PIL = Image.fromarray(img_cv2)
print(type(img_PIL))
print(img_PIL.size)    # (宽,高)

输出为:

<class 'PIL.Image.Image'>
(650, 975)

3、PIL读取图片,形状为(宽,高)

img_PIL = Image.open('mountain.jpg')

print(type(img_PIL))
print(img_PIL.size)    # (宽,高)
Size = img_PIL.size  # 返回图片 宽高 的一个元组,单位是像素
w = img_PIL.width  # 图片的宽
h = img_PIL.height  # 图片的高
f = img_PIL.format  # 图像格式

print(Size)
print('宽:',w,'  高:', h, '   格式:', f)

输出为:

<class 'PIL.JpegImagePlugin.JpegImageFile'>
(650, 975)
(650, 975)
宽: 650   高: 975    格式: JPEG

4、PIL图转为numpy.ndarray的格式(高,宽,通道)

array_img_PIL = np.array(img_PIL)
print(type(array_img_PIL))
print(array_img_PIL.shape)    # (高,宽,通道)

输出为:

<class 'numpy.ndarray'>
(975, 650, 3)

5、numpy.ndarray转为tensor的格式(通道,高,宽)

转为tensor后像素灰度值由之前[0,255]的整数区间归一化为[0,1]的小数区间

totensor = transforms.ToTensor()
img_tensor = totensor(array_img_PIL)
print(type(img_tensor))
print(img_tensor.shape)
print(img_tensor[1,1,0:650])

输出为:

<class 'torch.Tensor'>
torch.Size([3, 975, 650])
tensor([0.8431, 0.7451, 0.4980, 0.4863, 0.4157, 0.3294, 0.3647, 0.8627, 0.8235,
        0.8353, 0.8235, 0.8275, 0.8196, 0.8078, 0.8431, 0.3137, 0.1843, 0.3098,
        0.1490, 0.1725, 0.2118, 0.2706, 0.2745, 0.2431, 0.2196, 0.5765, 0.4157,
        0.3373, 0.8431, 0.8353, 0.8196, 0.8275, 0.8314, 0.8353, 0.8431, 0.8510,
...
        0.8275, 0.8314, 0.8314, 0.8275, 0.8314, 0.8275, 0.8275, 0.8275, 0.8314,
        0.8314, 0.8314, 0.8314, 0.8314, 0.8275, 0.8275, 0.8275, 0.8196, 0.8078,
        0.7961, 0.7961, 0.7882, 0.7843, 0.7765, 0.7725, 0.7686, 0.7608, 0.7569,
        0.7569, 0.7569])

6、tensor转为numpy.ndarray的格式(通道,高,宽)

img_numpy = img_tensor.numpy()
print(type(img_numpy))
print(img_numpy.shape)

输出为:

<class 'numpy.ndarray'>
(3, 975, 650)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值