本文已参加「新人创造礼」活动,一同敞开创造之路。

1 opencv读取数据的通道次序

1.1 opencv读取数据相关阐明

  • opencv默许读取的色彩通道次序是:BGR
  • opencv读取的数据类型numpy数组,是uint8的整型数据,规模为0-255
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
#1 opencv读取数据的通道次序  默许读取的色彩通道是BGR  数据通道次序是 hwc
def opencv_channel(img_path, show_mode=1):
    image = cv2.imread(img_path)
    print(f"image type: {type(image)}, image shape: {image.shape}")  # image shape: (305, 500, 3)   h w c
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)
    print(f"image type: {image.dtype}")  # image type: uint8
    print(f"min value: {np.min(image)}, max value: {np.max(image)}")  # min value: 0, max value: 255
    if show_mode == 1:
        # 假如用matplotlib显现opencv读取的图片,图片会发蓝,这是由于opencv读取的色彩通道次序是BGR,而matplotlib读取的色彩通道次序是RGB
        plt.imshow(image)
        plt.title("opencv BGR")
        plt.show()
    elif show_mode == 2:
        cv2.imshow("image", image)
        cv2.waitKey(0)
    # 运用plt正确显现opencv读取的数据,需求改变色彩通道次序  BGR2RGB
    # 下面三种办法都能够 把opencv读取的BGR色彩通道次序 更改为 RGB色彩通道次序
    # 办法一:
    cvColor_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # 办法二:
    b, g, r = cv2.split(image)
    cvColor_image2 = cv2.merge([r, g, b])
    # 办法三:
    cvColor_image3 = image[:, :, :: -1]
    if show_mode == 1:
        plt.imshow(cvColor_image)
        plt.title("BGR2RGB")
        plt.show()
    elif show_mode == 2:
        cv2.imshow("image", cvColor_image)
        cv2.waitKey(0)
if __name__ == '__main__':
    img_path = "./bee.jpg"
    opencv_channel(img_path)

1.2 显现opencv读取的数据

1、运用cv2.imshow()

这种显现的是正常的

2、运用plt.imshow()显现opencv读取数据

你会发现显现如下,这是由于plt默许显现的色彩通道次序为RGB,因而我们需求把opencv读取的数据从BGR转化为RGB

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

1.3 把opencv读取的BGR转化RGB的三种方式

1、办法一:

cvColor_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

2、办法二:

b, g, r = cv2.split(image) cvColor_image2 = cv2.merge([r, g, b])

3、办法三:

cvColor_image3 = image[:, :, :: -1]

BGR转化为RGB之后,再用plt.imshow()进行显现,能够发现色彩已经正常了!

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

2 matplotlib读取数据的通道次序

2.1 matplotlib读取数据相关阐明

  • plt.imread()默许读取的色彩通道次序是:RGB
  • plt.imread()读取的数据类型numpy数组,是uint8的整型数据,规模为0-255
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
#2 matplotlib读取数据的通道次序  默许读取的色彩通道是RGB  数据通道次序是 hwc
def plt_channel(img_path):
    image = plt.imread(img_path)
    print(f"image type: {type(image)}, image shape: {image.shape}")
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)   h w c
    plt.imshow(image)
    plt.title("plt image")
    plt.show()
    # 能够把numpy数据转化为pillow数据
    pil_image = Image.fromarray(image)
    plt.imshow(pil_image)
    plt.title("numpy convert to pillow type")
    plt.show()
if __name__ == '__main__':
    img_path = "./bee.jpg"
    plt_channel(img_path)

显现成果如下:

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

2.2 把numpy数组类型转化为pillow类型

也能够把plt读取的numpy数组类型转化为pillow类型

pil_image = Image.fromarray(image)

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

3 pillow读取数据的通道次序

3.1 pillow读取数据相关阐明

  • pillow默许读取的色彩通道次序是:RGB
  • pillow自己的数据结构的,可是能够转化成numpy数组,转化后的数组为unit8,0-255
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
#3 pillow读取数据的通道次序
def pillow_channel(img_path, show_mode=1):
    image = Image.open(img_path)
    print(f"image mode: {image.mode}")  # image mode: RGB
    print(f"image type: {type(image)}, image shape: {image.size}")
    # image type: <class 'PIL.JpegImagePlugin.JpegImageFile'>, image shape: (500, 305)   w, h
    if show_mode == 1:
        plt.imshow(image)
        plt.title("pillow image")
        plt.show()
    elif show_mode == 2:
        image.show()
    # 把pillow数据转化为numpy数据
    np_image = np.array(image)
    print(f"image type: {type(np_image)}, image shape: {np_image.shape}")
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)   h w c
    plt.imshow(np_image)
    plt.title("pillow convert to numpy type")
    plt.show()
