reading *.his (image) file in Python
Question: I am trying to read an image file which is in *.his format. Honestly, I do not
know much about this format, on spending some time on google I figured out
that its a binary format and it can be read in ImageJ software as a raw format
import. On further inquiry, I found the following details of the *.his file:

  * Image type = 16-bit unsigned 
  * Matrix dimensions in pixels = w1024 x h1024 
  * Skip header info = 100 Bytes (The number of bytes in the file before the first byte of image data). 
  * Little-Endian Byte Order

With this information in hand, I started out ...

* * *

Just wanted to print the values in one by one, just to see the output:

    
    
    f = open("file.his", 'rb')
    f.seek(100) 
    try:
       byte = f.read(2)
       while byte != "":
          byte = f.read(2)
          print unpack('<H', byte) 
    finally:
    f.close()
    

It prints some numbers out and then the error message : ..... (64846,)
(64846,) (64830,)

Traceback (most recent call last): print unpack('

Plz can someone suggest me how to read this kind of file. I still think
'unpack' is the right function however if someone has similar experience, any
response greatly appreciated.

Rky.


Answer: I've done a very similar task with *.inr image file maybe the logic could help
you, here its what you could apply:

**1-Reading the file**

First you need to read the file.

    
    
    file = open(hisfile, 'r')
    inp = file.readlines()
    

**2-Get header**

In my case i done a for loop until the number of characters was 256, in your
case you need to count the bits so you could "print" line by line to find out
when you need to stop or try to use this to count the bits:

    
    
    import sys
    sys.getsizeof(line) #returns the size of the object
    

**3-Data**

When you already know that the following lines are the raw data you need to
put them in one variable with a for loop:

    
    
    for line in inp:
        raw_data += line
    

**4-Convert the data**

To convert the string to a numpy array you could do:

    
    
    data = fromstring(raw_data, dtype='uint16')
    

And then aplying the shape data:

    
    
    data = data.reshape((1024,1024)).transpose() #You need to see if the transpose part its relevant,because in my case was fundamental.
    

Maybe if you have an example of the file i could try to read it and help you
more. Of course you could do all the process in 1 for loop using if's.

