1
2
3
4
5 """
6 Reads a bytestream
7
8 Authors: Jon Wright Henning O. Sorensen & Erik Knudsen
9 ESRF Risoe National Laboratory
10 """
11
12 import numpy as N, logging
13
14 DATATYPES = {
15
16 ("int", 'n', 1) : N.uint8,
17 ("int", 'n', 2) : N.uint16,
18 ("int", 'n', 4) : N.uint32,
19 ("int", 'y', 1) : N.int8,
20 ("int", 'y', 2) : N.int16,
21 ("int", 'y', 4) : N.int32,
22 ('float','y',4) : N.float32,
23 ('double','y',4): N.float64
24 }
25
26
27 -def readbytestream(fil,
28 offset,
29 x,
30 y,
31 nbytespp,
32 datatype='int',
33 signed='n',
34 swap='n',
35 typeout=N.uint16):
36 """
37 Reads in a bytestream from a file (which may be a string indicating
38 a filename, or an already opened file (should be "rb"))
39 offset is the position (in bytes) where the pixel data start
40 nbytespp = number of bytes per pixel
41 type can be int or float (4 bytes pp) or double (8 bytes pp)
42 signed: normally signed data 'y', but 'n' to try to get back the
43 right numbers when unsigned data are converted to signed
44 (python once had no unsigned numeric types.)
45 swap, normally do not bother, but 'y' to swap bytes
46 typeout is the numpy type to output, normally uint16,
47 but more if overflows occurred
48 x and y are the pixel dimensions
49
50 TODO : Read in regions of interest
51
52 PLEASE LEAVE THE STRANGE INTERFACE ALONE -
53 IT IS USEFUL FOR THE BRUKER FORMAT
54 """
55 tin = "dunno"
56 length = nbytespp * x * y
57 if datatype in ['float', 'double']:
58 signed = 'y'
59
60 key = (datatype, signed, nbytespp)
61 try:
62 tin = DATATYPES[key]
63 except:
64 logging.warning("datatype,signed,nbytespp "+str(key))
65 raise Exception("Unknown combination of types to readbytestream")
66
67
68 if hasattr(fil,"read") and hasattr(fil,"seek"):
69 infile = fil
70 opened = False
71 else:
72 infile = open(fil,'rb')
73 opened = True
74
75 infile.seek(offset)
76
77 arr = N.array(N.reshape(
78 N.fromstring(
79 infile.read(length), tin) ,(x, y)),typeout)
80
81 if swap == 'y':
82 arr = arr.byteswap()
83
84 if opened:
85 infile.close()
86
87 return arr
88