2011-04-19 71 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

相關問題