tsaebeht
tsaebeht

Reputation: 1680

How to convert Python OpenCV Image Matrix into a List of 4x4 blocks

I have an image in the form of a matrix of 512 x 512 entries. Something like

[[12,234, . . ... .  (512 entries)],
 [[12,234, . . ... .  (512 entries)],
 [[12,234, . . ... .  (512 entries)],
 .
 .
 [12,234, . . ... .  (512 entries)]]

I want to break the image into 4x4 blocks and put them into one list. How do I do this? There would be 128 blocks of size 4 x 4, starting indexing from left.

Upvotes: 1

Views: 1387

Answers (2)

furas
furas

Reputation: 142794

OpenCV use numpy and numpy lets you use indexes like image[0:4, 0:4] to get square:

So you need something similar to this:

width, height = image.shape

# for image with ie. `RGB` color (3 bytes in every pixel)
#width, height, depth = image.shape 

blocks = []

for y in range(0, height, 4):
    for x in range(0, width, 4):
        blocks.append(image[y:y+4, x:x+4])

Upvotes: 1

cf2
cf2

Reputation: 591

Here is a function I use for this purpose:

def blockshaped(arr, nrows, ncols):

   h, w = arr.shape
   return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))

Where: arr = your input 2D np array

windowsize = integer, representing the size of the tiles

The output is an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size.

Upvotes: 2

Related Questions