以pytorch为例子,2D卷积在设置的时候具有以下参数,具有输入通道的多少(这个决定了卷积核的通道数量),滤波器数量,这个是有多少个滤波器,越多提取的特征就越有用,kernel_size,这个是卷积核的大小,相当于一个观测器的大小,越大参数越大其实是越强。
- import torch
- import torch.nn as nn
-
- # 创建一个输入张量,假设是一张3通道的4x4图像
- # 输入通道数为3
- input_tensor = torch.randn(1, 3, 4, 4) # (batch_size, in_channels, height, width)
-
- # 创建卷积层
- # 输入通道数为3,输出通道数为16,卷积核大小为3x3,步幅为1,无填充
- conv_layer = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=0)
-
- # 执行卷积操作
- output_tensor = conv_layer(input_tensor)
-
- # 查看输出张量的形状
- print("输出张量的形状:", output_tensor.shape)
Param # = (input_channels * output_channels * kernel_height * kernel_width) + output_channels
- import cv2
- import numpy as np
- import torch
- import torch.nn as nn
- import matplotlib.pyplot as plt
-
- # 创建一个随机的灰度图像
- gray_image = np.random.rand(64, 64) * 255 # 生成0到255之间的随机灰度值
- gray_image=cv2.imread("7.jpg",0)
-
-
- # 将灰度图像复制到RGB通道,创建彩色图像
- color_image = cv2.cvtColor(gray_image.astype(np.uint8), cv2.COLOR_GRAY2RGB)
-
- # 定义一个锐化卷积核
- # kernel = np.array([[-1, -1, -1],
- # [-1, 9, -1],
- # [-1, -1, -1]])/2 # 平均滤波器
-
- kernel = np.array([[ 0 , 1 , 0],
- [ 1 ,-4 , 1],
- [ 0 , 1 , 0]])*128 # 平均滤波器
-
-
- kernel = np.array([[ 1 , 1 , 1],
- [ 1 ,1 , 1],
- [ 1 , 1 , 1]])/9 # 平均滤波器
-
- # 进行基本卷积操作、OpenCV卷积操作和锐化卷积操作
- basic_result = cv2.filter2D(gray_image, -1, kernel)
- opencv_conv_result = cv2.filter2D(gray_image, -1, kernel)
- sharpened_image = cv2.filter2D(gray_image, -1, kernel)
-
- # 将灰度图像转换为PyTorch张量
- gray_image_tensor = torch.from_numpy(gray_image).unsqueeze(0).unsqueeze(0).float() / 255.0
-
- # 创建一个卷积层,使用相同的卷积核
- conv2d_layer = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=1, bias=False)
- conv2d_layer.weight.data = torch.from_numpy(kernel).unsqueeze(0).unsqueeze(0).float()
-
- # 进行PyTorch的Conv2d卷积操作
- pytorch_conv_result = conv2d_layer(gray_image_tensor).squeeze().detach().numpy()
-
-
- # 显示原始灰度图像、基本卷积结果、OpenCV卷积结果、锐化卷积结果和PyTorch卷积结果
- plt.figure(figsize=(25, 5))
- plt.subplot(1, 5, 1)
- plt.title("Original Gray Image")
- plt.imshow(gray_image, cmap='gray', vmin=0, vmax=255)
-
- plt.subplot(1, 5, 2)
- plt.title("Basic Convolution")
- plt.imshow(basic_result, cmap='gray', vmin=0, vmax=255)
-
- plt.subplot(1, 5, 3)
- plt.title("OpenCV Convolution")
- plt.imshow(opencv_conv_result, cmap='gray', vmin=0, vmax=255)
-
- # plt.subplot(1, 5, 4)
- # plt.title("Sharpened Gray Image")
- # plt.imshow(sharpened_image, cmap='gray', vmin=0, vmax=255)
-
- plt.subplot(1, 5, 4)
- plt.title("PyTorch Convolution")
- plt.imshow(pytorch_conv_result, cmap='gray', vmin=0, vmax=1)
-
- plt.show()
均值滤波结果如下
采用边缘检测算法结果如下
从结果来看卷积似乎有些区别但是功能一致具体问题处在哪,以后再尝试