Created
July 28, 2016 20:30
-
-
Save casperkaae/a4bc4bb30009a4fbbccfe588209f6d24 to your computer and use it in GitHub Desktop.
mirror padding for theano
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mirror_padding(images, filter_size): | |
""" | |
Mirror padding is used to apply a 2D convolution avoiding the border | |
effects that one normally gets with zero padding. | |
We assume that the filter has an odd size. | |
To obtain a filtered tensor with the same output size, substitute | |
a ``conv2d(images, filters, mode="half")`` with | |
``conv2d(mirror_padding(images, filters.shape), filters, mode="valid")``. | |
Parameters | |
---------- | |
images : Tensor | |
4D tensor containing a set of images. | |
filter_size : tuple | |
Spatial size of the filter (height, width). | |
Returns | |
------- | |
padded : Tensor | |
4D tensor containing the padded set of images. | |
""" | |
if (filter_size[0] % 2) == 0 or (filter_size[1] % 2) == 0: | |
raise ValueError('Filter size must be odd in both dimensions.') | |
h_pad = filter_size[0] // 2 | |
w_pad = filter_size[1] // 2 | |
# Allocate space for padded images. | |
s = images.shape | |
padded_shape = (s[0], s[1], s[2] + 2*h_pad, s[3] + 2*w_pad) | |
x_padded = zeros(padded_shape) | |
# Copy the original image to the central part. | |
x_padded = set_subtensor( | |
x_padded[:, :, h_pad:s[2]+h_pad, w_pad:w_pad+s[3]], | |
images, | |
) | |
# Copy borders. | |
# Note that we don't mirror starting at pixel number 0: assuming that | |
# we have a symmetric, odd filter, the central element of the filter | |
# will run along the original border, and we need to match the | |
# statistics of the elements around it. | |
x_padded = set_subtensor( | |
x_padded[:, :, :h_pad, w_pad:-w_pad], | |
images[:, :, h_pad:0:-1, :], | |
) | |
x_padded = set_subtensor( | |
x_padded[:, :, -h_pad:, w_pad:-w_pad], | |
images[:, :, -2:-h_pad-2:-1, :], | |
) | |
x_padded = set_subtensor( | |
x_padded[:, :, :, :w_pad], | |
x_padded[:, :, :, 2*w_pad:w_pad:-1], | |
) | |
x_padded = T.set_subtensor( | |
x_padded[:, :, :, -w_pad:], | |
x_padded[:, :, :, -w_pad-2:-2*w_pad-2:-1], | |
) | |
return x_padded |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment