PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] how crop an image evenly without loop

 July 27, 2022     crop, numpy, python     No comments   

Issue

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



Answered By - Andrej Kesely
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing