将图像切成" Tiles"使用Numpy

时间:2018-01-28 01:32:27

标签: python image numpy

我有一个图像,我想将其平铺成较小的块,以用于一些深度学习目的。我想使用numpy数组来更好地理解使用np。

目前我的图片已加载到numpy数组中,其形状为: (448,528,3)

我想要一个较小的8x8块的列表,我相信表示将是(n,8,8,3)。

目前我采取以下行动:

smaller_image.reshape(3696, 8, 8, 3)

图像变形。

感谢您的时间。

1 个答案:

答案 0 :(得分:5)

[更新:生成图块的新功能]

import numpy as np

def get_tile_images(image, width=8, height=8):
    _nrows, _ncols, depth = image.shape
    _size = image.size
    _strides = image.strides

    nrows, _m = divmod(_nrows, height)
    ncols, _n = divmod(_ncols, width)
    if _m != 0 or _n != 0:
        return None

    return np.lib.stride_tricks.as_strided(
        np.ravel(image),
        shape=(nrows, ncols, height, width, depth),
        strides=(height * _strides[0], width * _strides[1], *_strides),
        writeable=False
    )

假设我们a_image形状为(448, 528, 3)。获取28x33个图块(每个小图片的大小为16x16):

import matplotlib.pyplot as plt

image = plt.imread(a_image)
tiles = get_tile_images(image, 16, 16)

_nrows = int(image.shape[0] / 16)
_ncols = int(image.shape[1] / 16)

fig, ax = plt.subplots(nrows=_nrows, ncols=_ncols)

for i in range(_nrows):
    for j in range(_ncols):
        ax[i, j].imshow(tiles[i, j]); ax[i, j].set_axis_off();
相关问题