背景:
对于 numpy 来说,我们使用 uint8 类型,并没有 bit 类型。 因此,我抽取了一个函数,使用 unit8 类型,存储bit 类型的数据。
代码如下:
import numpy as np
def convert_binary_to_bitmap(binary_im):
""" 将 uint8 类型的 binary 变成 bitmap """
height = binary_im.shape[0]
width = binary_im.shape[1]
flatten_im = binary_im.flatten()
bitmap_im = np.zeros((int(width * height / 8)), dtype=np.uint8)
for idx in list(range(0, flatten_im.shape[0], 8)):
value = np.uint8(0)
for idx_inner in range(8):
value += flatten_im[idx + idx_inner] * 2 ** idx_inner
bitmap_im[int(idx / 8)] = value
return width, height, bitmap_im
if __name__ == '__main__':
binary_im = np.eye(8, dtype=np.uint8)
print(binary_im)
_, _, bitmap = convert_binary_to_bitmap(binary_im)
print(bitmap)
``
``
[[1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]]
[ 1 2 4 8 16 32 64 128]
``
|