[英]Converting byte array to 16 bit grayscale image in Python
我正在處理以非標准圖像格式 (.Tsm) 存儲的大型圖像數據集。 本質上它是一個二進制文件,開頭有一些頭文件,與 FITS 標准非常相似,只是存儲在 little-endian 而不是 FITS big-endian。
讀取文件 header 並格式化元數據后,我可以使用以下代碼讀取單個圖像
def __read_slice(self, file, img_num, dimensions):
"""Read a single image slice from .tsm file"""
pixel_range = self.metadata["pixel range"]
bytes_to_read = self.metadata["bytes to read"]
# position file pointer to correct byte
file.seek(self.HEADER_TOTAL_LEN + (bytes_to_read * img_num), 0)
all_bytes = file.read(bytes_to_read) # read image bytes
img = np.empty(len(pixels), dtype='uint16') # preallocate image vector
byte_idx = 0
for idx, pixel in enumerate(pixel_range):
img[idx] = (all_bytes[byte_idx + 1] << 8) + all_bytes[byte_idx]
byte_idx += 2
return np.reshape(img, (dimensions[1], dimensions[0])) # reshape array to correct dimensions
問題是圖像可能非常大(2048x2048),因此即使只是加載 20-30 幀進行處理也可能需要大量時間。 我是 python 的新手,所以我猜這里的代碼效率很低,尤其是循環。
有沒有更有效的方法將字節數據轉換為 16 位整數?
你可以試試:
img= np.frombuffer(all_bytes, dtype='uint16')
例子:
>>> np.frombuffer(b'\x01\x02\x03\x04', dtype='uint16')
array([ 513, 1027], dtype=uint16)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.