0% found this document useful (0 votes)
26 views1 page

Zero Padding Images in Python

This document defines a function called zero_pad that pads all images in a dataset X with zeros. The padding is applied to the height and width of each image. The function takes in the dataset X and an integer pad amount, and returns a padded version of X with shape (m, n_H + 2*pad, n_W + 2*pad, n_C) where m is the number of images, n_H is the original height, n_W is the original width, and n_C is the number of channels. It pads X with zeros using NumPy's pad function.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views1 page

Zero Padding Images in Python

This document defines a function called zero_pad that pads all images in a dataset X with zeros. The padding is applied to the height and width of each image. The function takes in the dataset X and an integer pad amount, and returns a padded version of X with shape (m, n_H + 2*pad, n_W + 2*pad, n_C) where m is the number of images, n_H is the original height, n_W is the original width, and n_C is the number of channels. It pads X with zeros using NumPy's pad function.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

# GRADED FUNCTION: zero_pad

def zero_pad(X, pad):


"""
Pad with zeros all images of the dataset X. The padding is applied to the
height and width of an image,
as illustrated in Figure 1.

Argument:
X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch
of m images
pad -- integer, amount of padding around each image on vertical and
horizontal dimensions

Returns:
X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)
"""

### START CODE HERE ### (≈ 1 line)


X_pad = [Link](X,((0,0),(pad,pad),(pad,pad),
(0,0)),'constant',constant_values = 0)
### END CODE HERE ###

return X_pad
In [3]:
[Link](1)
x = [Link](4, 3, 3, 2)
x_pad = zero_pad(x, 2)
print ("[Link] =", [Link])
print ("x_pad.shape =", x_pad.shape)
print ("x[1,1] =", x[1,1])
print ("x_pad[1,1] =", x_pad[1,1])

fig, axarr = [Link](1, 2)


axarr[0].set_title('x')
axarr[0].imshow(x[0,:,:,0])
axarr[1].set_title('x_pad')
axarr[1].imshow(x_pad[0,:,:,0])

You might also like