if __name__ == '__main__':
    img_path = "./bee.jpg"
    pillow_channel(img_path)

由于,pillow默许读取图片的色彩通道也是RGB,因而用plt显现的时分是没有问题的!显现成果如下:

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

3.2 把pillow类型转化为numpy类型

把pillow类型的数据转化为numpy数组类型数据:

np_image = np.array(image)

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

4 pytorch读取数据的通道次序

  • pytorch 读取数据类型为tensor
  • pytorch读取数据类型的通道次序为:NCHW
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
#4 pytorch读取数据的通道次序
def torch_channel(imgs_dir):
    # 1、数据增强
    train_data_transforms = transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
    ])
    # 2、从目录中读取数据集
    # 存放数据的目录
    root_data_dir = imgs_dir
    train_datasets = datasets.ImageFolder(root_data_dir, train_data_transforms)
    # 3、加载数据增强后的数据
    train_dataloaders = torch.utils.data.DataLoader(train_datasets,
                                                    batch_size=2,
                                                    shuffle=True,
                                                    num_workers=0)
    # 遍历读取数据
    for inputs, labels in train_dataloaders:
        print(f"inputs shape: {inputs.shape}")
        print(f"labels shape: {labels.shape}")
        '''
        # 输出成果:
        inputs shape: torch.Size([2, 3, 224, 224])  bs, c, h, w  即:NCHW, tensorflow读取的次序为NHWC
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        '''
        # 可视化其中的图片,batch_size=2, 因而每个batch中有存储两张图片的数据
        # 先把tensor类型转化为numpy类型
        np_inputs = inputs.numpy()
        print(f"np_inputs type: {type(np_inputs)}, np_inputs shape: {np_inputs.shape}")
        # np_inputs type: <class 'numpy.ndarray'>, np_inputs shape: (2, 3, 224, 224)
        # 更改图片的数据的通道次序, NCHW 改为 NHWC   0123   0231
        np_change_channel = np_inputs.transpose(0, 2, 3, 1 )
        print(f"np_change_channel type: {type(np_change_channel)}, np_change_channel shape: {np_change_channel.shape}")
        # np_change_channel type: <class 'numpy.ndarray'>, np_change_channel shape: (2, 224, 224, 3)
        # 显现图片,这里把每个batch中的两张图片放到一同显现
        out_image = np.hstack((np_change_channel[0], np_change_channel[1]))
        # # 假如用opencv显现需求再在转化一下色彩空间,转化为BGR,由于torchvision内部是基于Pillow完成的,默许是RGB色彩通道
        # out_image = cv2.cvtColor(out_image, cv2.COLOR_RGB2BGR)
        # cv2.imshow("image", out_image)
        # cv2.waitKey(0)
        plt.imshow(out_image)
        plt.title("pytorch tensor convert to numpy data")
        plt.show()
if __name__ == '__main__':
    imgs_dir = './hymenoptera/train'
    torch_channel(imgs_dir)

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

opencv、matplotlib、pillow和pytorch读取数据的通道顺序

5 全部完好代码

完好代码如下:

'''
比较 opencv、matplotlib、pillow 和 pytorch读取数据的通道次序
'''
__Author__ = "Shliang"
__Email__ = "shliang0603@gmail.com"
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
#1 opencv读取数据的通道次序  默许读取的色彩通道是BGR  数据通道次序是 hwc
def opencv_channel(img_path, show_mode=1):
    image = cv2.imread(img_path)
    print(f"image type: {type(image)}, image shape: {image.shape}")  # image shape: (305, 500, 3)   h w c
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)
    print(f"image type: {image.dtype}")  # image type: uint8
    print(f"min value: {np.min(image)}, max value: {np.max(image)}")  # min value: 0, max value: 255
    if show_mode == 1:
        # 假如用matplotlib显现opencv读取的图片,图片会发蓝,这是由于opencv读取的色彩通道次序是BGR,而matplotlib读取的色彩通道次序是RGB
        plt.imshow(image)
        plt.title("opencv BGR")
        plt.show()
    elif show_mode == 2:
        cv2.imshow("image", image)
        cv2.waitKey(0)
    # 运用plt正确显现opencv读取的数据,需求改变色彩通道次序  BGR2RGB
    # 下面三种办法都能够 把opencv读取的BGR色彩通道次序 更改为 RGB色彩通道次序
    # 办法一:
    cvColor_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # 办法二:
    b, g, r = cv2.split(image)
    cvColor_image2 = cv2.merge([r, g, b])
    # 办法三:
    cvColor_image3 = image[:, :, :: -1]
    if show_mode == 1:
        plt.imshow(cvColor_image)
        plt.title("BGR2RGB")
        plt.show()
    elif show_mode == 2:
        cv2.imshow("image", cvColor_image)
        cv2.waitKey(0)
