[英]How to read an Unsigned Char image file to Python?
我有一个名为“.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
我相信这是一个未签名的字符文件,但我很难在 python 中打开它(并将其另存为 jpg、png 等)
已尝试标准PIL.Image.open()
,保存为字符串并使用Image.fromstring('RGB', (512,512), string)
读取,并读取为类似字节的 object Image.open(io.BytesIO(filepath))
有任何想法吗? 提前致谢
如果我们假设文件中有一些任意的、未知长度的 header,我们可以读取整个文件,而不是解析 header,只需从文件尾部取出最后的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.