Image Processing Toolbox | ![]() ![]() |
Padding of Borders
When you apply a filter to pixels on the borders of an image, some of the elements of the computational molecule may not overlap actual image pixels. For example, if the molecule is 3-by-3 and you are computing the result for a pixel on the top row of the image, some of the elements of the molecule are outside the border of the image.
Figure 6-2 illustrates a 3-by-3 computational molecule being applied to the pixel (1,3) of a 5-by-5 matrix. The center pixel is indicated by a filled circle.
Figure 6-2: Computational Molecule Overhanging Top Row of Image
In order to compute output values for the border pixels, conv2
pads the image matrix with zeroes. In other words, the output values are computed by assuming that the input image is surrounded by additional rows and columns of zeroes. In the figure shown above, the elements in the top row of the computational molecule are assumed to overlap zeroes.
Depending on what you are trying to accomplish, you may want to discard output pixels whose values depend on zero padding. To indicate what portion of the convolution to return, conv2
takes a third input argument, called the shape parameter, whose value is one of these three strings.
'valid'
- returns only the pixels whose values can be computed without using zero padding of the input image. The resulting output image is smaller than the input image. In this example, the output image is 3-by-3.'same'
- returns the set of pixels that can be computed by applying the filter to all pixels that are actually part of the input image. Border pixels are computed using zero padding, but the center pixel of the computational kernel is applied only to pixels in the image. This results in an output image that is the same size as the input image.'full'
- returns the full convolution. This means conv2
returns all pixels for which any of the pixels in the computational molecule overlap pixels in the image, even when the center pixel is outside the input image. The resulting output image is larger than the input image. In this example, the output image is 7-by-7.conv2
returns the full convolution by default.
Figure 6-3 below illustrates applying a computational molecule to three different places in an image matrix.
Figure 6-3: Computation Molecule Applied to Different Areas at Edge
If you use the full
option, then the order of the first two input arguments is interchangeable, because full convolution is commutative. In other words, it does not matter which matrix is considered the convolution kernel, because the result is the same in either case. If you use the valid
or same
option, the operation is not commutative, so the convolution kernel must be the second argument.
![]() | Convolution | The filter2 Function | ![]() |