如何将线和列分成相等的部分

时间:2018-09-15 22:24:26

标签: python arrays numpy split

我在numpy.array中有一张图片,我需要将所有行分成4个“相等”(忽略奇数)组和4个cols组。我确实尝试过:

for count in range(0, camera.shape[0], camera.shape[0] // 4):

    pp.figure()

    if count == 0:
        pp.imshow(camera[0:camera.shape[0] // 4:, :], cmap='gray')

        continue

    pp.imshow(camera[count: count * 2:, :], cmap='gray')

    # pp.imshow(camera[0:camera.shape[0] // 4:, :], cmap='gray')

pp.show()

结果: enter image description here 但是这种方法在第一个循环和begin:end:step中存在问题。一些提示?

我也制作了这张图片来说明我想要的东西:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将逻辑与zip函数一起使用,并动态进行拆分::

def split(img, rows, cols):
    '''
        Split array in n rows and columns

        Parameters
        ----------

        img:
            Arbitrary Numpy array

        rows:
            Number of rows to split the array

        cols:
            Number of cols to split the array

        Usage
        -----

        >>> split(skimage.data.camera(), 4, 4)

        Return
        ------

        Python list containing the subsets
    '''

    cache = []

    try:
        img_r = img.shape[0]

        img_c = img.shape[1]
    except Exception as e:
        raise Exception(
            f'\nInform a \033[31mNumpy\033[37m array\n\n{str(e)}\n')

    for c, n in zip(range(0, img_r + 1, img_r // rows), range(img_r // rows, img_r + 1, img_r // rows)):
        for i, f in zip(range(0, img_c + 1, img_c // cols), range(img_c // cols, img_c + 1, img_r // cols)):
            cache.append(img[c:n, i:f])

    return cache