Py学习  »  Python

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

Alekcey Dan • 5 年前 • 3719 次点击  

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

我有干扰模式 *.img 格式和我需要处理它。我试图用GDAL打开它,但是我有一个错误:

ERROR 4: `frame_064_0000.img' not recognized as a supported file format.
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51802
 
3719 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Mark Setchell
Reply   •   1 楼
Mark Setchell    5 年前

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

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

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

enter image description here

在Python中,可以打开文件,从文件末尾向后查找2097152字节,然后将其读入uint16的1024x102np.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)) 

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