镜像padding一张图片,利用pytorch.nn.functional.pad()

import torch as t
import torch.nn as nn

def ReflectPad2D(image, pad_size):
    '''
    镜像padding
    :param image: 图像
    :param pad_size: padding大小,我这里简化成正方形图,四个方向全padding同样的值

    :return: padding后的图像
    '''
    original_shape = image.shape
    image = image.reshape([1]+list(original_shape)) # reshape成4D

    ''' 利用torch.nn.functional.pad() 进行padding,由于该函数其只能padding 4D图的后两维,3D的最后一维 ,所以这里进行了两次reshape'''
    image = t.tensor(image)
    p1d = (pad_size, pad_size, pad_size, pad_size) # pad last dim by (1, 1) and 2nd to last by (2, 2)
    pad_image = nn.functional.pad(image, p1d, mode='reflect')
    pad_image = pad_image.reshape(original_shape[0], original_shape[1]+2*pad_size, original_shape[2]+2*pad_size) # reshape 回3D

    return pad_image

 

我的代码如下:import torch.nn.functional as F import torch.nn as nn import torch import numpy as np import os import torchvision.transforms.functional as TF from PIL import Image from torchvision.transforms import ToPILImage import cv2 import datetime import matplotlib.pyplot as plt class EnhancedSpatialAttention(nn.Module): def __init__(self, kernel_size=7): super().__init__() padding = kernel_size // 2 # 多尺度特征融合 self.conv1 = nn.Conv2d(2, 32, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(32, 1, kernel_size, padding=padding) self.bn = nn.BatchNorm2d(32) def forward(self, x): avg_out = torch.mean(x, dim=1, keepdim=True) max_out = torch.max(x, dim=1, keepdim=True)[0] x = torch.cat([avg_out, max_out], dim=1) x = F.relu(self.bn(self.conv1(x))) # 加入非线性 x = self.conv2(x) return torch.sigmoid(x) class EdgeAttention(nn.Module): def __init__(self, channels, reduction=16): super().__init__() # 高效通道注意力 (ECA-Net风格) self.channel_att = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels//reduction, 1), nn.ReLU(), nn.Conv2d(channels//reduction, channels, 1), nn.Sigmoid() ) self.spatial_att = EnhancedSpatialAttention() # 残差连接 self.conv = nn.Conv2d(channels, channels, 3, padding=1) def forward(self, x): # 通道注意力 ca = self.channel_att(x) x_ca = x * ca # 空间注意力 sa = self.spatial_att(x_ca) x_sa = x_ca * sa # 残差连接 return self.conv(x_sa) + x class ReflectedConvolution(nn.Module): def __init__(self, kernel_nums = 8, kernel_size = 3): #设计8个卷积核,用于学习光照不变特征 #设置3*3卷积 #分别对三个特征进行归一化 super(ReflectedConvolution, self).__init__() self.kernel_nums = kernel_nums self.kernel_size = kernel_size
03-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值