Dividing binary image into 'blocks' of pixel data

不羁岁月 提交于 2019-12-05 12:38:18

You need to use numpy array slicing to get group of pixels. Image is just 2D array, so you can use arr = numpy.array(Image.open(filename)), and after you can slice it.

#this code block from my fractal dimension finder
step = 2**a
for j in range(2**l):
    for i in range(2**l):
        block = arr[j * step:(j + 1) * step, i * step:(i + 1) * step]

You can use the little known stride tricks to create a view of your image that is built of blocks. It's very fast and does not take any additional memory (the example is a bit verbose):

import numpy as np

#img = np.array(Image.open(filename), dtype='uint8')

w, h = 5, 4 # width, height of image
bw, bh = 2, 3 # width, height of blocks

img = np.random.randint(2, size=(h, w)) # create a random binary image

# build a blocky view of the image data
sz = img.itemsize # size in bytes of the elements in img
shape = (h-bh+1, w-bw+1, bh, bw) # the shape of the new array: two indices for the blocks,
                                 # two indices for the content of each block
strides = (w*sz, sz, w*sz, sz) # information about how to map indices to image data
blocks = np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)

# now we can access the blocks
print img
[[1 1 0 0 0]
 [0 1 1 0 0]
 [0 0 1 0 1]
 [1 0 1 0 0]]

print blocks[0,0]
[[1 1]
 [0 1]
 [0 0]]

print blocks[1,2]
[[1 0]
 [1 0]
 [1 0]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!