Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - 如何在python中读取.img文件?(How to read .img files in python?)

I have an image in format .img and I want to open it in python.

(我有一个.img格式的图像,我想在python中打开它。)

How can I do it?

(我该怎么做?)

I have an interference pattern in *.img format and I need to process it.

(我有一个*.img格式的干扰模式,需要对其进行处理。)

I tried to open it using GDAL, but I have an error:

(我尝试使用GDAL打开它,但出现错误:)

ERROR 4: `frame_064_0000.img' not recognized as a supported file format.
  ask by Alekcey Dan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your image is 1,024 x 1,024 pixels, that would make 1048576 bytes, if the data are 8-bit.

(如果图像是1,024 x 1,024像素,那么如果数据是8位的,则将占用1048576字节。)

But your file is 2097268 bytes, which is just a bit more than double the expected size, so I guessed your data are 16-bit, ie 2 bytes per pixel.

(但是您的文件为2097268字节,仅比预期大小多一倍,因此我猜您的数据为16位,即每像素2个字节。)

That means there are 2097268-(2*1024*1024), ie 116 bytes of other junk in the file.

(这意味着文件中有2097268-(2 * 1024 * 1024),即116字节的其他垃圾。)

Folks normally store that extra stuff at the start of the file.

(人们通常在文件的开头存储这些多余的东西。)

So, I just took the last 2097152 bytes of your file and assumed that was a 16-bit greyscale image at 1024x1024.

(因此,我只提取了文件的最后2097152字节,并假设该图像是1024x1024的16位灰度图像。)

You can do it at the command-line in Terminal with ImageMagick like this:

(您可以使用ImageMagick在Terminal的命令行中执行以下操作:)

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

在此处输入图片说明

In Python, you could open the file, seek backwards 2097152 bytes from the end of the file and read that into a 1024x1024 np.array of uint16.

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

That will look something like this:

(看起来像这样:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...