简体   繁体   English

从python中的图像中有效地提取特定大小的补丁

[英]Extracting patches of a certain size from the image in python efficiently

I have an image and I want to extract square patches of different sizes from it. 我有一个图像,我想从中提取不同大小的方形补丁。

I need dense patches, that is, I need a patch at every pixel in the image. 我需要密集的补丁,也就是说,我需要在图像的每个像素处都有一个补丁。

For example if the image is 100x100 and the patch size is 64 . 例如,如果图像为100x100且色块大小为64

The result will be 10000 patches of size 64x64 结果将是10000个大小为64x64补丁

These are the same patches which we use for filtering operations for example. 这些是我们用于过滤操作的补丁,例如。

In case there is a boundary I would like to mirror the image. 如果有边界我想镜像图像。

What is the most efficient way of extracting patches using python? 使用python提取补丁的最有效方法是什么?

Thanks 谢谢

sklearn sklearn

You might want to have a look at sklearn.feature_extraction.image.extract_patches_2d and skimage.util.pad : 您可能想查看sklearn.feature_extraction.image.extract_patches_2dskimage.util.pad

>>> from sklearn.feature_extraction.image import extract_patches_2d
>>> import numpy as np
>>> A = np.arange(4*4).reshape(4,4)
>>> window_shape = (2, 2)
>>> B = extract_patches_2d(A, window_shape)
>>> B[0]
array([[0, 1],
       [4, 5]])
>>> B
array([[[ 0,  1],
        [ 4,  5]],

       [[ 1,  2],
        [ 5,  6]],

       [[ 2,  3],
        [ 6,  7]],

       [[ 4,  5],
        [ 8,  9]],

       [[ 5,  6],
        [ 9, 10]],

       [[ 6,  7],
        [10, 11]],

       [[ 8,  9],
        [12, 13]],

       [[ 9, 10],
        [13, 14]],

       [[10, 11],
        [14, 15]]])

skimage skimage

Expanding the answer of Stefan van der Walt a bit: 扩大了Stefan van der Walt的答案:

Install skimage 安装skimage

On Ubuntu 在Ubuntu上

$ sudo apt-get install python-skimage

or 要么

$ pip install scikit-image

Example from the docs 来自文档的示例

>>> from skimage.util import view_as_windows
>>> import numpy as np
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> window_shape = (2, 2)
>>> B = view_as_windows(A, window_shape)
>>> B[0]
array([[[0, 1],
        [4, 5]],

       [[1, 2],
        [5, 6]],

       [[2, 3],
        [6, 7]]])

>>> B
array([[[[ 0,  1],
         [ 4,  5]],

        [[ 1,  2],
         [ 5,  6]],

        [[ 2,  3],
         [ 6,  7]]],


       [[[ 4,  5],
         [ 8,  9]],

        [[ 5,  6],
         [ 9, 10]],

        [[ 6,  7],
         [10, 11]]],


       [[[ 8,  9],
         [12, 13]],

        [[ 9, 10],
         [13, 14]],

        [[10, 11],
         [14, 15]]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM