954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Extract header info from image file

I would like to extract the header info from an image file. For example I would like to search for the key "LINES" and return "2240" as string. And should I use open("r") or open("b") since im only interested in the header.

Header:



BANDS = 1
BAND_STORAGE_TYPE = BAND_SEQUENTIAL
BAND_NAME = "N/A"
LINES = 2240
LINE_SAMPLES = 3840
SAMPLE_TYPE = UNSIGNED_INTEGER
SAMPLE_BITS = 8
END





I wonder if this is the right direction.

file = "D:\\IMG\\mc03.img"
f = open(file,"r").readline()

for line in f:
if line.find("BAND"):
s = line.split()
h_band = s[2]
if line.find("LINES"):
s = line.split()
h_lines = s[2]

Thanks for any suggestions.

lostpenan
Newbie Poster
3 posts since Jul 2006
Reputation Points: 10
Solved Threads: 0
 

For image files I would stick with binary file operation, it can handle text too. Here is example:

# typical image header
str1 = \
"""BANDS = 1
BAND_STORAGE_TYPE = BAND_SEQUENTIAL
BAND_NAME = "N/A"
LINES = 2240
LINE_SAMPLES = 3840
SAMPLE_TYPE = UNSIGNED_INTEGER
SAMPLE_BITS = 8
END
~~now starts binary image data~~
"""

filename = "mc03.img"

# write test image file
fout = open(filename, "wb")
fout.write(str1)
fout.close()

# read image file line by line
for line in open(filename, "rb"):
    if 'END' in line:
        break
    if 'LINES' in line:
        # remove trailing newline
        line = line.rstrip('\n')
        # extract integer value
        print int(line.split('=')[1])  # 2240
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

Thanks! That's exactly what I need!

lostpenan
Newbie Poster
3 posts since Jul 2006
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You