How to split lines and cols in equal parts

Viewed 159

I have a image in numpy.arrayand I need to split all the lines into 4 'equal' (disregard odd) groups and 4 groups of cols. 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: enter image description here But this approach have a problem with the first loop and the begin:end:step. Some tips ?

I have also made this image to illustrate what I want:

enter image description here

1 Answers

You can use your logic with zip function and make the split dynamically::

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
Related