Dividing binary image into 'blocks' of pix

2019-05-07 02:00发布

I am using Python and PIL as part of my work on embedding data in binary images and need to analyse groups of pixels to determine appropriate pixels to manipulate in order to embed data. The image needs to be split into equal 'blocks' of pixel data ready for analysis, but I am struggling to come up with an appropriate method of doing this. I have tried techniques using Python and numPy arrays, but without success. Any suggestions would be greatly appreciated.

Thanks

2条回答
对你真心纯属浪费
2楼-- · 2019-05-07 02:06

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]]
查看更多
Fickle 薄情
3楼-- · 2019-05-07 02:26

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]
查看更多
登录 后发表回答