python - 选择具有边界规则的感兴趣区域

标签 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 等中是否已经存在这样的选项。

最佳答案

通常,您首先通过 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 找到它们。 。再说一遍,只是为了让它们如此:

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

关于python - 选择具有边界规则的感兴趣区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53691157/

相关文章:

python - 替换字符串后缀

python - ipython 在不破坏目标文件中定义的全局变量的情况下运行

带有 sqlalchemy 的 Python Pandas |批量插入错误

python - 根据条件将数据帧的值移动到列表

python - 按日期时间对象对 numpy 数组进行排序

java - 在 OpenCV 3.2 中返回 Java 中的 Mat 对象

C++:升级到 GTX970 后 cv::gpu::GpuMat::upload 出现长时间延迟

Python,有没有办法将 df.drop 分配给新变量?

python - 为什么这些 numpy 操作不等效,我该如何解决这个问题?

opencv - 如何获得使用 OpenCV 创建的窗口位置 (x,y)?