MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / GaussianSmoothing

Class GaussianSmoothing

diffusers/examples/community/hd_painter.py:896–952  ·  view source on GitHub ↗

Apply gaussian 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 channel

Source from the content-addressed store, hash-verified

894
895
896class GaussianSmoothing(nn.Module):
897 """
898 Apply gaussian smoothing on a
899 1d, 2d or 3d tensor. Filtering is performed seperately for each channel
900 in the input using a depthwise convolution.
901 Arguments:
902 channels (int, sequence): Number of channels of the input tensors. Output will
903 have this number of channels as well.
904 kernel_size (int, sequence): Size of the gaussian kernel.
905 sigma (float, sequence): Standard deviation of the gaussian kernel.
906 dim (int, optional): The number of dimensions of the data.
907 Default value is 2 (spatial).
908 """
909
910 def __init__(self, channels, kernel_size, sigma, dim=2):
911 super(GaussianSmoothing, self).__init__()
912 if isinstance(kernel_size, numbers.Number):
913 kernel_size = [kernel_size] * dim
914 if isinstance(sigma, numbers.Number):
915 sigma = [sigma] * dim
916
917 # The gaussian kernel is the product of the
918 # gaussian function of each dimension.
919 kernel = 1
920 meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
921 for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
922 mean = (size - 1) / 2
923 kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
924
925 # Make sure sum of values in gaussian kernel equals 1.
926 kernel = kernel / torch.sum(kernel)
927
928 # Reshape to depthwise convolutional weight
929 kernel = kernel.view(1, 1, *kernel.size())
930 kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
931
932 self.register_buffer("weight", kernel)
933 self.groups = channels
934
935 if dim == 1:
936 self.conv = F.conv1d
937 elif dim == 2:
938 self.conv = F.conv2d
939 elif dim == 3:
940 self.conv = F.conv3d
941 else:
942 raise RuntimeError("Only 1, 2 and 3 dimensions are supported. Received {}.".format(dim))
943
944 def forward(self, input):
945 """
946 Apply gaussian filter to input.
947 Arguments:
948 input (torch.Tensor): Input to apply gaussian filter on.
949 Returns:
950 filtered (torch.Tensor): Filtered output.
951 """
952 return self.conv(input, weight=self.weight.to(input.dtype), groups=self.groups, padding="same")
953

Callers 1

__call__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected