简体   繁体   English

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

[英]How to split lines and cols in equal parts

I have a image in numpy.array and I need to split all the lines into 4 'equal' (disregard odd) groups and 4 groups of cols.我在numpy.array有一个图像,我需要将所有行分成 4 个“相等”(不考虑奇数)组和 4 组列。 I did try this:我确实尝试过这个:

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()

The result:结果: 在此处输入图片说明 But this approach have a problem with the first loop and the begin:end:step .但是这种方法在第一个循环和begin:end:step Some tips ?一些技巧 ?

I have also made this image to illustrate what I want:我还制作了这张图片来说明我想要的:

在此处输入图片说明

You can use your logic with zip function and make the split dynamically::您可以使用带有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

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

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