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

问题描述 投票:-2回答:1

我有一个.img格式的图像,我想用python打开它。我该怎么办?

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

ERROR 4: `frame_064_0000.img' not recognized as a supported file format.
python image gdal
1个回答
1
投票

如果图像为8位,则图像为1,024 x 1,024像素,则将占用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.jpg

enter image description here

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

看起来像这样:

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)) 

Image.fromarray((img>>8).astype(np.uint8)).save('result.jpg') 
© www.soinside.com 2019 - 2024. All rights reserved.