如何读取 python 中的 .img 文件?

How to read .img files in python?

我有一张格式为 .img 的图片,我想以 python 格式打开它。我该怎么做?

我有一个 *.img 格式的干涉图案,我需要对其进行处理。我尝试使用 GDAL 打开它,但出现错误:

ERROR 4: `frame_064_0000.img' not recognized as a supported file format.

如果您的图像是 1,024 x 1,024 像素,那么如果数据是 8 位,则将产生 1048576 字节。但是你的文件是 2097268 字节,只是预期大小的两倍多一点,所以我猜你的数据是 16 位的,即每个像素 2 个字节。这意味着文件中有 2097268-(2*1024*1024),即 116 字节的其他垃圾。人们通常将这些额外的东西存储在文件的开头。所以,我只取了你文件的最后 2097152 个字节,并假设这是一张 1024x1024 的 16 位灰度图像。

您可以使用 ImageMagick 在终端的命令行中执行此操作,如下所示:

magick -depth 16 -size 1024x1024+116 gray:frame_064_0000.img -auto-level result.png

在 Python 中,您可以打开文件,从文件末尾向后查找 2097152 字节并将其读入 1024x1024 np.array 的 uint16。

看起来像这样:

import numpy as np
from PIL import Image

filename = 'frame_064_0000.img' 

# set width and height 
w, h = 1024, 1024 

with open(filename, 'rb') as f: 
    # Seek backwards from end of file by 2 bytes per pixel 
    f.seek(-w*h*2, 2) 
    img = np.fromfile(f, dtype=np.uint16).reshape((h,w)) 

# Save as PNG, and retain 16-bit resolution
Image.fromarray(img).save('result.png')

# Alternative to line above - save as JPEG, but lose 16-bit resolution
Image.fromarray((img>>8).astype(np.uint8)).save('result.jpg')