![]() |
VOOZH | about |
Adding a border around a NumPy array means surrounding the original array with extra rows and columns. NumPy provides the numpy.pad() function, which allows adding borders of any width and value. This is commonly done when preparing matrices for image processing, padding operations, or structural modifications.
Example: This example shows how a border is added around a 2×2 array. A padding width of 1 and a border value of 0 are used to surround the original matrix.
[[0. 0. 0. 0.] [0. 1. 1. 0.] [0. 1. 1. 0.] [0. 0. 0. 0.]]
Explanation:
numpy.pad(array, pad_width, mode='constant', constant_values=value)
Parameters:
Example 1: This example adds a border of -1 around a 4×1 column vector.
[[-1 -1 -1] [-1 10 -1] [-1 20 -1] [-1 30 -1] [-1 40 -1] [-1 -1 -1]]
Explanation:
Example 2: This example pads a rectangular (3×5) array by adding a border of -1 on all sides.
[[-1. -1. -1. -1. -1. -1. -1.] [-1. 1. 1. 1. 1. 1. -1.] [-1. 1. 1. 1. 1. 1. -1.] [-1. 1. 1. 1. 1. 1. -1.] [-1. -1. -1. -1. -1. -1. -1.]]
Explanation
Example 3: This example pads only the top and bottom of an array by using different padding widths for each side.
[[9 9 9] [0 1 2] [3 4 5] [9 9 9]]
Explanation: