I have of a numpy array of a image.I want to convert this image into 8*8 block using python.How should I do this?
2 Answers
reshape and then swapaxes:
import numpy as np
img = np.random.randint(0, 255, size=(128, 256, 3)).astype(np.uint8)
blocks = img.reshape(img.shape[0]//8, 8, img.shape[1]//8, 8, 3).swapaxes(1, 2)
print(blocks.shape)
to check the result:
np.allclose(blocks[0, 0], img[:8, :8, :])
np.allclose(blocks[3, 2], img[3*8:3*8+8, 2*8:2*8+8, :])
Comments
Please provide your array structure.
you can use img_arrary.reshape(8,8), to work total elements must be 64
2 Comments
Gayan Jeewantha
In reshape function only get the whole image shaped.But I want to access the image data block by block.How sholud I do this?EX: It is needed to seperate whole image as seperate 8*8 pixel blocks.
SivaTP
you can use slicing or boolean masking. Just look at on Numpy Slicing tutorial, you will get it easily.