2 回答

TA贡献1998条经验 获得超6个赞
在这种情况下,您对缺乏 bit numpy 位级别支持是正确的。可以按如下方式处理位的高级(但功能)方法:
image_16_bit = 123 # A 16bit integer.
bits = '{:016b}'.format(image_16_bit)
transparency = int(bits[0], 2)
red_channel = int(bits[1:6], 2)
green_channel = int(bits[6:11], 2)
blue_channel = int(bits[11:], 2)
print(transparency, red_channel, green_channel, blue_channel) # 0 0 3 27
您可以对所有整数运行此操作,然后收集各个通道值。最后,您可以将其转换为一个 numpy 数组,以将您的图像作为一个 numpy 数组。

TA贡献1794条经验 获得超8个赞
以下是如何使您的方法奏效:
# make small example
x = np.random.randint(0,1<<16,size=(5,5),dtype=np.uint16)
# set up dtype
dt = np.dtype([*zip('argb',(bool,*3*(np.uint8,)))])
# bit of bit twiddling
def unpack_argb(x):
out = np.empty(x.shape,dt)
for i,ch in enumerate(reversed('argb')):
out[ch] = (x>>(5*i))&31
return out
def pack_argb(x):
out = x['a'].astype(np.uint16)
for ch in 'rgb':
out <<= 5
out += x[ch]&31
return out
# check round trip
np.all(x == pack_argb(unpack_argb(x)))
# True
更新:
def argb16_to_rgba32(x):
out = np.empty(x.shape+(4,),np.uint8)
out[...,3] = (x>>8)&0x80
out[...,0] = (x>>7)&0xf8
out[...,1] = (x>>2)&0xf8
out[...,2] = (x<<3)&0xf8
return out
def rgba32_to_argb16(x):
x16 = x.astype(np.uint16)&0xf8
out = (x16[...,3]&0x80)<<8
out += x16[...,0]<<7
out += x16[...,1]<<2
out += x16[...,2]>>3
return out
添加回答
举报