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.

Recommended Answers

All 2 Replies

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

Thanks! That's exactly what I need!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.