• 画图、图片处理


    画图

    问题代码

    def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5): #@save
    """绘制图像列表"""
    figsize = (num_cols * scale, num_rows * scale)
    _, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
    axes = axes.flatten()
    for i, (ax, img) in enumerate(zip(axes, imgs)):
    if torch.is_tensor(img):
    # 图片张量
    ax.imshow(img.numpy())
    else:
    # PIL图片
    ax.imshow(img)
    ax.axes.get_xaxis().set_visible(False)
    ax.axes.get_yaxis().set_visible(False)
    if titles:
    ax.set_title(titles[i])
    return axes
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    d2l.plt.subplots返回值

    plt.subplots是matplotlib库中的一个函数,用于创建一个新的Figure对象,并在其中创建一个或多个子图(subplot)。
    它的基本用法是:

    fig, ax = plt.subplots(nrows=1, ncols=1, **kwargs)
    其中,nrowsncols分别指定了子图的行数和列数。如果只想创建一个子图,可以省略其中一个参数。

    返回值fig是Figure对象ax则是一个或多个子图的Axes对象(如果只创建了一个子图,则返回一个单独的Axes对象;如果创建了多个子图,则返回一个Axes对象列表)。

    kwargs是可选的关键字参数,用于设置Figure和子图的属性。例如,可以使用figsize参数设置Figure的大小,使用sharexsharey参数来共享子图的x轴和y轴。

    axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)

    解释:

    d2l.plt.subplots创建了一个包含多个子图的网格(grid);

    num_rows和num_cols分别指定了网格中子图的行数和列数;
    figsize指定了整个图像的尺寸,即包含所有子图的画布大小。
    返回值axes是一个由网格的子图对象组成的NumPy数组。
    我们可以使用它来访问、控制和绘制每个子图。

    举例说明:

    axes是一个由子图对象组成的NumPy数组,它可以用来访问、控制和绘制每个子图。具体来说,axes是一个大小为(num_rows, num_cols)的NumPy数组,其中axes[i, j]表示第 i + 1 i+1 i+1行和第 j + 1 j+1 j+1列的子图对象。

    例如,如果我们使用以下代码创建一个包含 2 2 2 3 3 3列子图的网格:

    
    import matplotlib.pyplot as plt
    
    import d2l
    
    
    
    figsize = (6, 4)
    
    num_rows, num_cols = 2, 3
    
    axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
    
    那么`axes`将是一个大小为$(2, 3)$的NumPy数组,可以通过索引来访问每个子图对象。例如,我们可以在第$1$行第$2$列的子图中绘制一条直线:
    
    axes[0, 1].plot([0, 1], [0, 1])
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    或者我们可以在所有子图中添加一个标题:

    
    for i in range(num_rows):
    
    for j in range(num_cols):
    
    axes[i, j].set_title(f'Subplot ({i+1}, {j+1})')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    原链接

    subplot()、subplots()

    subplot()、subplots()在实际过程中,先创建了一个figure画窗,然后通过调用add_subplot()来向画窗中各个分块添加坐标区,其差别在于是分次添加(subplot())还是一次性添加(subplots())

    在这里插入图片描述
    3.plt.subplots()
    语法格式:

    matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False,
    sharey=False, squeeze=True,subplot_kw=None, gridspec_kw=None, **fig_kw)
    -nrows:默认为 1,设置图表的行数。
    -ncols:默认为 1,设置图表的列数。
    -sharex、sharey:设置 x、y 轴是否共享属性,默认为 false,可设置为 ‘none’、‘all’、‘row’ 或 ‘col’。 False 或 none 每个子图的 x 轴或 y 轴都是独立的,True 或 ‘all’:所有子图共享 x 轴或 y 轴,‘row’ 设置每个子图行共享一个 x 轴或 y 轴,‘col’:设置每个子图列共享一个 x 轴或 y 轴。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # 创建一些测试数据 
    x = np.linspace(0,100, 4)
    y = np.sin(x**2)
    
    # 创建一个画像和子图 -- 图1
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set_title('Simple plot')
    
    # 创建两个子图 -- 图2
    #如图figure2,四个子图中上两幅图并无x轴(与下子图共享),因为已设置sharex=True
    #若改为sharey=True,可观察到四副子图中右两幅无y轴(即与左子图共享)
    f, ([ax1, ax2],[ax3,ax4]) = plt.subplots(2, 2, sharex=True)
    ax1.plot(x, y)
    ax1.set_title('Sharing x axis')
    ax2.scatter(x, y)
    ax3.scatter(x, y)
    ax4.scatter(x, y)
    
    # 创建四个子图 -- 图3
    #通过对subplot_kw传入参数,生成关于极坐标系的子图
    fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
    axs[0, 0].plot(x, y)
    axs[1, 1].scatter(x, y)
    
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    在这里插入图片描述

    文章来源地址

    python内置函数:zip()函数搭配enumerate函数使用,用在for循环中

    简介enumerate()

    enumerate()函数是Python的内置函数,对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),可以利用enumerate函数同时获取对象的索引和值。

    x=np.arange(0,100,10)
    for i in enumerate(x):
        index = i[0]; xval = i[1]
        print(index,xval)
    
    • 1
    • 2
    • 3
    • 4
    0 0
    1 10
    2 20
    3 30
    4 40
    5 50
    6 60
    7 70
    8 80
    9 90
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    简介zip()

    zip函数是Python的内置函数,它用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象(即对多个序列进行并行迭代)。如果各个迭代器元素个数不一致,zip()函数则在最短序列“用完”时就会停止。

    sz = np.arange(1,100,10)
    sx = np.arange(1,10,1)
    for index, (szi, sxi) in enumerate(zip(sz, sx)):
        print(index,szi,sxi)
    
    • 1
    • 2
    • 3
    • 4
    0 1 1
    1 11 2
    2 21 3
    3 31 4
    4 41 5
    5 51 6
    6 61 7
    7 71 8
    8 81 9
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    transforms.Compose(trans)

    Compose()类会将transforms列表里面的transform操作进行遍历。实现的代码很简单:

    ## 这里对源码进行了部分截取。
    def __call__(self, img):
    	for t in self.transforms:	
    		img = t(img)
        return img
    
    • 1
    • 2
    • 3
    • 4
    • 5

    pytorch通过深度学习进行预处理图片,离不开transforms.Compose(),torchvision.datasets.ImageFolder(),torch.utils.data.DataLoader()的用法。

    源自于文章

    1.Transform.Compose()详解

    导入相应的库

    
    import torch
    import torchvision
    import matplotlib.pyplot as plt
    from torch.utils import data
    from torchvision import datasets,transforms
    from PIL import Image
    %matplotlib inline
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    class torchvision.transforms.Compose(transforms):
     # Composes several transforms together.
     # Parameters: transforms (list of Transform objects) – list of transforms to compose.
     
    Example # 可以看出Compose里面的参数实际上就是个列表,而这个列表里面的元素就是你想要执行的transform操作。
    >>> transforms.Compose([
    >>>     transforms.CenterCrop(10),
    >>>     transforms.ToTensor(),])
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    展示原始图片

    pic = "./train/Chihuahua/n02085620_10074.jpg"
    
    img = plt.imread(pic)
    plt.imshow(img)
    
    • 1
    • 2
    • 3
    • 4

    定义图片预处理的对象。

    traintransform = transforms.Compose([transforms.RandomRotation(20),           # 随机旋转20°
                                         transforms.ColorJitter(brightness=0.1), #随机改变图像的亮度对比度和饱和度
                                         transforms.Resize([150,150]),          # 转换为需要的尺寸
                                         transforms.ToTensor(),                #convert a PIL image to tensor (H*W*C)
                                        ])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    img1 = Image.fromarray(img)   #将numpy对象的img转换为PIL格式
    img2 = traintransform(img1)# 图像预处理tensor
    img3 = transforms.ToPILImage()(img2)#转换为PIL进行展示
    plt.imshow(img3)
    
    • 1
    • 2
    • 3
    • 4

    展示处理之后的图片,可以看出,图片旋转了20°,并且大小转换为(150,150)

    附上——transforms中的函数如何使用?

    # Resize:把给定的图片resize到given size
    # Normalize:Normalized an tensor image with mean and standard deviation
    # ToTensor:convert a PIL image to tensor (H*W*C) in range [0,255] to a torch.Tensor(C*H*W) in the range [0.0,1.0]
    # ToPILImage: convert a tensor to PIL image
    # Scale:目前已经不用了,推荐用Resize
    # CenterCrop:在图片的中间区域进行裁剪
    # RandomCrop:在一个随机的位置进行裁剪
    # RandomHorizontalFlip:以0.5的概率水平翻转给定的PIL图像
    # RandomVerticalFlip:以0.5的概率竖直翻转给定的PIL图像
    # RandomResizedCrop:将PIL图像裁剪成任意大小和纵横比
    # Grayscale:将图像转换为灰度图像
    # RandomGrayscale:将图像以一定的概率转换为灰度图像
    # FiceCrop:把图像裁剪为四个角和一个中心
    # TenCrop
    # Pad:填充
    # ColorJitter:随机改变图像的亮度对比度和饱和度。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    fastlio2 论文笔记
    硬件学习 PAD9.5 day01 原理图布局开始设置, 元器件的调用和绘制, 新建库, 库添加元器件,
    小白C语言编程实战(16):统计4门课的优秀率和不及格率
    【云原生之K8s】Kubeadm搭建K8s
    PID控制原理
    JAVA毕业设计古玩玉器交易系统计算机源码+lw文档+系统+调试部署+数据库
    计算机毕业设计之java+SSM酒店客房预定管理系统
    优维低代码实践:片段
    一键复制 — vue
    [《考驾照》闲笔记事集]2012年8月28日
  • 原文地址:https://blog.csdn.net/qq_51070956/article/details/134289144