Back to top

Viewing SPE 2 images using Python

Old CCD camera's developed by Princeton Instruments generate images in the SPE 2 file format. On Debian I was not able to find any software able to open these images. Luckily I was able to find the SPE 3.0 file format specification which contained enough information about the SPE 2 image format to write a Python script able to display the images.
import struct
import numpy as np
import matplotlib.pyplot as plt

def from_bytes(b, fmt, offset):
    size = struct.calcsize(fmt)
    return struct.unpack(fmt, b[offset:offset+size])[0]

def show_spe_image(b):
    datatype = from_bytes(b, "h", 108)
    version = from_bytes(b, "<f", 1992)
    frame_width = from_bytes(b, "H", 42)
    frame_height = from_bytes(b, "H", 656)
    num_frames = from_bytes(b, "i", 1446)
    exposure = from_bytes(b, "<f", 10)
    delay_time = from_bytes(b, "<f", 134)
    pulse_rep_width = from_bytes(b, "<f", 118)
    date = b[20:30]
    time = b[172:179]
    pulse_type = [None, "Fixed", "Exponential"][from_bytes(b, "h", 142)]
    
    print("datatype:", datatype)
    to_np_type = [np.float32, np.int32, np.int16, np.uint16, None, np.float64, np.uint8, None, np.uint32]
    np_type = to_np_type[datatype]
    itemsize = np.dtype(np_type).itemsize
    print("numpy type:", np_type)
    print("SPE version:", version)
    print("Frame width:", frame_width)
    print("Frame height:", frame_height)
    print("Number of frames:", num_frames)
    print("Exposure (s):", exposure)
    print("Delay time (us)", delay_time)
    print("Pulse repetition width (us)", pulse_rep_width)
    print("Pulse type increments: ", pulse_type)
    print("Date collected: ", date)
    print("Time collected (hhmmss):", time)
    
    count = frame_width * frame_height
    
    for i in range(0, num_frames):
        print("Showing frame number ", i+1)
        data = np.frombuffer(b, dtype=np_type, count=count, offset=4100 + i*count*itemsize)
        image = np.reshape(data, (frame_height, frame_width))

        plt.figure()
        plt.imshow(image)
        plt.show()

def show_image_from_file(filename):
    print("Filename:", filename)
    f = open(filename, "rb")
    show_spe_image(f.read())