def flatten_and_pack(img, bits):
"""
Packs reduced bit depth images into bytes and returns a flattened array
Args:
img (uint8 numpy array): grayscale or multi-channel image
bits (int): 1, 2, 4, or 8 bits per channel
Returns:
uint8 numpy array: flattened and packed array
"""
# pad the image at the end of the rows, so that each row ends on a byte boundary
pixels_per_byte = 8 // bits
if len(img.shape) > 1:
if img.shape[1] % pixels_per_byte != 0:
img = np.hstack((img, np.zeros((img.shape[0], pixels_per_byte - img.shape[1] % pixels_per_byte), dtype=np.uint8)))
a = np.right_shift(img, 8-bits) # reduce bit depth
b = a.flatten() # flatten
c = np.zeros(b.size // pixels_per_byte, dtype=np.uint8)
for i in range(0, pixels_per_byte):
c += np.left_shift(b[i::pixels_per_byte], (pixels_per_byte-1-i)*bits) # pack pixels and add to result
return c
评论列表
文章目录