Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how crop an image evenly without loop

Tags:

python

numpy

crop

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

like image 691
Shawn Zhuang Avatar asked Jul 11 '26 22:07

Shawn Zhuang


1 Answers

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]]

like image 193
Andrej Kesely Avatar answered Jul 13 '26 12:07

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!