#2 matplotlib读取数据的通道次序  默许读取的色彩通道是RGB  数据通道次序是 hwc
def plt_channel(img_path):
    image = plt.imread(img_path)
    print(f"image type: {type(image)}, image shape: {image.shape}")
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)   h w c
    plt.imshow(image)
    plt.title("plt image")
    plt.show()
    # 能够把numpy数据转化为pillow数据
    pil_image = Image.fromarray(image)
    plt.imshow(pil_image)
    plt.title("numpy convert to pillow type")
    plt.show()
#3 pillow读取数据的通道次序
def pillow_channel(img_path, show_mode=1):
    image = Image.open(img_path)
    print(f"image mode: {image.mode}")  # image mode: RGB
    print(f"image type: {type(image)}, image shape: {image.size}")
    # image type: <class 'PIL.JpegImagePlugin.JpegImageFile'>, image shape: (500, 305)   w, h
    if show_mode == 1:
        plt.imshow(image)
        plt.title("pillow image")
        plt.show()
    elif show_mode == 2:
        image.show()
    # 把pillow数据转化为numpy数据
    np_image = np.array(image)
    print(f"image type: {type(np_image)}, image shape: {np_image.shape}")
    # image type: <class 'numpy.ndarray'>, image shape: (305, 500, 3)   h w c
    plt.imshow(np_image)
    plt.title("pillow convert to numpy type")
    plt.show()
#4 pytorch读取数据的通道次序
def torch_channel(imgs_dir):
    # 1、数据增强
    train_data_transforms = transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
    ])
    # 2、从目录中读取数据集
    # 存放数据的目录
    root_data_dir = imgs_dir
    train_datasets = datasets.ImageFolder(root_data_dir, train_data_transforms)
    # 3、加载数据增强后的数据
    train_dataloaders = torch.utils.data.DataLoader(train_datasets,
                                                    batch_size=2,
                                                    shuffle=True,
                                                    num_workers=0)
    # 遍历读取数据
    for inputs, labels in train_dataloaders:
        print(f"inputs shape: {inputs.shape}")
        print(f"labels shape: {labels.shape}")
        '''
        # 输出成果:
        inputs shape: torch.Size([2, 3, 224, 224])  bs, c, h, w  即:NCHW, tensorflow读取的次序为NHWC
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        inputs shape: torch.Size([2, 3, 224, 224])
        labels shape: torch.Size([2])
        '''
        # 可视化其中的图片,batch_size=2, 因而每个batch中有存储两张图片的数据
        # 先把tensor类型转化为numpy类型
        np_inputs = inputs.numpy()
        print(f"np_inputs type: {type(np_inputs)}, np_inputs shape: {np_inputs.shape}")
        # np_inputs type: <class 'numpy.ndarray'>, np_inputs shape: (2, 3, 224, 224)
        # 更改图片的数据的通道次序, NCHW 改为 NHWC   0123   0231
        np_change_channel = np_inputs.transpose(0, 2, 3, 1 )
        print(f"np_change_channel type: {type(np_change_channel)}, np_change_channel shape: {np_change_channel.shape}")
        # np_change_channel type: <class 'numpy.ndarray'>, np_change_channel shape: (2, 224, 224, 3)
        # 显现图片,这里把每个batch中的两张图片放到一同显现
        out_image = np.hstack((np_change_channel[0], np_change_channel[1]))
        # # 假如用opencv显现需求再在转化一下色彩空间,转化为BGR,由于torchvision内部是基于Pillow完成的,默许是RGB色彩通道
        # out_image = cv2.cvtColor(out_image, cv2.COLOR_RGB2BGR)
        # cv2.imshow("image", out_image)
        # cv2.waitKey(0)
        plt.imshow(out_image)
        plt.title("pytorch tensor convert to numpy data")
        plt.show()
if __name__ == '__main__':
    img_path = "./bee.jpg"
    opencv_channel(img_path)
    plt_channel(img_path)
    pillow_channel(img_path)
    imgs_dir = './hymenoptera/train'
    torch_channel(imgs_dir)

参考:www.cnblogs.com/ranjiewen/p… 参考:blog.csdn.net/cxx654/arti… # 还有imagei和scipy 参考:blog.csdn.net/qq_36941368… 参考:blog.csdn.net/oLingFengYu… # 不同框架通道次序


创造不易,观众老爷们请留步… 动起心爱的小手,点个赞再走呗 (๑◕←๑)
opencv、matplotlib、pillow和pytorch读取数据的通道顺序