Sub topic 3
What happens at the image border
Why the border needs a rule
A kernel of size k×k is centered on each pixel and multiplies the neighborhood around it. For a pixel in the first row, part of that neighborhood lies outside the image. Those missing values do not exist, so OpenCV has to invent them.
This chapter assumes you know what cv2.filter2D does with a kernel. The border rule you pick decides what the invented values are. For a kernel of size k, the border extends k // 2 pixels on each side. A 5×5 kernel needs 2 extra pixels on every side, and a 3×3 kernel needs 1.
OpenCV filters return an image of the same size as the input. It does this by padding the image virtually, running the kernel over the padded copy, and keeping only the central region. The padding rule is the borderType argument.
The border modes
Suppose a row of pixels is 1 2 3 4 5 and the kernel needs two extra pixels on each side. The table shows what each mode puts there. The | marks the true image edge.
| Mode | Padded row | Rule | Column | Column |
|---|---|---|---|---|
| `cv2.BORDER_CONSTANT` | `0 0 \ | 1 2 3 4 5 \ | 0 0` | Fill with a fixed value, 0 by default |
| `cv2.BORDER_REPLICATE` | `1 1 \ | 1 2 3 4 5 \ | 5 5` | Repeat the outermost pixel |
| `cv2.BORDER_REFLECT` | `2 1 \ | 1 2 3 4 5 \ | 5 4` | Mirror, repeating the edge pixel |
| `cv2.BORDER_REFLECT_101` | `3 2 \ | 1 2 3 4 5 \ | 4 3` | Mirror without repeating the edge pixel |
| `cv2.BORDER_WRAP` | `4 5 \ | 1 2 3 4 5 \ | 1 2` | Wrap around to the opposite side |
BORDER_REFLECT_101 is also available as cv2.BORDER_DEFAULT. Most OpenCV filters use it when you do not pass borderType.
You can check the table yourself with cv2.copyMakeBorder. It applies the same padding rules that the filters use internally.
import cv2
import numpy as np
row = np.array([[1, 2, 3, 4, 5]], dtype=np.uint8)
modes = {
"CONSTANT": cv2.BORDER_CONSTANT,
"REPLICATE": cv2.BORDER_REPLICATE,
"REFLECT": cv2.BORDER_REFLECT,
"REFLECT_101": cv2.BORDER_REFLECT_101,
"WRAP": cv2.BORDER_WRAP,
}
for name, mode in modes.items():
# top, bottom, left, right: pad 2 pixels on the left and right only
padded = cv2.copyMakeBorder(row, 0, 0, 2, 2, mode, value=0)
print(f"{name:12s}", padded[0])The output rows match the table. For example, REFLECT_101 prints [3 2 1 2 3 4 5 4 3].
Why the default is REFLECT_101
Reflection keeps the local statistics of the image near the edge. If the pixels near the border are smooth, the mirrored pixels are smooth too. Both kinds of reflection produce padding that looks like a plausible continuation of the image.
REFLECT_101 avoids duplicating the edge pixel. Duplicating it gives that pixel twice the weight in the neighborhood, and that can slightly bias the result.
BORDER_REPLICATE is a good choice when the image content near the edge is flat, such as a uniform background. BORDER_WRAP makes sense only when the image is periodic, such as a tiling texture or an unrolled panorama. For ordinary photos it mixes unrelated content from opposite sides.
The cost of constant borders
BORDER_CONSTANT is easy to understand but often produces visible artifacts. It treats the outside world as black, so any averaging near the edge pulls values toward zero.
The example below blurs a uniformly bright image. A correct blur should leave a uniform image unchanged.
import cv2
import numpy as np
img = np.full((7, 7), 200, dtype=np.uint8)
default = cv2.blur(img, (5, 5)) # REFLECT_101
const = cv2.blur(img, (5, 5), borderType=cv2.BORDER_CONSTANT)
print("default row 0:", default[0])
print("constant row 0:", const[0])
print("constant corner:", const[0, 0], "edge middle:", const[0, 3], "center:", const[3, 3])With the default border, every pixel stays at 200. With a constant border, the corner pixel has only 9 of its 25 neighbors inside the image, so it becomes about 200 × 9/25 = 72. A pixel in the middle of the top row has 15 of 25, so it becomes 120. The center pixel stays at 200. The result is a dark frame around the image.
Borders and gradients
The border rule matters even more for derivative filters such as Sobel. A derivative responds to change, and a constant border creates a change that is not in the image.
import cv2
import numpy as np
img = np.full((9, 9), 200, dtype=np.uint8)
for name, mode in [("REFLECT_101", cv2.BORDER_REFLECT_101),
("CONSTANT", cv2.BORDER_CONSTANT)]:
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3, borderType=mode)
print(name, "max |gy| =", np.abs(gy).max())
print(" row 0:", gy[0, 3], " row 4:", gy[4, 3])The image is perfectly flat, so it has no edges. With REFLECT_101 the vertical gradient is 0 everywhere. With BORDER_CONSTANT the pixels in the first and last rows get a gradient of magnitude 800. That is the 3×3 Sobel weight total of 4 times the jump of 200 between the image and the zero padding. Those false responses would show up in a gradient magnitude image as a bright frame, and they could create false edges in Canny.
Reflection gives zero here because the mirrored rows are identical to the real rows, so the difference between the rows above and below cancels.
Which functions accept a border mode
Not every function exposes the setting, and the ones that do use different defaults and keyword names. The common cases:
cv2.filter2D(src, ddepth, kernel, borderType=...)takes a border mode. The default isBORDER_DEFAULT.cv2.blur,cv2.boxFilter,cv2.GaussianBlur,cv2.bilateralFilterandcv2.SobelacceptborderTypeas a keyword argument.cv2.medianBlurhas no border parameter. It pads by replicating the edge pixels internally.cv2.Cannyhas no border parameter. It handles the border internally, so you cannot change it. If you need control, pad the image yourself withcopyMakeBorder, run the filter, and crop.cv2.erode,cv2.dilateandcv2.morphologyExacceptborderTypeandborderValue. By default the border value is chosen so that the padding never affects the result. Erosion pads with the maximum possible value and dilation pads with the minimum, so the image edge does not shrink or grow artificially.
Pass the mode by keyword (borderType=...). The positional order differs between functions, and a wrong positional argument can silently be taken as another parameter such as the anchor.
Padding manually
Sometimes the built-in modes are not enough. A common pattern is to pad explicitly, filter, and crop, so you know exactly what the filter saw.
import cv2
import numpy as np
gray = np.random.default_rng(0).integers(0, 256, (40, 60), dtype=np.uint8)
pad = 10
padded = cv2.copyMakeBorder(gray, pad, pad, pad, pad, cv2.BORDER_REPLICATE)
blurred = cv2.GaussianBlur(padded, (0, 0), 3)
result = blurred[pad:-pad, pad:-pad]
print(gray.shape, padded.shape, result.shape)Choose pad at least as large as the kernel radius. For a Gaussian with sigma=3, OpenCV derives a kernel size of roughly 6 × sigma + 1, so a radius near 9 or 10 is appropriate. This approach also lets you filter an image tile with context from its neighbors, so that tile seams do not show.
Deciding which mode to use
In most cases, leave the default. Change it only when you can name a reason, such as periodic content or a known background value.
Common mistakes
- Cropping the border and assuming it is clean. Even with reflection, the outermost
k // 2pixels depend on invented data. If accuracy matters at the edge, discard that band or pad with real context. - Comparing results across functions.
medianBluralways replicates, whileGaussianBlurreflects by default, so edge pixels can differ between filters even with identical content. - Using a constant border with gradients. As shown above, it creates an artificial step edge along the image frame.
- Filtering a region of interest. When you pass a NumPy slice such as
img[10:50, 10:50], OpenCV can read pixels outside the slice from the parent image. PassborderType=cv2.BORDER_DEFAULT | cv2.BORDER_ISOLATEDto treat the slice as a standalone image. Copy the slice with.copy()if you want to avoid the question entirely.
Exercise
A uniform image has every pixel equal to 100. You apply a 3x3 box filter (cv2.blur with ksize (3, 3)) with borderType=cv2.BORDER_CONSTANT and the default fill value of 0. What value does the top-left corner pixel have in the output, and what value does a pixel in the middle of the top row have?
Show answer
The corner pixel has only 4 of its 9 neighborhood pixels inside the image, so its value is 100 4/9 = 44.4, which rounds to 44. A pixel in the middle of the top row has 6 of 9 inside, so its value is 100 6/9 = 66.7, which rounds to 67. Interior pixels stay at 100.
Exercise
You run Sobel and then Canny on a photo and see a thin bright line along the entire image frame in the gradient magnitude. You called cv2.Sobel with borderType=cv2.BORDER_CONSTANT. What causes the line, and how do you remove it?
Show answer
The constant border pads the image with zeros, so wherever the first and last rows or columns are not zero there is an artificial step between the image and the padding. Sobel reads that step as a strong gradient. Remove it by using the default BORDERREFLECT101 (or BORDER_REPLICATE), which pads with values similar to the real edge pixels and produces no step.