小能豆

在 Python 中使用反射(镜像)进行图像填充

py

我在 Python 中加载了一个图像,作为形状为 (7, 7) 的 np.array。我需要对图像应用过滤过程。为此,我需要应用一个将卷积 2D 图像的内核(就像移动窗口一样)。但是,为了获得与输入形状相同的输出过滤图像,我需要扩展原始图像(填充)并在过滤之前将这些像素填充为镜像。

下面我用一张图片来说明我的问题:

1.png
注意:必须对图像的所有角应用填充。

我如何创建这个填充?

以下是一些示例数据:

img = np.array([[1, 2, 3, 4, 5, 6, 7],
                [8, 9, 10, 11, 12, 13, 14],
                [15, 16, 17, 18, 19, 20, 21],
                [22, 23, 24, 25, 26, 27, 28],
                [29, 30, 31, 32, 33, 34, 35],
                [36, 37, 37, 39, 40, 41, 42],
                [43, 44, 45, 46, 47, 48, 49]], dtype=np.uint8)

plt.imshow(img)

阅读 17

收藏
2025-01-04

共1个答案

小能豆

可以将np.padmode=一起使用'reflect'

img = np.pad(img, ((2, 2), (2, 2)), 'reflect')

例子:

import numpy as np

img = np.array([[ 1,  2,  3,  4,  5,  6,  7],
                [ 8,  9, 10, 11, 12, 13, 14],
                [15, 16, 17, 18, 19, 20, 21],
                [22, 23, 24, 25, 26, 27, 28],
                [29, 30, 31, 32, 33, 34, 35],
                [36, 37, 37, 39, 40, 41, 42],
                [43, 44, 45, 46, 47, 48, 49]], dtype=np.uint8)

pimg = np.pad(img, ((2, 2), (2, 2)), 'reflect')

Value of pimg:

array([[17, 16, 15, 16, 17, 18, 19, 20, 21, 20, 19],
       [10,  9,  8,  9, 10, 11, 12, 13, 14, 13, 12],
       [ 3,  2,  1,  2,  3,  4,  5,  6,  7,  6,  5],
       [10,  9,  8,  9, 10, 11, 12, 13, 14, 13, 12],
       [17, 16, 15, 16, 17, 18, 19, 20, 21, 20, 19],
       [24, 23, 22, 23, 24, 25, 26, 27, 28, 27, 26],
       [31, 30, 29, 30, 31, 32, 33, 34, 35, 34, 33],
       [37, 37, 36, 37, 37, 39, 40, 41, 42, 41, 40],
       [45, 44, 43, 44, 45, 46, 47, 48, 49, 48, 47],
       [37, 37, 36, 37, 37, 39, 40, 41, 42, 41, 40],
       [31, 30, 29, 30, 31, 32, 33, 34, 35, 34, 33]], dtype=uint8)
2025-01-04