2014-07-01 88 views
2

我有一个数组,我可以处理这样的:最快的方式

ba = bytearray(fh.read())[32:] 
size = int(math.sqrt(len(ba))) 

我可以告诉大家,如果一个像素应该是黑色或白色给

iswhite = (ba[i]&1)==1 

如何快速将我的1D字节数组转换为行长为size的白色像素为(ba[i]&1)==1,黑色为其他人的2D numpy阵列?我创建数组是这样的:

im_m = np.zeros((size,size,3),dtype="uint8) 

回答

3
import numpy as np 

# fh containts the file handle 

# go to position 32 where the image data starts 
fh.seek(32) 

# read the binary data into unsigned 8-bit array 
ba = np.fromfile(fh, dtype='uint8') 

# calculate the side length of the square array and reshape ba accordingly 
side = int(np.sqrt(len(ba))) 
ba = ba.reshape((side,side)) 

# toss everything else apart from the last bit of each pixel 
ba &= 1 

# make a 3-deep array with 255,255,255 or 0,0,0 
img = np.dstack([255*ba]*3) 
# or 
img = ba[:,:,None] * np.array([255,255,255], dtype='uint8') 

有几种方法可以做到最后一步。如果您需要,请注意您获得相同的数据类型(uint8)。

+0

非常感谢,正是我所需要的 –

+0

嗯,我有一个问题,这里是完整的代码:http://pastebin.com/qX69JxpZ 我试图导出到JPG,但我得到的错误“最大支持的图像尺寸是65500像素” –

+0

该结构似乎是像素阵列(3个数字)的阵列中的一个单一的外部阵列 –