卷积层(api介绍)
![]()
案例:演示提取图像的特征图
- 第一步:plt.imread 读取图像为numpy
- 第二步: 将获取到的图像numpy转换为tensor张量 torch.tensor(img1, dtype=torch.float32)
- 第三步: 将上面的张量形状改变从hwc,转换为标准的chw torch.permute(img2, (2, 0, 1))
- 第四步:将chw转化为 Conv2d 要求的输入格式 (N, C, H, W) img3.unsqueeze(dim=0)
- 第五步:定义一个卷积层 conv = nn.Conv2d(3,4,3,1,0)
- 第六步:卷积层特征提取,得到的是nchw张量
- 第七步:拿到其中的chw
- 第八步:将chw张量转换为hwc为可视化特征图做准备 img6 = torch.permute(img5, (1,2,0))
- 最后一步:拿到的特征图张量转换为数组进行可视化(因为是nn的自动微分所以需要detach) feature2 = img6[:,:,1].detach().numpy()
![]()
测试代码
import torch import matplotlib.pyplot as plt import torch.nn as nn from pyexpat import features def dm01(): img1 = plt.imread("../data/img.jpg") img2 = torch.tensor(img1, dtype=torch.float32) print(f'img2.shape:{img2.shape}') # 将640,640,3 转换为3,640,640 img3 = torch.permute(img2, (2, 0, 1)) print(f'img3.shape:{img3.shape}') # 将 3,640,640 变为 1,3,640,640 img4 = img3.unsqueeze(dim=0) print(f'img4.shape:{img4.shape}') # 定义一个卷积层 # Conv2d 要求的输入格式 (N, C, H, W) # 参1: 输入通道数, 参2: 输出通道数(也就是有几个卷积核),参3:卷积核大小。参4:步长, 参5:填充0(不填充) conv = nn.Conv2d(3,4,3,1,0) # 提取特征后为 1,4,638,638 conv_img = conv(img4) print(f'img5.shape:{conv_img.shape}') # 取出其中4,638,638 (c,h,w) img5 = conv_img[0] print(f'img5.shape:{img5.shape}') # 转化为 638,638,4(h,w,c)才能可视化 img6 = torch.permute(img5, (1,2,0)) print(f'img6.shape:{img6.shape}') # 展示四个卷积核,提取到的不同的4个特征图 # 最后一步再将张量转换为数组用于可视化(又因为nn,自动微分了所以需要detach) feature1 = img6[:,:,0].detach().numpy() plt.imshow(feature1) plt.show() feature2 = img6[:,:,1].detach().numpy() plt.imshow(feature2) plt.show() feature3 = img6[:, :, 2].detach().numpy() plt.imshow(feature3) plt.show() feature4 = img6[:, :, 3].detach().numpy() plt.imshow(feature4) plt.show() pass if __name__ == '__main__': dm01()
测试结果
D:\pythonDemo\.venv\Scripts\python.exe -X pycache_prefix=C:\Users\Administrator.SY-202408261506\AppData\Local\JetBrains\PyCharm2025.3\cpython-cache "D:/Software/PyCharm 2025.3/plugins/python-ce/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 57683 --file D:\pythonDemo\demo\test30_cnn.py Connected to: <socket.socket fd=816, family=2, type=1, proto=0, laddr=('127.0.0.1', 57684), raddr=('127.0.0.1', 57683)>. Connected to pydev debugger (build 253.28294.336) img2.shape:torch.Size([640, 640, 3]) img3.shape:torch.Size([3, 640, 640]) img4.shape:torch.Size([1, 3, 640, 640]) img5.shape:torch.Size([1, 4, 638, 638]) img5.shape:torch.Size([4, 638, 638]) img6.shape:torch.Size([638, 638, 4]) Process finished with exit code 0
![]()
总结
![]()