Search code examples
pythonnumpycrop

how crop an image evenly without loop


Suppose I have an np.array(image)

img = [[1,2,3,4],
       [5,6,7,8],
       [9,10,11,12],
       [13,14,15,16]]

How can I divide this in to 4 crops?

[[1,2],    [[3,4],    [[9,10],    [[11,12],
 [5,6]]     [7,8]]     [13,14]]     [15,16]]

The only way I know is to use loop to specify the img[x_start:x_end,y_start:y_end]. But this is very time-consuming when it comes to a large 3D Volume. NumPy library seems to perform better by itself than the loop in some algorithms. Btw, if I use img.reshape(-1,2,2), I get the following matrix, which is not what I want:

[[1,2],    [[5,6],    [[9,10],    [[13,14],
 [3,4]]     [7,8]]     [11,12]]     [15,16]]

Of course, it doesn't have to be Numpy library but can also cv2 or something like that which I can use in python


Solution

  • I hope I've undersdoot your question right:

    img = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
    
    out = [np.vsplit(x, 2) for x in np.hsplit(img, 2)]
    
    for arr1 in out:
        for arr2 in arr1:
            print(arr2)
            print()
    

    Prints:

    [[1 2]
     [5 6]]
    
    [[ 9 10]
     [13 14]]
    
    [[3 4]
     [7 8]]
    
    [[11 12]
     [15 16]]