【问题标题】:Quickest way to convert 1D byte array to 2D numpy array将一维字节数组转换为二维 numpy 数组的最快方法
【发布时间】:2014-07-01 19:39:47
【问题描述】:

我有一个可以这样处理的数组:

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

我可以判断一个像素应该是黑色还是白色

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

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

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

【问题讨论】:

    标签: python arrays image numpy


    【解决方案1】:
    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)。

    【讨论】:

    • 非常感谢,正是我需要的
    • 好吧,我遇到了一点问题,这是完整的代码:pastebin.com/qX69JxpZ 我正在尝试导出为 jpg,但出现错误“支持的最大图像尺寸为 65500 像素"
    • 该结构似乎是一个外部数组,其中包含一个像素数组(3 个)
    • @Christian Stewart。我的代码在 reshape 的行中有一个错字。我修好了它。关键是a.reshape(x,x)返回a的重塑版本(不重塑它),而a.resize((x,x))a = a.reshape((x,x))确实改变了A的形状。抱歉这个错误!
    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2012-09-16
    • 2023-02-03
    • 2014-06-21
    • 2011-07-05
    • 1970-01-01
    • 2015-08-23
    相关资源
    最近更新 更多