Main Content

imfilter Boundary Padding Options

When computing an output pixel at the boundary of an image, a portion of the convolution or correlation kernel is usually off the edge of the image, as illustrated in the following figure.

When the Values of the Kernel Fall Outside the Image

A grid of pixels displaying the pixel values. The 3-by-3 kernel centered on the (1, 4) pixel is highlighted in gray and extends past the edge of the image, where there are no pixels.

The imfilter function normally fills in these off-the-edge image pixels by assuming that they are 0. This is called zero padding and is illustrated in the following figure.

Zero Padding of Outside Pixels

A grid of pixels displaying the pixel values. Pixels are simulated where the 3-by-3 kernel extends past the edge of the image. The value of the simulated pixels is 0.

When you filter an image, zero padding can result in a dark band around the edge of the image, as shown in this example.

I = imread("eight.tif");
h = ones(5,5) / 25;
I2 = imfilter(I,h);
imshow(I)
title("Original Image");
figure
imshow(I2)
title("Filtered Image with Black Border")

On the left is the original image and on the right is the filtered image with dark pixels along the edge of the image.

To eliminate the zero-padding artifacts around the edge of the image, imfilter offers an alternative boundary padding method called border replication. In border replication, the value of any pixel outside the image is determined by replicating the value from the nearest border pixel. This is illustrated in the following figure.

Replicated Boundary Pixels

A grid of pixels displaying the pixel values. Pixels are simulated where the 3-by-3 kernel extends past the edge of the image. The value of each simulated pixel is equal to the value of the edge pixel adjacent to the simulated pixel.

To filter using border replication, pass the additional optional argument "replicate" to imfilter.

I3 = imfilter(I,h,"replicate");
figure
imshow(I3); 
title("Filtered Image with Border Replication")

The filtered image with border replication does not have dark pixels along the edge of the image.

The imfilter function supports other boundary padding options, such as "circular" and "symmetric".

See Also

Related Topics