2011-04-19 59 views
4

我使用Python和PIL作为我的工作的一部分,将数据嵌入到二值图像中,需要分析像素组以确定适当的像素以便嵌入数据。图像需要被分解成像素数据的“块”,以备分析,但我正在努力想出一个合适的方法来做这件事。我尝试过使用Python和numPy数组的技术,但没有成功。任何建议将不胜感激。将二进制图像划分为像素数据的'块'

感谢

+0

您有RGB或灰度/ bw图像吗? – Anatolij 2011-04-19 12:39:22

+0

图像是二进制的,因为黑色像素是'0',白色像素是'1',我认为这是一种灰度。 – BootStrap 2011-04-19 12:42:41

+1

单色或1位:) – Skurmedel 2011-04-19 12:51:30

回答

3

您需要使用numpyarray切片得到一组像素。图像只是2D数组,因此您可以使用arr = numpy.array(Image.open(filename)),然后切片。

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

可以使用鲜为人知的步幅技巧来创建你的形象是内置块的视图。它非常快速,并且不需要任何额外的内存(该示例有点冗长):

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

你如何防止块重叠? – Cerin 2011-11-09 02:29:40

相关问题