medianfilt.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """This is code for median pooling from https://gist.github.com/rwightman.
  2. https://gist.github.com/rwightman/f2d3849281624be7c0f11c85c87c1598
  3. """
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from torch.nn.modules.utils import _pair, _quadruple
  7. class MedianPool2d(nn.Module):
  8. """Median pool (usable as median filter when stride=1) module.
  9. Args:
  10. kernel_size: size of pooling kernel, int or 2-tuple
  11. stride: pool stride, int or 2-tuple
  12. padding: pool padding, int or 4-tuple (l, r, t, b) as in pytorch F.pad
  13. same: override padding and enforce same padding, boolean
  14. """
  15. def __init__(self, kernel_size=3, stride=1, padding=0, same=True):
  16. """Initialize with kernel_size, stride, padding."""
  17. super().__init__()
  18. self.k = _pair(kernel_size)
  19. self.stride = _pair(stride)
  20. self.padding = _quadruple(padding) # convert to l, r, t, b
  21. self.same = same
  22. def _padding(self, x):
  23. if self.same:
  24. ih, iw = x.size()[2:]
  25. if ih % self.stride[0] == 0:
  26. ph = max(self.k[0] - self.stride[0], 0)
  27. else:
  28. ph = max(self.k[0] - (ih % self.stride[0]), 0)
  29. if iw % self.stride[1] == 0:
  30. pw = max(self.k[1] - self.stride[1], 0)
  31. else:
  32. pw = max(self.k[1] - (iw % self.stride[1]), 0)
  33. pl = pw // 2
  34. pr = pw - pl
  35. pt = ph // 2
  36. pb = ph - pt
  37. padding = (pl, pr, pt, pb)
  38. else:
  39. padding = self.padding
  40. return padding
  41. def forward(self, x):
  42. # using existing pytorch functions and tensor ops so that we get autograd,
  43. # would likely be more efficient to implement from scratch at C/Cuda level
  44. x = F.pad(x, self._padding(x), mode='reflect')
  45. x = x.unfold(2, self.k[0], self.stride[0]).unfold(3, self.k[1], self.stride[1])
  46. x = x.contiguous().view(x.size()[:4] + (-1,)).median(dim=-1)[0]
  47. return x