我有一個名為“.image”擴展名的文本檔案,檔案頂部如下:
Image Type: unsigned char
Dimension: 2
Image Size: 512 512
Image Spacing: 1 1
Image Increment: 1 1
Image Axis Labels: "" ""
Image Intensity Label: ""
193
我相信這是一個未簽名的 char 檔案,但我很難在 python 中打開它(并將其保存為 jpg、png 等)
已經嘗試過標準PIL.Image.open(),保存為字串并讀取Image.fromstring('RGB', (512,512), string),并讀取為類似位元組的物件Image.open(io.BytesIO(filepath))
有任何想法嗎?提前致謝
uj5u.com熱心網友回復:
如果我們假設檔案上有一些任意的、未知長度的標頭,我們可以讀取整個檔案,而不是決議標頭,只需從檔案尾部獲取最后的 512x512 位元組:
#!/usr/bin/env python3
from PIL import Image
import pathlib
# Slurp the entire contents of the file
f = pathlib.Path('image.raw').read_bytes()
# Specify height and width
h, w = 512, 512
# Take final h*w bytes from the tail of the file and treat as greyscale values, i.e. mode='L'
im = Image.frombuffer('L', (w,h), f[-(h*w):], "raw", 'L', 0, 1)
# Save to disk
im.save('result.png')
或者,如果您更喜歡 Numpy 而不是 Pathlib:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Specify height and width
h, w = 512, 512
# Slurp entire file into Numpy array, take final 512x512 bytes, and reshape to 512x512
na = np.fromfile('image.raw', dtype=np.uint8)[-(h*w):].reshape((h,w))
# Make Numpy array into PIL Image and save
Image.fromarray(na).save('result.png')
或者,如果您真的不喜歡撰寫任何 Python,只需tail 在終端中使用從檔案中切出最后 512x512 位元組,并告訴ImageMagick從灰度位元組值制作 8 位 PNG:
tail -c $((512*512)) image.raw | magick -depth 8 -size 512x512 gray:- result.png
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434012.html
