简体   繁体   English

如何将 Unsigned Char 图像文件读取到 Python?

[英]How to read an Unsigned Char image file to Python?

I have an text file called with the extension '.image', at the top of the file is the following:我有一个名为“.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

I believe this to be an unsigned char file, but i'm having a hard time opening it in python (and saving it as a jpg, png etc)我相信这是一个未签名的字符文件,但我很难在 python 中打开它(并将其另存为 jpg、png 等)

Have tried the standard PIL.Image.open() , saving as a string and reading with Image.fromstring('RGB', (512,512), string) , and reading as byte-like object Image.open(io.BytesIO(filepath))已尝试标准PIL.Image.open() ,保存为字符串并使用Image.fromstring('RGB', (512,512), string)读取,并读取为类似字节的 object Image.open(io.BytesIO(filepath))

Any ideas?有任何想法吗? Thanks in advance提前致谢

If we assume there is some arbitrary, unknown length header on the file, we can read the entire file and then rather than parsing the header, just take the final 512x512 bytes from the tail of the file:如果我们假设文件中有一些任意的、未知长度的 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')

Or, if you prefer Numpy to Pathlib:或者,如果您更喜欢 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')

Or, if you don't really fancy writing any Python, just use tail in Terminal to slice the last 512x512 bytes off your file and tell ImageMagick to make an 8-bit PNG from the grayscale byte values:或者,如果您真的不想写任何 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM