Debian Codegraph @

imageio/plugins/feisem.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """Read TIFF from FEI SEM microscopes.
5
6 Backend Library: internal
7
8 This format is based on :mod:`TIFF <imageio.plugins.tifffile>`, and supports the
9 same parameters. FEI microscopes append metadata as ASCII text at the end of the
10 file, which this reader correctly extracts.
11
12 Parameters
13 ----------
14 discard_watermark : bool
15 If True (default), discard the bottom rows of the image, which
16 contain no image data, only a watermark with metadata.
17 watermark_height : int
18 The height in pixels of the FEI watermark. The default is 70.
19
20 See Also
21 --------
22 :mod:`imageio.plugins.tifffile`
23
24 """
25
26 from .tifffile import TiffFormat
27
28
29 class FEISEMFormat(TiffFormat):
30 """See :mod:`imageio.plugins.feisem`"""
31
32 def _can_write(self, request):
33 return False # FEI-SEM only supports reading
34
35 class Reader(TiffFormat.Reader):
36 def _get_data(self, index=0, discard_watermark=True, watermark_height=70):
37 """Get image and metadata from given index.
38
39 FEI images usually (always?) contain a watermark at the
40 bottom of the image, 70 pixels high. We discard this by
41 default as it does not contain any information not present
42 in the metadata.
43 """
44 im, meta = super(FEISEMFormat.Reader, self)._get_data(index)
45 if discard_watermark:
46 im = im[:-watermark_height]
47 return im, meta
48
49 def _get_meta_data(self, index=None):
50 """Read the metadata from an FEI SEM TIFF.
51
52 This metadata is included as ASCII text at the end of the file.
53
54 The index, if provided, is ignored.
55
56 Returns
57 -------
58 metadata : dict
59 Dictionary of metadata.
60 """
61 if hasattr(self, "_fei_meta"):
62 return self._fei_meta
63
64 md = {"root": {}}
65 current_tag = "root"
66 reading_metadata = False
67 filename = self.request.get_local_filename()
68 with open(filename, encoding="utf8", errors="ignore") as fin:
69 for line in fin:
70 if not reading_metadata:
71 if not line.startswith("Date="):
72 continue
73 else:
74 reading_metadata = True
75 line = line.rstrip()
76 if line.startswith("["):
77 current_tag = line.lstrip("[").rstrip("]")
78 md[current_tag] = {}
79 else:
80 if "=" in line: # ignore empty and irrelevant lines
81 key, val = line.split("=", maxsplit=1)
82 for tag_type in (int, float):
83 try:
84 val = tag_type(val)
85 except ValueError:
86 continue
87 else:
88 break
89 md[current_tag][key] = val
90 if not md["root"] and len(md) == 1:
91 raise ValueError("Input file %s contains no FEI metadata." % filename)
92
93 self._fei_meta = md
94 return md