使用边界规则选择感兴趣的区域

时间:2018-12-09 09:57:20

标签: python numpy opencv scikit-image

我想在图像中的每个像素周围提取一个小窗口。当然,我可以使用Python列表切片来实现此目的。但是,仅列表切片无法解决“边缘情况”,在该情况下,大小W的窗口根本不存在于像素周围,因为它靠近边缘。考虑简单矩阵M

1 1 1 1
1 1 1 1
1 1 1 1

如果我想在M(1,1)周围选择一个3x3大小的窗口,因为上面或左边没有任何东西,我将无法选择。

Skimage中是否有Numpy函数或某些东西可以让我指定当列表索引超出范围时会发生什么?例如,如果我只想复制最近的邻居怎么办?

我当然可以自己编写此逻辑,因为这是一个微不足道的算法。我只是想知道Numpy,Skimage,OpenCV等中是否已经存在这样的选项。

1 个答案:

答案 0 :(得分:2)

通常,您首先通过np.pad() (docs)cv2.copyMakeBorder() (docs)填充图像,然后根据填充的大小移动要选择的索引。这两个功能的优点在于,它们提供了许多不同的选项,以及填充图像的值。 Numpy有更多选项,但是您要使用的大多数标准选项(重复边缘像素,镜像边缘像素,包装边缘像素或恒定填充)在两个库中都可用。

numpy边框类型直接在文档中列出,但是我将在此处复制它们:

mode : str or function
    One of the following string values or a user supplied function.

    ‘constant’
        Pads with a constant value.

    ‘edge’
        Pads with the edge values of array.

    ‘linear_ramp’
        Pads with the linear ramp between end_value and the array edge value.

    ‘maximum’
        Pads with the maximum value of all or part of the vector along each axis.

    ‘mean’
        Pads with the mean value of all or part of the vector along each axis.

    ‘median’
        Pads with the median value of all or part of the vector along each axis.

    ‘minimum’
        Pads with the minimum value of all or part of the vector along each axis.

    ‘reflect’
        Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

    ‘symmetric’
        Pads with the reflection of the vector mirrored along the edge of the array.

    ‘wrap’
        Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.

    <function>
        Padding function, see Notes.

对于传入的任意功能,它还有更进一步的说明,这是一个很酷的功能。

OpenCV边界类型未在copyMakeBorder()文档中直接指定,但是您可以通过搜索border types on the docs来找到。再说一次,只是将它们放在SO上:

BORDER_CONSTANT 
Python: cv.BORDER_CONSTANT
iiiiii|abcdefgh|iiiiiii with some specified i

BORDER_REPLICATE 
Python: cv.BORDER_REPLICATE
aaaaaa|abcdefgh|hhhhhhh

BORDER_REFLECT 
Python: cv.BORDER_REFLECT
fedcba|abcdefgh|hgfedcb

BORDER_WRAP 
Python: cv.BORDER_WRAP
cdefgh|abcdefgh|abcdefg

BORDER_REFLECT_101 
Python: cv.BORDER_REFLECT_101
gfedcb|abcdefgh|gfedcba

BORDER_TRANSPARENT 
Python: cv.BORDER_TRANSPARENT
uvwxyz|abcdefgh|ijklmno

BORDER_REFLECT101 
Python: cv.BORDER_REFLECT101
same as BORDER_REFLECT_101

BORDER_DEFAULT 
Python: cv.BORDER_DEFAULT
same as BORDER_REFLECT_101

BORDER_ISOLATED 
Python: cv.BORDER_ISOLATED
do not look outside of ROI