MCPcopy Create free account
hub / github.com/Monalissaa/DisenDiff / AverageSmoothing

Class AverageSmoothing

src/gaussian_smoothing.py:74–119  ·  view source on GitHub ↗

Apply average smoothing on a 1d, 2d or 3d tensor. Filtering is performed seperately for each channel in the input using a depthwise convolution. Arguments: channels (int, sequence): Number of channels of the input tensors. Output will have this number of channels

Source from the content-addressed store, hash-verified

72
73
74class AverageSmoothing(nn.Module):
75 """
76 Apply average smoothing on a
77 1d, 2d or 3d tensor. Filtering is performed seperately for each channel
78 in the input using a depthwise convolution.
79 Arguments:
80 channels (int, sequence): Number of channels of the input tensors. Output will
81 have this number of channels as well.
82 kernel_size (int, sequence): Size of the average kernel.
83 sigma (float, sequence): Standard deviation of the rage kernel.
84 dim (int, optional): The number of dimensions of the data.
85 Default value is 2 (spatial).
86 """
87 def __init__(self, channels, kernel_size, dim=2):
88 super(AverageSmoothing, self).__init__()
89
90 # Make sure sum of values in gaussian kernel equals 1.
91 kernel = torch.ones(size=(kernel_size, kernel_size)) / (kernel_size * kernel_size)
92
93 # Reshape to depthwise convolutional weight
94 kernel = kernel.view(1, 1, *kernel.size())
95 kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
96
97 self.register_buffer('weight', kernel)
98 self.groups = channels
99
100 if dim == 1:
101 self.conv = F.conv1d
102 elif dim == 2:
103 self.conv = F.conv2d
104 elif dim == 3:
105 self.conv = F.conv3d
106 else:
107 raise RuntimeError(
108 'Only 1, 2 and 3 dimensions are supported. Received {}.'.format(dim)
109 )
110
111 def forward(self, input):
112 """
113 Apply average filter to input.
114 Arguments:
115 input (torch.Tensor): Input to apply average filter on.
116 Returns:
117 filtered (torch.Tensor): Filtered output.
118 """
119 return self.conv(input, weight=self.weight, groups=self.groups)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected