ZTWHHH commited on
Commit
9ff8e7c
·
verified ·
1 Parent(s): 4bbf272

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc +0 -0
  3. evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc +0 -0
  4. evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/imageio/config/plugins.py +782 -0
  6. evalkit_tf437/lib/python3.10/site-packages/imageio/config/plugins.pyi +28 -0
  7. evalkit_tf437/lib/python3.10/site-packages/imageio/core/findlib.py +161 -0
  8. evalkit_tf437/lib/python3.10/site-packages/imageio/core/imopen.py +281 -0
  9. evalkit_tf437/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi +27 -0
  10. evalkit_tf437/lib/python3.10/site-packages/imageio/core/util.py +561 -0
  11. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc +0 -0
  12. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_freeimage.cpython-310.pyc +0 -0
  13. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc +0 -0
  14. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc +0 -0
  15. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc +0 -0
  16. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/ffmpeg.cpython-310.pyc +0 -0
  17. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc +0 -0
  18. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimage.cpython-310.pyc +0 -0
  19. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/gdal.cpython-310.pyc +0 -0
  20. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/grab.cpython-310.pyc +0 -0
  21. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/lytro.cpython-310.pyc +0 -0
  22. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/opencv.cpython-310.pyc +0 -0
  23. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow.cpython-310.pyc +0 -0
  24. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_info.cpython-310.pyc +0 -0
  25. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_legacy.cpython-310.pyc +0 -0
  26. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/rawpy.cpython-310.pyc +0 -0
  27. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/spe.cpython-310.pyc +0 -0
  28. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/swf.cpython-310.pyc +0 -0
  29. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile.cpython-310.pyc +0 -0
  30. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile_v3.cpython-310.pyc +0 -0
  31. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/_dicom.py +932 -0
  32. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/example.py +145 -0
  33. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/feisem.py +95 -0
  34. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/grab.py +105 -0
  35. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/opencv.py +313 -0
  36. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/pillow_info.py +1053 -0
  37. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/pillow_legacy.py +823 -0
  38. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/simpleitk.py +156 -0
  39. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/swf.py +336 -0
  40. evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/tifffile.py +561 -0
  41. evalkit_tf437/lib/python3.10/site-packages/imageio/v3.py +259 -0
  42. falcon/bin/accelerate-merge-weights +8 -0
  43. falcon/bin/bzgrep +85 -0
  44. falcon/bin/convert-caffe2-to-onnx +8 -0
  45. falcon/bin/gradio +8 -0
  46. falcon/bin/httpx +8 -0
  47. falcon/bin/infocmp +0 -0
  48. falcon/bin/infotocap +0 -0
  49. falcon/bin/lzless +74 -0
  50. falcon/bin/lzmainfo +0 -0
.gitattributes CHANGED
@@ -1255,3 +1255,4 @@ evalkit_tf449/lib/python3.10/lib-dynload/_csv.cpython-310-x86_64-linux-gnu.so fi
1255
  evalkit_tf449/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1256
  evalkit_tf449/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1257
  infer_4_47_1/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
 
 
1255
  evalkit_tf449/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1256
  evalkit_tf449/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1257
  infer_4_47_1/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
1258
+ falcon/bin/x86_64-conda-linux-gnu-ld filter=lfs diff=lfs merge=lfs -text
evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (419 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc ADDED
Binary file (32.5 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/config/plugins.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ from ..core.legacy_plugin_wrapper import LegacyPlugin
4
+
5
+
6
+ class PluginConfig:
7
+ """Plugin Configuration Metadata
8
+
9
+ This class holds the information needed to lazy-import plugins.
10
+
11
+ Parameters
12
+ ----------
13
+ name : str
14
+ The name of the plugin.
15
+ class_name : str
16
+ The name of the plugin class inside the plugin module.
17
+ module_name : str
18
+ The name of the module/package from which to import the plugin.
19
+ is_legacy : bool
20
+ If True, this plugin is a v2 plugin and will be wrapped in a
21
+ LegacyPlugin. Default: False.
22
+ package_name : str
23
+ If the given module name points to a relative module, then the package
24
+ name determines the package it is relative to.
25
+ install_name : str
26
+ The name of the optional dependency that can be used to install this
27
+ plugin if it is missing.
28
+ legacy_args : Dict
29
+ A dictionary of kwargs to pass to the v2 plugin (Format) upon construction.
30
+
31
+ Examples
32
+ --------
33
+ >>> PluginConfig(
34
+ name="TIFF",
35
+ class_name="TiffFormat",
36
+ module_name="imageio.plugins.tifffile",
37
+ is_legacy=True,
38
+ install_name="tifffile",
39
+ legacy_args={
40
+ "description": "TIFF format",
41
+ "extensions": ".tif .tiff .stk .lsm",
42
+ "modes": "iIvV",
43
+ },
44
+ )
45
+ >>> PluginConfig(
46
+ name="pillow",
47
+ class_name="PillowPlugin",
48
+ module_name="imageio.plugins.pillow"
49
+ )
50
+
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ name,
56
+ class_name,
57
+ module_name,
58
+ *,
59
+ is_legacy=False,
60
+ package_name=None,
61
+ install_name=None,
62
+ legacy_args=None,
63
+ ):
64
+ legacy_args = legacy_args or dict()
65
+
66
+ self.name = name
67
+ self.class_name = class_name
68
+ self.module_name = module_name
69
+ self.package_name = package_name
70
+
71
+ self.is_legacy = is_legacy
72
+ self.install_name = install_name or self.name
73
+ self.legacy_args = {"name": name, "description": "A legacy plugin"}
74
+ self.legacy_args.update(legacy_args)
75
+
76
+ @property
77
+ def format(self):
78
+ """For backwards compatibility with FormatManager
79
+
80
+ Delete when migrating to v3
81
+ """
82
+ if not self.is_legacy:
83
+ raise RuntimeError("Can only get format for legacy plugins.")
84
+
85
+ module = importlib.import_module(self.module_name, self.package_name)
86
+ clazz = getattr(module, self.class_name)
87
+ return clazz(**self.legacy_args)
88
+
89
+ @property
90
+ def plugin_class(self):
91
+ """Get the plugin class (import if needed)
92
+
93
+ Returns
94
+ -------
95
+ plugin_class : Any
96
+ The class that can be used to instantiate plugins.
97
+
98
+ """
99
+
100
+ module = importlib.import_module(self.module_name, self.package_name)
101
+ clazz = getattr(module, self.class_name)
102
+
103
+ if self.is_legacy:
104
+ legacy_plugin = clazz(**self.legacy_args)
105
+
106
+ def partial_legacy_plugin(request):
107
+ return LegacyPlugin(request, legacy_plugin)
108
+
109
+ clazz = partial_legacy_plugin
110
+
111
+ return clazz
112
+
113
+
114
+ known_plugins = dict()
115
+ known_plugins["pillow"] = PluginConfig(
116
+ name="pillow", class_name="PillowPlugin", module_name="imageio.plugins.pillow"
117
+ )
118
+ known_plugins["pyav"] = PluginConfig(
119
+ name="pyav", class_name="PyAVPlugin", module_name="imageio.plugins.pyav"
120
+ )
121
+ known_plugins["opencv"] = PluginConfig(
122
+ name="opencv", class_name="OpenCVPlugin", module_name="imageio.plugins.opencv"
123
+ )
124
+ known_plugins["tifffile"] = PluginConfig(
125
+ name="tifffile",
126
+ class_name="TifffilePlugin",
127
+ module_name="imageio.plugins.tifffile_v3",
128
+ )
129
+ known_plugins["SPE"] = PluginConfig(
130
+ name="spe", class_name="SpePlugin", module_name="imageio.plugins.spe"
131
+ )
132
+ known_plugins["rawpy"] = PluginConfig(
133
+ name="rawpy", class_name="RawPyPlugin", module_name="imageio.plugins.rawpy"
134
+ )
135
+
136
+ # Legacy plugins
137
+ # ==============
138
+ #
139
+ # Which are partly registered by format, partly by plugin, and partly by a mix
140
+ # of both. We keep the naming here for backwards compatibility.
141
+ # In v3 this should become a single entry per plugin named after the plugin
142
+ # We can choose extension-specific priority in ``config.extensions``.
143
+ #
144
+ # Note: Since python 3.7 order of insertion determines the order of dict().keys()
145
+ # This means that the order here determines the order by which plugins are
146
+ # checked during the full fallback search. We don't advertise this downstream,
147
+ # but it could be a useful thing to keep in mind to choose a sensible default
148
+ # search order.
149
+
150
+ known_plugins["TIFF"] = PluginConfig(
151
+ name="TIFF",
152
+ class_name="TiffFormat",
153
+ module_name="imageio.plugins.tifffile",
154
+ is_legacy=True,
155
+ install_name="tifffile",
156
+ legacy_args={
157
+ "description": "TIFF format",
158
+ "extensions": ".tif .tiff .stk .lsm",
159
+ "modes": "iIvV",
160
+ },
161
+ )
162
+
163
+ # PILLOW plugin formats (legacy)
164
+ PILLOW_FORMATS = [
165
+ ("BMP", "Windows Bitmap", ".bmp", "PillowFormat"),
166
+ ("BUFR", "BUFR", ".bufr", "PillowFormat"),
167
+ ("CUR", "Windows Cursor", ".cur", "PillowFormat"),
168
+ ("DCX", "Intel DCX", ".dcx", "PillowFormat"),
169
+ ("DDS", "DirectDraw Surface", ".dds", "PillowFormat"),
170
+ ("DIB", "Windows Bitmap", "", "PillowFormat"),
171
+ ("EPS", "Encapsulated Postscript", ".ps .eps", "PillowFormat"),
172
+ ("FITS", "FITS", ".fit .fits", "PillowFormat"),
173
+ ("FLI", "Autodesk FLI/FLC Animation", ".fli .flc", "PillowFormat"),
174
+ ("FPX", "FlashPix", ".fpx", "PillowFormat"),
175
+ ("FTEX", "Texture File Format (IW2:EOC)", ".ftc .ftu", "PillowFormat"),
176
+ ("GBR", "GIMP brush file", ".gbr", "PillowFormat"),
177
+ ("GIF", "Compuserve GIF", ".gif", "GIFFormat"),
178
+ ("GRIB", "GRIB", ".grib", "PillowFormat"),
179
+ ("HDF5", "HDF5", ".h5 .hdf", "PillowFormat"),
180
+ ("ICNS", "Mac OS icns resource", ".icns", "PillowFormat"),
181
+ ("ICO", "Windows Icon", ".ico", "PillowFormat"),
182
+ ("IM", "IFUNC Image Memory", ".im", "PillowFormat"),
183
+ ("IMT", "IM Tools", "", "PillowFormat"),
184
+ ("IPTC", "IPTC/NAA", ".iim", "PillowFormat"),
185
+ ("JPEG", "JPEG (ISO 10918)", ".jfif .jpe .jpg .jpeg", "JPEGFormat"),
186
+ (
187
+ "JPEG2000",
188
+ "JPEG 2000 (ISO 15444)",
189
+ ".jp2 .j2k .jpc .jpf .jpx .j2c",
190
+ "JPEG2000Format",
191
+ ),
192
+ ("MCIDAS", "McIdas area file", "", "PillowFormat"),
193
+ ("MIC", "Microsoft Image Composer", ".mic", "PillowFormat"),
194
+ # skipped in legacy pillow
195
+ # ("MPEG", "MPEG", ".mpg .mpeg", "PillowFormat"),
196
+ ("MPO", "MPO (CIPA DC-007)", ".mpo", "PillowFormat"),
197
+ ("MSP", "Windows Paint", ".msp", "PillowFormat"),
198
+ ("PCD", "Kodak PhotoCD", ".pcd", "PillowFormat"),
199
+ ("PCX", "Paintbrush", ".pcx", "PillowFormat"),
200
+ ("PIXAR", "PIXAR raster image", ".pxr", "PillowFormat"),
201
+ ("PNG", "Portable network graphics", ".png", "PNGFormat"),
202
+ ("PPM", "Pbmplus image", ".pbm .pgm .ppm", "PillowFormat"),
203
+ ("PSD", "Adobe Photoshop", ".psd", "PillowFormat"),
204
+ ("SGI", "SGI Image File Format", ".bw .rgb .rgba .sgi", "PillowFormat"),
205
+ ("SPIDER", "Spider 2D image", "", "PillowFormat"),
206
+ ("SUN", "Sun Raster File", ".ras", "PillowFormat"),
207
+ ("TGA", "Targa", ".tga", "PillowFormat"),
208
+ ("TIFF", "Adobe TIFF", ".tif .tiff", "TIFFFormat"),
209
+ ("WMF", "Windows Metafile", ".wmf .emf", "PillowFormat"),
210
+ ("XBM", "X11 Bitmap", ".xbm", "PillowFormat"),
211
+ ("XPM", "X11 Pixel Map", ".xpm", "PillowFormat"),
212
+ ("XVTHUMB", "XV thumbnail image", "", "PillowFormat"),
213
+ ]
214
+ for id, summary, ext, class_name in PILLOW_FORMATS:
215
+ config = PluginConfig(
216
+ name=id.upper() + "-PIL",
217
+ class_name=class_name,
218
+ module_name="imageio.plugins.pillow_legacy",
219
+ is_legacy=True,
220
+ install_name="pillow",
221
+ legacy_args={
222
+ "description": summary + " via Pillow",
223
+ "extensions": ext,
224
+ "modes": "iI" if class_name == "GIFFormat" else "i",
225
+ "plugin_id": id,
226
+ },
227
+ )
228
+ known_plugins[config.name] = config
229
+
230
+ known_plugins["FFMPEG"] = PluginConfig(
231
+ name="FFMPEG",
232
+ class_name="FfmpegFormat",
233
+ module_name="imageio.plugins.ffmpeg",
234
+ is_legacy=True,
235
+ install_name="ffmpeg",
236
+ legacy_args={
237
+ "description": "Many video formats and cameras (via ffmpeg)",
238
+ "extensions": ".mov .avi .mpg .mpeg .mp4 .mkv .webm .wmv .h264",
239
+ "modes": "I",
240
+ },
241
+ )
242
+
243
+ known_plugins["BSDF"] = PluginConfig(
244
+ name="BSDF",
245
+ class_name="BsdfFormat",
246
+ module_name="imageio.plugins.bsdf",
247
+ is_legacy=True,
248
+ install_name="bsdf",
249
+ legacy_args={
250
+ "description": "Format based on the Binary Structured Data Format",
251
+ "extensions": ".bsdf",
252
+ "modes": "iIvV",
253
+ },
254
+ )
255
+
256
+ known_plugins["DICOM"] = PluginConfig(
257
+ name="DICOM",
258
+ class_name="DicomFormat",
259
+ module_name="imageio.plugins.dicom",
260
+ is_legacy=True,
261
+ install_name="dicom",
262
+ legacy_args={
263
+ "description": "Digital Imaging and Communications in Medicine",
264
+ "extensions": ".dcm .ct .mri",
265
+ "modes": "iIvV",
266
+ },
267
+ )
268
+
269
+ known_plugins["FEI"] = PluginConfig(
270
+ name="FEI",
271
+ class_name="FEISEMFormat",
272
+ module_name="imageio.plugins.feisem",
273
+ is_legacy=True,
274
+ install_name="feisem",
275
+ legacy_args={
276
+ "description": "FEI-SEM TIFF format",
277
+ "extensions": [".tif", ".tiff"],
278
+ "modes": "iv",
279
+ },
280
+ )
281
+
282
+ known_plugins["FITS"] = PluginConfig(
283
+ name="FITS",
284
+ class_name="FitsFormat",
285
+ module_name="imageio.plugins.fits",
286
+ is_legacy=True,
287
+ install_name="fits",
288
+ legacy_args={
289
+ "description": "Flexible Image Transport System (FITS) format",
290
+ "extensions": ".fits .fit .fts .fz",
291
+ "modes": "iIvV",
292
+ },
293
+ )
294
+
295
+ known_plugins["GDAL"] = PluginConfig(
296
+ name="GDAL",
297
+ class_name="GdalFormat",
298
+ module_name="imageio.plugins.gdal",
299
+ is_legacy=True,
300
+ install_name="gdal",
301
+ legacy_args={
302
+ "description": "Geospatial Data Abstraction Library",
303
+ "extensions": ".tiff .tif .img .ecw .jpg .jpeg",
304
+ "modes": "iIvV",
305
+ },
306
+ )
307
+
308
+ known_plugins["ITK"] = PluginConfig(
309
+ name="ITK",
310
+ class_name="ItkFormat",
311
+ module_name="imageio.plugins.simpleitk",
312
+ is_legacy=True,
313
+ install_name="simpleitk",
314
+ legacy_args={
315
+ "description": "Insight Segmentation and Registration Toolkit (ITK) format",
316
+ "extensions": " ".join(
317
+ (
318
+ ".gipl",
319
+ ".ipl",
320
+ ".mha",
321
+ ".mhd",
322
+ ".nhdr",
323
+ ".nia",
324
+ ".hdr",
325
+ ".nrrd",
326
+ ".nii",
327
+ ".nii.gz",
328
+ ".img",
329
+ ".img.gz",
330
+ ".vtk",
331
+ ".hdf5",
332
+ ".lsm",
333
+ ".mnc",
334
+ ".mnc2",
335
+ ".mgh",
336
+ ".mnc",
337
+ ".pic",
338
+ ".bmp",
339
+ ".jpeg",
340
+ ".jpg",
341
+ ".png",
342
+ ".tiff",
343
+ ".tif",
344
+ ".dicom",
345
+ ".dcm",
346
+ ".gdcm",
347
+ )
348
+ ),
349
+ "modes": "iIvV",
350
+ },
351
+ )
352
+
353
+ known_plugins["NPZ"] = PluginConfig(
354
+ name="NPZ",
355
+ class_name="NpzFormat",
356
+ module_name="imageio.plugins.npz",
357
+ is_legacy=True,
358
+ install_name="numpy",
359
+ legacy_args={
360
+ "description": "Numpy's compressed array format",
361
+ "extensions": ".npz",
362
+ "modes": "iIvV",
363
+ },
364
+ )
365
+
366
+ known_plugins["SWF"] = PluginConfig(
367
+ name="SWF",
368
+ class_name="SWFFormat",
369
+ module_name="imageio.plugins.swf",
370
+ is_legacy=True,
371
+ install_name="swf",
372
+ legacy_args={
373
+ "description": "Shockwave flash",
374
+ "extensions": ".swf",
375
+ "modes": "I",
376
+ },
377
+ )
378
+
379
+ known_plugins["SCREENGRAB"] = PluginConfig(
380
+ name="SCREENGRAB",
381
+ class_name="ScreenGrabFormat",
382
+ module_name="imageio.plugins.grab",
383
+ is_legacy=True,
384
+ install_name="pillow",
385
+ legacy_args={
386
+ "description": "Grab screenshots (Windows and OS X only)",
387
+ "extensions": [],
388
+ "modes": "i",
389
+ },
390
+ )
391
+
392
+ known_plugins["CLIPBOARDGRAB"] = PluginConfig(
393
+ name="CLIPBOARDGRAB",
394
+ class_name="ClipboardGrabFormat",
395
+ module_name="imageio.plugins.grab",
396
+ is_legacy=True,
397
+ install_name="pillow",
398
+ legacy_args={
399
+ "description": "Grab from clipboard (Windows only)",
400
+ "extensions": [],
401
+ "modes": "i",
402
+ },
403
+ )
404
+
405
+ # LYTRO plugin (legacy)
406
+ lytro_formats = [
407
+ ("lytro-lfr", "Lytro Illum lfr image file", ".lfr", "i", "LytroLfrFormat"),
408
+ (
409
+ "lytro-illum-raw",
410
+ "Lytro Illum raw image file",
411
+ ".raw",
412
+ "i",
413
+ "LytroIllumRawFormat",
414
+ ),
415
+ ("lytro-lfp", "Lytro F01 lfp image file", ".lfp", "i", "LytroLfpFormat"),
416
+ ("lytro-f01-raw", "Lytro F01 raw image file", ".raw", "i", "LytroF01RawFormat"),
417
+ ]
418
+ for name, des, ext, mode, class_name in lytro_formats:
419
+ config = PluginConfig(
420
+ name=name.upper(),
421
+ class_name=class_name,
422
+ module_name="imageio.plugins.lytro",
423
+ is_legacy=True,
424
+ install_name="lytro",
425
+ legacy_args={
426
+ "description": des,
427
+ "extensions": ext,
428
+ "modes": mode,
429
+ },
430
+ )
431
+ known_plugins[config.name] = config
432
+
433
+ # FreeImage plugin (legacy)
434
+ FREEIMAGE_FORMATS = [
435
+ (
436
+ "BMP",
437
+ 0,
438
+ "Windows or OS/2 Bitmap",
439
+ ".bmp",
440
+ "i",
441
+ "FreeimageBmpFormat",
442
+ "imageio.plugins.freeimage",
443
+ ),
444
+ (
445
+ "CUT",
446
+ 21,
447
+ "Dr. Halo",
448
+ ".cut",
449
+ "i",
450
+ "FreeimageFormat",
451
+ "imageio.plugins.freeimage",
452
+ ),
453
+ (
454
+ "DDS",
455
+ 24,
456
+ "DirectX Surface",
457
+ ".dds",
458
+ "i",
459
+ "FreeimageFormat",
460
+ "imageio.plugins.freeimage",
461
+ ),
462
+ (
463
+ "EXR",
464
+ 29,
465
+ "ILM OpenEXR",
466
+ ".exr",
467
+ "i",
468
+ "FreeimageFormat",
469
+ "imageio.plugins.freeimage",
470
+ ),
471
+ (
472
+ "G3",
473
+ 27,
474
+ "Raw fax format CCITT G.3",
475
+ ".g3",
476
+ "i",
477
+ "FreeimageFormat",
478
+ "imageio.plugins.freeimage",
479
+ ),
480
+ (
481
+ "GIF",
482
+ 25,
483
+ "Static and animated gif (FreeImage)",
484
+ ".gif",
485
+ "iI",
486
+ "GifFormat",
487
+ "imageio.plugins.freeimagemulti",
488
+ ),
489
+ (
490
+ "HDR",
491
+ 26,
492
+ "High Dynamic Range Image",
493
+ ".hdr",
494
+ "i",
495
+ "FreeimageFormat",
496
+ "imageio.plugins.freeimage",
497
+ ),
498
+ (
499
+ "ICO",
500
+ 1,
501
+ "Windows Icon",
502
+ ".ico",
503
+ "iI",
504
+ "IcoFormat",
505
+ "imageio.plugins.freeimagemulti",
506
+ ),
507
+ (
508
+ "IFF",
509
+ 5,
510
+ "IFF Interleaved Bitmap",
511
+ ".iff .lbm",
512
+ "i",
513
+ "FreeimageFormat",
514
+ "imageio.plugins.freeimage",
515
+ ),
516
+ (
517
+ "J2K",
518
+ 30,
519
+ "JPEG-2000 codestream",
520
+ ".j2k .j2c",
521
+ "i",
522
+ "FreeimageFormat",
523
+ "imageio.plugins.freeimage",
524
+ ),
525
+ (
526
+ "JNG",
527
+ 3,
528
+ "JPEG Network Graphics",
529
+ ".jng",
530
+ "i",
531
+ "FreeimageFormat",
532
+ "imageio.plugins.freeimage",
533
+ ),
534
+ (
535
+ "JP2",
536
+ 31,
537
+ "JPEG-2000 File Format",
538
+ ".jp2",
539
+ "i",
540
+ "FreeimageFormat",
541
+ "imageio.plugins.freeimage",
542
+ ),
543
+ (
544
+ "JPEG",
545
+ 2,
546
+ "JPEG - JFIF Compliant",
547
+ ".jpg .jif .jpeg .jpe",
548
+ "i",
549
+ "FreeimageJpegFormat",
550
+ "imageio.plugins.freeimage",
551
+ ),
552
+ (
553
+ "JPEG-XR",
554
+ 36,
555
+ "JPEG XR image format",
556
+ ".jxr .wdp .hdp",
557
+ "i",
558
+ "FreeimageFormat",
559
+ "imageio.plugins.freeimage",
560
+ ),
561
+ (
562
+ "KOALA",
563
+ 4,
564
+ "C64 Koala Graphics",
565
+ ".koa",
566
+ "i",
567
+ "FreeimageFormat",
568
+ "imageio.plugins.freeimage",
569
+ ),
570
+ # not registered in legacy pillow
571
+ # ("MNG", 6, "Multiple-image Network Graphics", ".mng", "i", "FreeimageFormat", "imageio.plugins.freeimage"),
572
+ (
573
+ "PBM",
574
+ 7,
575
+ "Portable Bitmap (ASCII)",
576
+ ".pbm",
577
+ "i",
578
+ "FreeimageFormat",
579
+ "imageio.plugins.freeimage",
580
+ ),
581
+ (
582
+ "PBMRAW",
583
+ 8,
584
+ "Portable Bitmap (RAW)",
585
+ ".pbm",
586
+ "i",
587
+ "FreeimageFormat",
588
+ "imageio.plugins.freeimage",
589
+ ),
590
+ (
591
+ "PCD",
592
+ 9,
593
+ "Kodak PhotoCD",
594
+ ".pcd",
595
+ "i",
596
+ "FreeimageFormat",
597
+ "imageio.plugins.freeimage",
598
+ ),
599
+ (
600
+ "PCX",
601
+ 10,
602
+ "Zsoft Paintbrush",
603
+ ".pcx",
604
+ "i",
605
+ "FreeimageFormat",
606
+ "imageio.plugins.freeimage",
607
+ ),
608
+ (
609
+ "PFM",
610
+ 32,
611
+ "Portable floatmap",
612
+ ".pfm",
613
+ "i",
614
+ "FreeimageFormat",
615
+ "imageio.plugins.freeimage",
616
+ ),
617
+ (
618
+ "PGM",
619
+ 11,
620
+ "Portable Greymap (ASCII)",
621
+ ".pgm",
622
+ "i",
623
+ "FreeimageFormat",
624
+ "imageio.plugins.freeimage",
625
+ ),
626
+ (
627
+ "PGMRAW",
628
+ 12,
629
+ "Portable Greymap (RAW)",
630
+ ".pgm",
631
+ "i",
632
+ "FreeimageFormat",
633
+ "imageio.plugins.freeimage",
634
+ ),
635
+ (
636
+ "PICT",
637
+ 33,
638
+ "Macintosh PICT",
639
+ ".pct .pict .pic",
640
+ "i",
641
+ "FreeimageFormat",
642
+ "imageio.plugins.freeimage",
643
+ ),
644
+ (
645
+ "PNG",
646
+ 13,
647
+ "Portable Network Graphics",
648
+ ".png",
649
+ "i",
650
+ "FreeimagePngFormat",
651
+ "imageio.plugins.freeimage",
652
+ ),
653
+ (
654
+ "PPM",
655
+ 14,
656
+ "Portable Pixelmap (ASCII)",
657
+ ".ppm",
658
+ "i",
659
+ "FreeimagePnmFormat",
660
+ "imageio.plugins.freeimage",
661
+ ),
662
+ (
663
+ "PPMRAW",
664
+ 15,
665
+ "Portable Pixelmap (RAW)",
666
+ ".ppm",
667
+ "i",
668
+ "FreeimagePnmFormat",
669
+ "imageio.plugins.freeimage",
670
+ ),
671
+ (
672
+ "PSD",
673
+ 20,
674
+ "Adobe Photoshop",
675
+ ".psd",
676
+ "i",
677
+ "FreeimageFormat",
678
+ "imageio.plugins.freeimage",
679
+ ),
680
+ (
681
+ "RAS",
682
+ 16,
683
+ "Sun Raster Image",
684
+ ".ras",
685
+ "i",
686
+ "FreeimageFormat",
687
+ "imageio.plugins.freeimage",
688
+ ),
689
+ (
690
+ "RAW",
691
+ 34,
692
+ "RAW camera image",
693
+ ".3fr .arw .bay .bmq .cap .cine .cr2 .crw .cs1 .dc2 "
694
+ ".dcr .drf .dsc .dng .erf .fff .ia .iiq .k25 .kc2 .kdc .mdc .mef .mos .mrw .nef .nrw .orf "
695
+ ".pef .ptx .pxn .qtk .raf .raw .rdc .rw2 .rwl .rwz .sr2 .srf .srw .sti",
696
+ "i",
697
+ "FreeimageFormat",
698
+ "imageio.plugins.freeimage",
699
+ ),
700
+ (
701
+ "SGI",
702
+ 28,
703
+ "SGI Image Format",
704
+ ".sgi .rgb .rgba .bw",
705
+ "i",
706
+ "FreeimageFormat",
707
+ "imageio.plugins.freeimage",
708
+ ),
709
+ (
710
+ "TARGA",
711
+ 17,
712
+ "Truevision Targa",
713
+ ".tga .targa",
714
+ "i",
715
+ "FreeimageFormat",
716
+ "imageio.plugins.freeimage",
717
+ ),
718
+ (
719
+ "TIFF",
720
+ 18,
721
+ "Tagged Image File Format",
722
+ ".tif .tiff",
723
+ "i",
724
+ "FreeimageFormat",
725
+ "imageio.plugins.freeimage",
726
+ ),
727
+ (
728
+ "WBMP",
729
+ 19,
730
+ "Wireless Bitmap",
731
+ ".wap .wbmp .wbm",
732
+ "i",
733
+ "FreeimageFormat",
734
+ "imageio.plugins.freeimage",
735
+ ),
736
+ (
737
+ "WebP",
738
+ 35,
739
+ "Google WebP image format",
740
+ ".webp",
741
+ "i",
742
+ "FreeimageFormat",
743
+ "imageio.plugins.freeimage",
744
+ ),
745
+ (
746
+ "XBM",
747
+ 22,
748
+ "X11 Bitmap Format",
749
+ ".xbm",
750
+ "i",
751
+ "FreeimageFormat",
752
+ "imageio.plugins.freeimage",
753
+ ),
754
+ (
755
+ "XPM",
756
+ 23,
757
+ "X11 Pixmap Format",
758
+ ".xpm",
759
+ "i",
760
+ "FreeimageFormat",
761
+ "imageio.plugins.freeimage",
762
+ ),
763
+ ]
764
+ for name, i, des, ext, mode, class_name, module_name in FREEIMAGE_FORMATS:
765
+ config = PluginConfig(
766
+ name=name.upper() + "-FI",
767
+ class_name=class_name,
768
+ module_name=module_name,
769
+ is_legacy=True,
770
+ install_name="freeimage",
771
+ legacy_args={
772
+ "description": des,
773
+ "extensions": ext,
774
+ "modes": mode,
775
+ "fif": i,
776
+ },
777
+ )
778
+ known_plugins[config.name] = config
779
+
780
+ # exists for backwards compatibility with FormatManager
781
+ # delete in V3
782
+ _original_order = [x for x, config in known_plugins.items() if config.is_legacy]
evalkit_tf437/lib/python3.10/site-packages/imageio/config/plugins.pyi ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+ from ..core.v3_plugin_api import PluginV3
3
+
4
+ class PluginConfig:
5
+ name: str
6
+ class_name: str
7
+ module_name: str
8
+ is_legacy: bool
9
+ package_name: Optional[str] = None
10
+ install_name: Optional[str] = None
11
+ legacy_args: Optional[dict] = None
12
+ @property
13
+ def format(self) -> Any: ...
14
+ @property
15
+ def plugin_class(self) -> PluginV3: ...
16
+ def __init__(
17
+ self,
18
+ name: str,
19
+ class_name: str,
20
+ module_name: str,
21
+ *,
22
+ is_legacy: bool = False,
23
+ package_name: str = None,
24
+ install_name: str = None,
25
+ legacy_args: dict = None,
26
+ ) -> None: ...
27
+
28
+ known_plugins: Dict[str, PluginConfig]
evalkit_tf437/lib/python3.10/site-packages/imageio/core/findlib.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2015-1018, imageio contributors
3
+ # Copyright (C) 2013, Zach Pincus, Almar Klein and others
4
+
5
+ """ This module contains generic code to find and load a dynamic library.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import ctypes
11
+
12
+
13
+ LOCALDIR = os.path.abspath(os.path.dirname(__file__))
14
+
15
+ # Flag that can be patched / set to True to disable loading non-system libs
16
+ SYSTEM_LIBS_ONLY = False
17
+
18
+
19
+ def looks_lib(fname):
20
+ """Returns True if the given filename looks like a dynamic library.
21
+ Based on extension, but cross-platform and more flexible.
22
+ """
23
+ fname = fname.lower()
24
+ if sys.platform.startswith("win"):
25
+ return fname.endswith(".dll")
26
+ elif sys.platform.startswith("darwin"):
27
+ return fname.endswith(".dylib")
28
+ else:
29
+ return fname.endswith(".so") or ".so." in fname
30
+
31
+
32
+ def generate_candidate_libs(lib_names, lib_dirs=None):
33
+ """Generate a list of candidate filenames of what might be the dynamic
34
+ library corresponding with the given list of names.
35
+ Returns (lib_dirs, lib_paths)
36
+ """
37
+ lib_dirs = lib_dirs or []
38
+
39
+ # Get system dirs to search
40
+ sys_lib_dirs = [
41
+ "/lib",
42
+ "/usr/lib",
43
+ "/usr/lib/x86_64-linux-gnu",
44
+ "/usr/lib/aarch64-linux-gnu",
45
+ "/usr/local/lib",
46
+ "/opt/local/lib",
47
+ ]
48
+
49
+ # Get Python dirs to search (shared if for Pyzo)
50
+ py_sub_dirs = ["bin", "lib", "DLLs", "Library/bin", "shared"]
51
+ py_lib_dirs = [os.path.join(sys.prefix, d) for d in py_sub_dirs]
52
+ if hasattr(sys, "base_prefix"):
53
+ py_lib_dirs += [os.path.join(sys.base_prefix, d) for d in py_sub_dirs]
54
+
55
+ # Get user dirs to search (i.e. HOME)
56
+ home_dir = os.path.expanduser("~")
57
+ user_lib_dirs = [os.path.join(home_dir, d) for d in ["lib"]]
58
+
59
+ # Select only the dirs for which a directory exists, and remove duplicates
60
+ potential_lib_dirs = lib_dirs + sys_lib_dirs + py_lib_dirs + user_lib_dirs
61
+ lib_dirs = []
62
+ for ld in potential_lib_dirs:
63
+ if os.path.isdir(ld) and ld not in lib_dirs:
64
+ lib_dirs.append(ld)
65
+
66
+ # Now attempt to find libraries of that name in the given directory
67
+ # (case-insensitive)
68
+ lib_paths = []
69
+ for lib_dir in lib_dirs:
70
+ # Get files, prefer short names, last version
71
+ files = os.listdir(lib_dir)
72
+ files = reversed(sorted(files))
73
+ files = sorted(files, key=len)
74
+ for lib_name in lib_names:
75
+ # Test all filenames for name and ext
76
+ for fname in files:
77
+ if fname.lower().startswith(lib_name) and looks_lib(fname):
78
+ lib_paths.append(os.path.join(lib_dir, fname))
79
+
80
+ # Return (only the items which are files)
81
+ lib_paths = [lp for lp in lib_paths if os.path.isfile(lp)]
82
+ return lib_dirs, lib_paths
83
+
84
+
85
+ def load_lib(exact_lib_names, lib_names, lib_dirs=None):
86
+ """load_lib(exact_lib_names, lib_names, lib_dirs=None)
87
+
88
+ Load a dynamic library.
89
+
90
+ This function first tries to load the library from the given exact
91
+ names. When that fails, it tries to find the library in common
92
+ locations. It searches for files that start with one of the names
93
+ given in lib_names (case insensitive). The search is performed in
94
+ the given lib_dirs and a set of common library dirs.
95
+
96
+ Returns ``(ctypes_library, library_path)``
97
+ """
98
+
99
+ # Checks
100
+ assert isinstance(exact_lib_names, list)
101
+ assert isinstance(lib_names, list)
102
+ if lib_dirs is not None:
103
+ assert isinstance(lib_dirs, list)
104
+ exact_lib_names = [n for n in exact_lib_names if n]
105
+ lib_names = [n for n in lib_names if n]
106
+
107
+ # Get reference name (for better messages)
108
+ if lib_names:
109
+ the_lib_name = lib_names[0]
110
+ elif exact_lib_names:
111
+ the_lib_name = exact_lib_names[0]
112
+ else:
113
+ raise ValueError("No library name given.")
114
+
115
+ # Collect filenames of potential libraries
116
+ # First try a few bare library names that ctypes might be able to find
117
+ # in the default locations for each platform.
118
+ if SYSTEM_LIBS_ONLY:
119
+ lib_dirs, lib_paths = [], []
120
+ else:
121
+ lib_dirs, lib_paths = generate_candidate_libs(lib_names, lib_dirs)
122
+ lib_paths = exact_lib_names + lib_paths
123
+
124
+ # Select loader
125
+ if sys.platform.startswith("win"):
126
+ loader = ctypes.windll
127
+ else:
128
+ loader = ctypes.cdll
129
+
130
+ # Try to load until success
131
+ the_lib = None
132
+ errors = []
133
+ for fname in lib_paths:
134
+ try:
135
+ the_lib = loader.LoadLibrary(fname)
136
+ break
137
+ except Exception as err:
138
+ # Don't record errors when it couldn't load the library from an
139
+ # exact name -- this fails often, and doesn't provide any useful
140
+ # debugging information anyway, beyond "couldn't find library..."
141
+ if fname not in exact_lib_names:
142
+ errors.append((fname, err))
143
+
144
+ # No success ...
145
+ if the_lib is None:
146
+ if errors:
147
+ # No library loaded, and load-errors reported for some
148
+ # candidate libs
149
+ err_txt = ["%s:\n%s" % (lib, str(e)) for lib, e in errors]
150
+ msg = (
151
+ "One or more %s libraries were found, but "
152
+ + "could not be loaded due to the following errors:\n%s"
153
+ )
154
+ raise OSError(msg % (the_lib_name, "\n\n".join(err_txt)))
155
+ else:
156
+ # No errors, because no potential libraries found at all!
157
+ msg = "Could not find a %s library in any of:\n%s"
158
+ raise OSError(msg % (the_lib_name, "\n".join(lib_dirs)))
159
+
160
+ # Done
161
+ return the_lib, fname
evalkit_tf437/lib/python3.10/site-packages/imageio/core/imopen.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import warnings
3
+
4
+ from ..config import known_plugins
5
+ from ..config.extensions import known_extensions
6
+ from .request import (
7
+ SPECIAL_READ_URIS,
8
+ URI_FILENAME,
9
+ InitializationError,
10
+ IOMode,
11
+ Request,
12
+ )
13
+
14
+
15
+ def imopen(
16
+ uri,
17
+ io_mode,
18
+ *,
19
+ plugin=None,
20
+ extension=None,
21
+ format_hint=None,
22
+ legacy_mode=False,
23
+ **kwargs,
24
+ ):
25
+ """Open an ImageResource.
26
+
27
+ .. warning::
28
+ This warning is for pypy users. If you are not using a context manager,
29
+ remember to deconstruct the returned plugin to avoid leaking the file
30
+ handle to an unclosed file.
31
+
32
+ Parameters
33
+ ----------
34
+ uri : str or pathlib.Path or bytes or file or Request
35
+ The :doc:`ImageResource <../../user_guide/requests>` to load the
36
+ image from.
37
+ io_mode : str
38
+ The mode in which the file is opened. Possible values are::
39
+
40
+ ``r`` - open the file for reading
41
+ ``w`` - open the file for writing
42
+
43
+ Depreciated since v2.9:
44
+ A second character can be added to give the reader a hint on what
45
+ the user expects. This will be ignored by new plugins and will
46
+ only have an effect on legacy plugins. Possible values are::
47
+
48
+ ``i`` for a single image,
49
+ ``I`` for multiple images,
50
+ ``v`` for a single volume,
51
+ ``V`` for multiple volumes,
52
+ ``?`` for don't care
53
+
54
+ plugin : str, Plugin, or None
55
+ The plugin to use. If set to None imopen will perform a
56
+ search for a matching plugin. If not None, this takes priority over
57
+ the provided format hint.
58
+ extension : str
59
+ If not None, treat the provided ImageResource as if it had the given
60
+ extension. This affects the order in which backends are considered, and
61
+ when writing this may also influence the format used when encoding.
62
+ format_hint : str
63
+ Deprecated. Use `extension` instead.
64
+ legacy_mode : bool
65
+ If true use the v2 behavior when searching for a suitable
66
+ plugin. This will ignore v3 plugins and will check ``plugin``
67
+ against known extensions if no plugin with the given name can be found.
68
+ **kwargs : Any
69
+ Additional keyword arguments will be passed to the plugin upon
70
+ construction.
71
+
72
+ Notes
73
+ -----
74
+ Registered plugins are controlled via the ``known_plugins`` dict in
75
+ ``imageio.config``.
76
+
77
+ Passing a ``Request`` as the uri is only supported if ``legacy_mode``
78
+ is ``True``. In this case ``io_mode`` is ignored.
79
+
80
+ Using the kwarg ``format_hint`` does not enforce the given format. It merely
81
+ provides a `hint` to the selection process and plugin. The selection
82
+ processes uses this hint for optimization; however, a plugin's decision how
83
+ to read a ImageResource will - typically - still be based on the content of
84
+ the resource.
85
+
86
+
87
+ Examples
88
+ --------
89
+
90
+ >>> import imageio.v3 as iio
91
+ >>> with iio.imopen("/path/to/image.png", "r") as file:
92
+ >>> im = file.read()
93
+
94
+ >>> with iio.imopen("/path/to/output.jpg", "w") as file:
95
+ >>> file.write(im)
96
+
97
+ """
98
+
99
+ if isinstance(uri, Request) and legacy_mode:
100
+ warnings.warn(
101
+ "`iio.core.Request` is a low-level object and using it"
102
+ " directly as input to `imopen` is discouraged. This will raise"
103
+ " an exception in ImageIO v3.",
104
+ DeprecationWarning,
105
+ stacklevel=2,
106
+ )
107
+
108
+ request = uri
109
+ uri = request.raw_uri
110
+ io_mode = request.mode.io_mode
111
+ request.format_hint = format_hint
112
+ else:
113
+ request = Request(uri, io_mode, format_hint=format_hint, extension=extension)
114
+
115
+ source = "<bytes>" if isinstance(uri, bytes) else uri
116
+
117
+ # fast-path based on plugin
118
+ # (except in legacy mode)
119
+ if plugin is not None:
120
+ if isinstance(plugin, str):
121
+ try:
122
+ config = known_plugins[plugin]
123
+ except KeyError:
124
+ request.finish()
125
+ raise ValueError(
126
+ f"`{plugin}` is not a registered plugin name."
127
+ ) from None
128
+
129
+ def loader(request, **kwargs):
130
+ return config.plugin_class(request, **kwargs)
131
+
132
+ else:
133
+
134
+ def loader(request, **kwargs):
135
+ return plugin(request, **kwargs)
136
+
137
+ try:
138
+ return loader(request, **kwargs)
139
+ except InitializationError as class_specific:
140
+ err_from = class_specific
141
+ err_type = RuntimeError if legacy_mode else IOError
142
+ err_msg = f"`{plugin}` can not handle the given uri."
143
+ except ImportError:
144
+ err_from = None
145
+ err_type = ImportError
146
+ err_msg = (
147
+ f"The `{config.name}` plugin is not installed. "
148
+ f"Use `pip install imageio[{config.install_name}]` to install it."
149
+ )
150
+ except Exception as generic_error:
151
+ err_from = generic_error
152
+ err_type = IOError
153
+ err_msg = f"An unknown error occurred while initializing plugin `{plugin}`."
154
+
155
+ request.finish()
156
+ raise err_type(err_msg) from err_from
157
+
158
+ # fast-path based on format_hint
159
+ if request.format_hint is not None:
160
+ for candidate_format in known_extensions[format_hint]:
161
+ for plugin_name in candidate_format.priority:
162
+ config = known_plugins[plugin_name]
163
+
164
+ try:
165
+ candidate_plugin = config.plugin_class
166
+ except ImportError:
167
+ # not installed
168
+ continue
169
+
170
+ try:
171
+ plugin_instance = candidate_plugin(request, **kwargs)
172
+ except InitializationError:
173
+ # file extension doesn't match file type
174
+ continue
175
+
176
+ return plugin_instance
177
+ else:
178
+ resource = (
179
+ "<bytes>" if isinstance(request.raw_uri, bytes) else request.raw_uri
180
+ )
181
+ warnings.warn(f"`{resource}` can not be opened as a `{format_hint}` file.")
182
+
183
+ # fast-path based on file extension
184
+ if request.extension in known_extensions:
185
+ for candidate_format in known_extensions[request.extension]:
186
+ for plugin_name in candidate_format.priority:
187
+ config = known_plugins[plugin_name]
188
+
189
+ try:
190
+ candidate_plugin = config.plugin_class
191
+ except ImportError:
192
+ # not installed
193
+ continue
194
+
195
+ try:
196
+ plugin_instance = candidate_plugin(request, **kwargs)
197
+ except InitializationError:
198
+ # file extension doesn't match file type
199
+ continue
200
+
201
+ return plugin_instance
202
+
203
+ # error out for read-only special targets
204
+ # this is hacky; can we come up with a better solution for this?
205
+ if request.mode.io_mode == IOMode.write:
206
+ if isinstance(uri, str) and uri.startswith(SPECIAL_READ_URIS):
207
+ request.finish()
208
+ err_type = ValueError if legacy_mode else IOError
209
+ err_msg = f"`{source}` is read-only."
210
+ raise err_type(err_msg)
211
+
212
+ # error out for directories
213
+ # this is a bit hacky and should be cleaned once we decide
214
+ # how to gracefully handle DICOM
215
+ if request._uri_type == URI_FILENAME and Path(request.raw_uri).is_dir():
216
+ request.finish()
217
+ err_type = ValueError if legacy_mode else IOError
218
+ err_msg = (
219
+ "ImageIO does not generally support reading folders. "
220
+ "Limited support may be available via specific plugins. "
221
+ "Specify the plugin explicitly using the `plugin` kwarg, e.g. `plugin='DICOM'`"
222
+ )
223
+ raise err_type(err_msg)
224
+
225
+ # close the current request here and use fresh/new ones while trying each
226
+ # plugin This is slow (means potentially reopening a resource several
227
+ # times), but should only happen rarely because this is the fallback if all
228
+ # else fails.
229
+ request.finish()
230
+
231
+ # fallback option: try all plugins
232
+ for config in known_plugins.values():
233
+ # each plugin gets its own request
234
+ request = Request(uri, io_mode, format_hint=format_hint)
235
+
236
+ try:
237
+ plugin_instance = config.plugin_class(request, **kwargs)
238
+ except InitializationError:
239
+ continue
240
+ except ImportError:
241
+ continue
242
+ else:
243
+ return plugin_instance
244
+
245
+ err_type = ValueError if legacy_mode else IOError
246
+ err_msg = f"Could not find a backend to open `{source}`` with iomode `{io_mode}`."
247
+
248
+ # check if a missing plugin could help
249
+ if request.extension in known_extensions:
250
+ missing_plugins = list()
251
+
252
+ formats = known_extensions[request.extension]
253
+ plugin_names = [
254
+ plugin for file_format in formats for plugin in file_format.priority
255
+ ]
256
+ for name in plugin_names:
257
+ config = known_plugins[name]
258
+
259
+ try:
260
+ config.plugin_class
261
+ continue
262
+ except ImportError:
263
+ missing_plugins.append(config)
264
+
265
+ if len(missing_plugins) > 0:
266
+ install_candidates = "\n".join(
267
+ [
268
+ (
269
+ f" {config.name}: "
270
+ f"pip install imageio[{config.install_name}]"
271
+ )
272
+ for config in missing_plugins
273
+ ]
274
+ )
275
+ err_msg += (
276
+ "\nBased on the extension, the following plugins might add capable backends:\n"
277
+ f"{install_candidates}"
278
+ )
279
+
280
+ request.finish()
281
+ raise err_type(err_msg)
evalkit_tf437/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from typing import Optional, Dict, Any, Union, List, Iterator
3
+
4
+ from .request import Request
5
+ from .v3_plugin_api import PluginV3, ImageProperties
6
+ from .format import Format
7
+ from ..typing import ArrayLike
8
+
9
+ class LegacyPlugin(PluginV3):
10
+ def __init__(self, request: Request, legacy_plugin: Format) -> None: ...
11
+ def legacy_get_reader(self, **kwargs) -> Format.Reader: ...
12
+ def read(self, *, index: Optional[int] = 0, **kwargs) -> np.ndarray: ...
13
+ def legacy_get_writer(self, **kwargs) -> Format.Writer: ...
14
+ def write(
15
+ self,
16
+ ndimage: Union[ArrayLike, List[ArrayLike]],
17
+ *,
18
+ is_batch: bool = None,
19
+ **kwargs
20
+ ) -> Optional[bytes]: ...
21
+ def iter(self, **kwargs) -> Iterator[np.ndarray]: ...
22
+ def properties(self, index: Optional[int] = 0) -> ImageProperties: ...
23
+ def get_meta(self, *, index: Optional[int] = 0) -> Dict[str, Any]: ...
24
+ def metadata(
25
+ self, index: Optional[int] = 0, exclude_applied: bool = True
26
+ ) -> Dict[str, Any]: ...
27
+ def __del__(self) -> None: ...
evalkit_tf437/lib/python3.10/site-packages/imageio/core/util.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """
5
+ Various utilities for imageio
6
+ """
7
+
8
+
9
+ from collections import OrderedDict
10
+ import numpy as np
11
+ import os
12
+ import re
13
+ import struct
14
+ import sys
15
+ import time
16
+ import logging
17
+
18
+
19
+ logger = logging.getLogger("imageio")
20
+
21
+ IS_PYPY = "__pypy__" in sys.builtin_module_names
22
+ THIS_DIR = os.path.abspath(os.path.dirname(__file__))
23
+
24
+
25
+ def urlopen(*args, **kwargs):
26
+ """Compatibility function for the urlopen function. Raises an
27
+ RuntimeError if urlopen could not be imported (which can occur in
28
+ frozen applications.
29
+ """
30
+ try:
31
+ from urllib.request import urlopen
32
+ except ImportError:
33
+ raise RuntimeError("Could not import urlopen.")
34
+ return urlopen(*args, **kwargs)
35
+
36
+
37
+ def _precision_warn(p1, p2, extra=""):
38
+ t = (
39
+ "Lossy conversion from {} to {}. {} Convert image to {} prior to "
40
+ "saving to suppress this warning."
41
+ )
42
+ logger.warning(t.format(p1, p2, extra, p2))
43
+
44
+
45
+ def image_as_uint(im, bitdepth=None):
46
+ """Convert the given image to uint (default: uint8)
47
+
48
+ If the dtype already matches the desired format, it is returned
49
+ as-is. If the image is float, and all values are between 0 and 1,
50
+ the values are multiplied by np.power(2.0, bitdepth). In all other
51
+ situations, the values are scaled such that the minimum value
52
+ becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1
53
+ (255 for 8-bit and 65535 for 16-bit).
54
+ """
55
+ if not bitdepth:
56
+ bitdepth = 8
57
+ if not isinstance(im, np.ndarray):
58
+ raise ValueError("Image must be a numpy array")
59
+ if bitdepth == 8:
60
+ out_type = np.uint8
61
+ elif bitdepth == 16:
62
+ out_type = np.uint16
63
+ else:
64
+ raise ValueError("Bitdepth must be either 8 or 16")
65
+ dtype_str1 = str(im.dtype)
66
+ dtype_str2 = out_type.__name__
67
+ if (im.dtype == np.uint8 and bitdepth == 8) or (
68
+ im.dtype == np.uint16 and bitdepth == 16
69
+ ):
70
+ # Already the correct format? Return as-is
71
+ return im
72
+ if dtype_str1.startswith("float") and np.nanmin(im) >= 0 and np.nanmax(im) <= 1:
73
+ _precision_warn(dtype_str1, dtype_str2, "Range [0, 1].")
74
+ im = im.astype(np.float64) * (np.power(2.0, bitdepth) - 1) + 0.499999999
75
+ elif im.dtype == np.uint16 and bitdepth == 8:
76
+ _precision_warn(dtype_str1, dtype_str2, "Losing 8 bits of resolution.")
77
+ im = np.right_shift(im, 8)
78
+ elif im.dtype == np.uint32:
79
+ _precision_warn(
80
+ dtype_str1,
81
+ dtype_str2,
82
+ "Losing {} bits of resolution.".format(32 - bitdepth),
83
+ )
84
+ im = np.right_shift(im, 32 - bitdepth)
85
+ elif im.dtype == np.uint64:
86
+ _precision_warn(
87
+ dtype_str1,
88
+ dtype_str2,
89
+ "Losing {} bits of resolution.".format(64 - bitdepth),
90
+ )
91
+ im = np.right_shift(im, 64 - bitdepth)
92
+ else:
93
+ mi = np.nanmin(im)
94
+ ma = np.nanmax(im)
95
+ if not np.isfinite(mi):
96
+ raise ValueError("Minimum image value is not finite")
97
+ if not np.isfinite(ma):
98
+ raise ValueError("Maximum image value is not finite")
99
+ if ma == mi:
100
+ return im.astype(out_type)
101
+ _precision_warn(dtype_str1, dtype_str2, "Range [{}, {}].".format(mi, ma))
102
+ # Now make float copy before we scale
103
+ im = im.astype("float64")
104
+ # Scale the values between 0 and 1 then multiply by the max value
105
+ im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth) - 1) + 0.499999999
106
+ assert np.nanmin(im) >= 0
107
+ assert np.nanmax(im) < np.power(2.0, bitdepth)
108
+ return im.astype(out_type)
109
+
110
+
111
+ class Array(np.ndarray):
112
+ """Array(array, meta=None)
113
+
114
+ A subclass of np.ndarray that has a meta attribute. Get the dictionary
115
+ that contains the meta data using ``im.meta``. Convert to a plain numpy
116
+ array using ``np.asarray(im)``.
117
+
118
+ """
119
+
120
+ def __new__(cls, array, meta=None):
121
+ # Check
122
+ if not isinstance(array, np.ndarray):
123
+ raise ValueError("Array expects a numpy array.")
124
+ if not (meta is None or isinstance(meta, dict)):
125
+ raise ValueError("Array expects meta data to be a dict.")
126
+ # Convert and return
127
+ meta = meta if meta is not None else getattr(array, "meta", {})
128
+ try:
129
+ ob = array.view(cls)
130
+ except AttributeError: # pragma: no cover
131
+ # Just return the original; no metadata on the array in Pypy!
132
+ return array
133
+ ob._copy_meta(meta)
134
+ return ob
135
+
136
+ def _copy_meta(self, meta):
137
+ """Make a 2-level deep copy of the meta dictionary."""
138
+ self._meta = Dict()
139
+ for key, val in meta.items():
140
+ if isinstance(val, dict):
141
+ val = Dict(val) # Copy this level
142
+ self._meta[key] = val
143
+
144
+ @property
145
+ def meta(self):
146
+ """The dict with the meta data of this image."""
147
+ return self._meta
148
+
149
+ def __array_finalize__(self, ob):
150
+ """So the meta info is maintained when doing calculations with
151
+ the array.
152
+ """
153
+ if isinstance(ob, Array):
154
+ self._copy_meta(ob.meta)
155
+ else:
156
+ self._copy_meta({})
157
+
158
+ def __array_wrap__(self, out, context=None):
159
+ """So that we return a native numpy array (or scalar) when a
160
+ reducting ufunc is applied (such as sum(), std(), etc.)
161
+ """
162
+ if not out.shape:
163
+ return out.dtype.type(out) # Scalar
164
+ elif out.shape != self.shape:
165
+ return out.view(type=np.ndarray)
166
+ elif not isinstance(out, Array):
167
+ return Array(out, self.meta)
168
+ else:
169
+ return out # Type Array
170
+
171
+
172
+ Image = Array # Alias for backwards compatibility
173
+
174
+
175
+ def asarray(a):
176
+ """Pypy-safe version of np.asarray. Pypy's np.asarray consumes a
177
+ *lot* of memory if the given array is an ndarray subclass. This
178
+ function does not.
179
+ """
180
+ if isinstance(a, np.ndarray):
181
+ if IS_PYPY: # pragma: no cover
182
+ a = a.copy() # pypy has issues with base views
183
+ plain = a.view(type=np.ndarray)
184
+ return plain
185
+ return np.asarray(a)
186
+
187
+
188
+ class Dict(OrderedDict):
189
+ """A dict in which the keys can be get and set as if they were
190
+ attributes. Very convenient in combination with autocompletion.
191
+
192
+ This Dict still behaves as much as possible as a normal dict, and
193
+ keys can be anything that are otherwise valid keys. However,
194
+ keys that are not valid identifiers or that are names of the dict
195
+ class (such as 'items' and 'copy') cannot be get/set as attributes.
196
+ """
197
+
198
+ __reserved_names__ = dir(OrderedDict()) # Also from OrderedDict
199
+ __pure_names__ = dir(dict())
200
+
201
+ def __getattribute__(self, key):
202
+ try:
203
+ return object.__getattribute__(self, key)
204
+ except AttributeError:
205
+ if key in self:
206
+ return self[key]
207
+ else:
208
+ raise
209
+
210
+ def __setattr__(self, key, val):
211
+ if key in Dict.__reserved_names__:
212
+ # Either let OrderedDict do its work, or disallow
213
+ if key not in Dict.__pure_names__:
214
+ return OrderedDict.__setattr__(self, key, val)
215
+ else:
216
+ raise AttributeError(
217
+ "Reserved name, this key can only "
218
+ + "be set via ``d[%r] = X``" % key
219
+ )
220
+ else:
221
+ # if isinstance(val, dict): val = Dict(val) -> no, makes a copy!
222
+ self[key] = val
223
+
224
+ def __dir__(self):
225
+ def isidentifier(x):
226
+ return bool(re.match(r"[a-z_]\w*$", x, re.I))
227
+
228
+ names = [k for k in self.keys() if (isinstance(k, str) and isidentifier(k))]
229
+ return Dict.__reserved_names__ + names
230
+
231
+
232
+ class BaseProgressIndicator(object):
233
+ """BaseProgressIndicator(name)
234
+
235
+ A progress indicator helps display the progress of a task to the
236
+ user. Progress can be pending, running, finished or failed.
237
+
238
+ Each task has:
239
+ * a name - a short description of what needs to be done.
240
+ * an action - the current action in performing the task (e.g. a subtask)
241
+ * progress - how far the task is completed
242
+ * max - max number of progress units. If 0, the progress is indefinite
243
+ * unit - the units in which the progress is counted
244
+ * status - 0: pending, 1: in progress, 2: finished, 3: failed
245
+
246
+ This class defines an abstract interface. Subclasses should implement
247
+ _start, _stop, _update_progress(progressText), _write(message).
248
+ """
249
+
250
+ def __init__(self, name):
251
+ self._name = name
252
+ self._action = ""
253
+ self._unit = ""
254
+ self._max = 0
255
+ self._status = 0
256
+ self._last_progress_update = 0
257
+
258
+ def start(self, action="", unit="", max=0):
259
+ """start(action='', unit='', max=0)
260
+
261
+ Start the progress. Optionally specify an action, a unit,
262
+ and a maximum progress value.
263
+ """
264
+ if self._status == 1:
265
+ self.finish()
266
+ self._action = action
267
+ self._unit = unit
268
+ self._max = max
269
+ #
270
+ self._progress = 0
271
+ self._status = 1
272
+ self._start()
273
+
274
+ def status(self):
275
+ """status()
276
+
277
+ Get the status of the progress - 0: pending, 1: in progress,
278
+ 2: finished, 3: failed
279
+ """
280
+ return self._status
281
+
282
+ def set_progress(self, progress=0, force=False):
283
+ """set_progress(progress=0, force=False)
284
+
285
+ Set the current progress. To avoid unnecessary progress updates
286
+ this will only have a visual effect if the time since the last
287
+ update is > 0.1 seconds, or if force is True.
288
+ """
289
+ self._progress = progress
290
+ # Update or not?
291
+ if not (force or (time.time() - self._last_progress_update > 0.1)):
292
+ return
293
+ self._last_progress_update = time.time()
294
+ # Compose new string
295
+ unit = self._unit or ""
296
+ progressText = ""
297
+ if unit == "%":
298
+ progressText = "%2.1f%%" % progress
299
+ elif self._max > 0:
300
+ percent = 100 * float(progress) / self._max
301
+ progressText = "%i/%i %s (%2.1f%%)" % (progress, self._max, unit, percent)
302
+ elif progress > 0:
303
+ if isinstance(progress, float):
304
+ progressText = "%0.4g %s" % (progress, unit)
305
+ else:
306
+ progressText = "%i %s" % (progress, unit)
307
+ # Update
308
+ self._update_progress(progressText)
309
+
310
+ def increase_progress(self, extra_progress):
311
+ """increase_progress(extra_progress)
312
+
313
+ Increase the progress by a certain amount.
314
+ """
315
+ self.set_progress(self._progress + extra_progress)
316
+
317
+ def finish(self, message=None):
318
+ """finish(message=None)
319
+
320
+ Finish the progress, optionally specifying a message. This will
321
+ not set the progress to the maximum.
322
+ """
323
+ self.set_progress(self._progress, True) # fore update
324
+ self._status = 2
325
+ self._stop()
326
+ if message is not None:
327
+ self._write(message)
328
+
329
+ def fail(self, message=None):
330
+ """fail(message=None)
331
+
332
+ Stop the progress with a failure, optionally specifying a message.
333
+ """
334
+ self.set_progress(self._progress, True) # fore update
335
+ self._status = 3
336
+ self._stop()
337
+ message = "FAIL " + (message or "")
338
+ self._write(message)
339
+
340
+ def write(self, message):
341
+ """write(message)
342
+
343
+ Write a message during progress (such as a warning).
344
+ """
345
+ if self.__class__ == BaseProgressIndicator:
346
+ # When this class is used as a dummy, print explicit message
347
+ print(message)
348
+ else:
349
+ return self._write(message)
350
+
351
+ # Implementing classes should implement these
352
+
353
+ def _start(self):
354
+ pass
355
+
356
+ def _stop(self):
357
+ pass
358
+
359
+ def _update_progress(self, progressText):
360
+ pass
361
+
362
+ def _write(self, message):
363
+ pass
364
+
365
+
366
+ class StdoutProgressIndicator(BaseProgressIndicator):
367
+ """StdoutProgressIndicator(name)
368
+
369
+ A progress indicator that shows the progress in stdout. It
370
+ assumes that the tty can appropriately deal with backspace
371
+ characters.
372
+ """
373
+
374
+ def _start(self):
375
+ self._chars_prefix, self._chars = "", ""
376
+ # Write message
377
+ if self._action:
378
+ self._chars_prefix = "%s (%s): " % (self._name, self._action)
379
+ else:
380
+ self._chars_prefix = "%s: " % self._name
381
+ sys.stdout.write(self._chars_prefix)
382
+ sys.stdout.flush()
383
+
384
+ def _update_progress(self, progressText):
385
+ # If progress is unknown, at least make something move
386
+ if not progressText:
387
+ i1, i2, i3, i4 = "-\\|/"
388
+ M = {i1: i2, i2: i3, i3: i4, i4: i1}
389
+ progressText = M.get(self._chars, i1)
390
+ # Store new string and write
391
+ delChars = "\b" * len(self._chars)
392
+ self._chars = progressText
393
+ sys.stdout.write(delChars + self._chars)
394
+ sys.stdout.flush()
395
+
396
+ def _stop(self):
397
+ self._chars = self._chars_prefix = ""
398
+ sys.stdout.write("\n")
399
+ sys.stdout.flush()
400
+
401
+ def _write(self, message):
402
+ # Write message
403
+ delChars = "\b" * len(self._chars_prefix + self._chars)
404
+ sys.stdout.write(delChars + " " + message + "\n")
405
+ # Reprint progress text
406
+ sys.stdout.write(self._chars_prefix + self._chars)
407
+ sys.stdout.flush()
408
+
409
+
410
+ # From pyzolib/paths.py (https://bitbucket.org/pyzo/pyzolib/src/tip/paths.py)
411
+ def appdata_dir(appname=None, roaming=False):
412
+ """appdata_dir(appname=None, roaming=False)
413
+
414
+ Get the path to the application directory, where applications are allowed
415
+ to write user specific files (e.g. configurations). For non-user specific
416
+ data, consider using common_appdata_dir().
417
+ If appname is given, a subdir is appended (and created if necessary).
418
+ If roaming is True, will prefer a roaming directory (Windows Vista/7).
419
+ """
420
+
421
+ # Define default user directory
422
+ userDir = os.getenv("IMAGEIO_USERDIR", None)
423
+ if userDir is None:
424
+ userDir = os.path.expanduser("~")
425
+ if not os.path.isdir(userDir): # pragma: no cover
426
+ userDir = "/var/tmp" # issue #54
427
+
428
+ # Get system app data dir
429
+ path = None
430
+ if sys.platform.startswith("win"):
431
+ path1, path2 = os.getenv("LOCALAPPDATA"), os.getenv("APPDATA")
432
+ path = (path2 or path1) if roaming else (path1 or path2)
433
+ elif sys.platform.startswith("darwin"):
434
+ path = os.path.join(userDir, "Library", "Application Support")
435
+ # On Linux and as fallback
436
+ if not (path and os.path.isdir(path)):
437
+ path = userDir
438
+
439
+ # Maybe we should store things local to the executable (in case of a
440
+ # portable distro or a frozen application that wants to be portable)
441
+ prefix = sys.prefix
442
+ if getattr(sys, "frozen", None):
443
+ prefix = os.path.abspath(os.path.dirname(sys.executable))
444
+ for reldir in ("settings", "../settings"):
445
+ localpath = os.path.abspath(os.path.join(prefix, reldir))
446
+ if os.path.isdir(localpath): # pragma: no cover
447
+ try:
448
+ open(os.path.join(localpath, "test.write"), "wb").close()
449
+ os.remove(os.path.join(localpath, "test.write"))
450
+ except IOError:
451
+ pass # We cannot write in this directory
452
+ else:
453
+ path = localpath
454
+ break
455
+
456
+ # Get path specific for this app
457
+ if appname:
458
+ if path == userDir:
459
+ appname = "." + appname.lstrip(".") # Make it a hidden directory
460
+ path = os.path.join(path, appname)
461
+ if not os.path.isdir(path): # pragma: no cover
462
+ os.makedirs(path, exist_ok=True)
463
+
464
+ # Done
465
+ return path
466
+
467
+
468
+ def resource_dirs():
469
+ """resource_dirs()
470
+
471
+ Get a list of directories where imageio resources may be located.
472
+ The first directory in this list is the "resources" directory in
473
+ the package itself. The second directory is the appdata directory
474
+ (~/.imageio on Linux). The list further contains the application
475
+ directory (for frozen apps), and may include additional directories
476
+ in the future.
477
+ """
478
+ dirs = [resource_package_dir()]
479
+ # Resource dir baked in the package.
480
+ # Appdata directory
481
+ try:
482
+ dirs.append(appdata_dir("imageio"))
483
+ except Exception: # pragma: no cover
484
+ pass # The home dir may not be writable
485
+ # Directory where the app is located (mainly for frozen apps)
486
+ if getattr(sys, "frozen", None):
487
+ dirs.append(os.path.abspath(os.path.dirname(sys.executable)))
488
+ elif sys.path and sys.path[0]:
489
+ dirs.append(os.path.abspath(sys.path[0]))
490
+ return dirs
491
+
492
+
493
+ def resource_package_dir():
494
+ """package_dir
495
+
496
+ Get the resources directory in the imageio package installation
497
+ directory.
498
+
499
+ Notes
500
+ -----
501
+ This is a convenience method that is used by `resource_dirs` and
502
+ imageio entry point scripts.
503
+ """
504
+ # Make pkg_resources optional if setuptools is not available
505
+ try:
506
+ # Avoid importing pkg_resources in the top level due to how slow it is
507
+ # https://github.com/pypa/setuptools/issues/510
508
+ import pkg_resources
509
+ except ImportError:
510
+ pkg_resources = None
511
+
512
+ if pkg_resources:
513
+ # The directory returned by `pkg_resources.resource_filename`
514
+ # also works with eggs.
515
+ pdir = pkg_resources.resource_filename("imageio", "resources")
516
+ else:
517
+ # If setuptools is not available, use fallback
518
+ pdir = os.path.abspath(os.path.join(THIS_DIR, "..", "resources"))
519
+ return pdir
520
+
521
+
522
+ def get_platform():
523
+ """get_platform()
524
+
525
+ Get a string that specifies the platform more specific than
526
+ sys.platform does. The result can be: linux32, linux64, win32,
527
+ win64, osx32, osx64. Other platforms may be added in the future.
528
+ """
529
+ # Get platform
530
+ if sys.platform.startswith("linux"):
531
+ plat = "linux%i"
532
+ elif sys.platform.startswith("win"):
533
+ plat = "win%i"
534
+ elif sys.platform.startswith("darwin"):
535
+ plat = "osx%i"
536
+ elif sys.platform.startswith("freebsd"):
537
+ plat = "freebsd%i"
538
+ else: # pragma: no cover
539
+ return None
540
+
541
+ return plat % (struct.calcsize("P") * 8) # 32 or 64 bits
542
+
543
+
544
+ def has_module(module_name):
545
+ """Check to see if a python module is available."""
546
+ if sys.version_info > (3, 4):
547
+ import importlib
548
+
549
+ name_parts = module_name.split(".")
550
+ for i in range(len(name_parts)):
551
+ if importlib.util.find_spec(".".join(name_parts[: i + 1])) is None:
552
+ return False
553
+ return True
554
+ else: # pragma: no cover
555
+ import imp
556
+
557
+ try:
558
+ imp.find_module(module_name)
559
+ except ImportError:
560
+ return False
561
+ return True
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc ADDED
Binary file (23.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_freeimage.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc ADDED
Binary file (20.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/ffmpeg.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc ADDED
Binary file (4.73 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimage.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/gdal.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/grab.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/lytro.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/opencv.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow.cpython-310.pyc ADDED
Binary file (18.5 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_info.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_legacy.cpython-310.pyc ADDED
Binary file (23.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/rawpy.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/spe.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/swf.cpython-310.pyc ADDED
Binary file (8.68 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile_v3.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/_dicom.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Plugin for reading DICOM files.
5
+ """
6
+
7
+ # todo: Use pydicom:
8
+ # * Note: is not py3k ready yet
9
+ # * Allow reading the full meta info
10
+ # I think we can more or less replace the SimpleDicomReader with a
11
+ # pydicom.Dataset For series, only ned to read the full info from one
12
+ # file: speed still high
13
+ # * Perhaps allow writing?
14
+
15
+ import sys
16
+ import os
17
+ import struct
18
+ import logging
19
+
20
+ import numpy as np
21
+
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Determine endianity of system
26
+ sys_is_little_endian = sys.byteorder == "little"
27
+
28
+ # Define a dictionary that contains the tags that we would like to know
29
+ MINIDICT = {
30
+ (0x7FE0, 0x0010): ("PixelData", "OB"),
31
+ # Date and time
32
+ (0x0008, 0x0020): ("StudyDate", "DA"),
33
+ (0x0008, 0x0021): ("SeriesDate", "DA"),
34
+ (0x0008, 0x0022): ("AcquisitionDate", "DA"),
35
+ (0x0008, 0x0023): ("ContentDate", "DA"),
36
+ (0x0008, 0x0030): ("StudyTime", "TM"),
37
+ (0x0008, 0x0031): ("SeriesTime", "TM"),
38
+ (0x0008, 0x0032): ("AcquisitionTime", "TM"),
39
+ (0x0008, 0x0033): ("ContentTime", "TM"),
40
+ # With what, where, by whom?
41
+ (0x0008, 0x0060): ("Modality", "CS"),
42
+ (0x0008, 0x0070): ("Manufacturer", "LO"),
43
+ (0x0008, 0x0080): ("InstitutionName", "LO"),
44
+ # Descriptions
45
+ (0x0008, 0x1030): ("StudyDescription", "LO"),
46
+ (0x0008, 0x103E): ("SeriesDescription", "LO"),
47
+ # UID's
48
+ (0x0008, 0x0016): ("SOPClassUID", "UI"),
49
+ (0x0008, 0x0018): ("SOPInstanceUID", "UI"),
50
+ (0x0020, 0x000D): ("StudyInstanceUID", "UI"),
51
+ (0x0020, 0x000E): ("SeriesInstanceUID", "UI"),
52
+ (0x0008, 0x0117): ("ContextUID", "UI"),
53
+ # Numbers
54
+ (0x0020, 0x0011): ("SeriesNumber", "IS"),
55
+ (0x0020, 0x0012): ("AcquisitionNumber", "IS"),
56
+ (0x0020, 0x0013): ("InstanceNumber", "IS"),
57
+ (0x0020, 0x0014): ("IsotopeNumber", "IS"),
58
+ (0x0020, 0x0015): ("PhaseNumber", "IS"),
59
+ (0x0020, 0x0016): ("IntervalNumber", "IS"),
60
+ (0x0020, 0x0017): ("TimeSlotNumber", "IS"),
61
+ (0x0020, 0x0018): ("AngleNumber", "IS"),
62
+ (0x0020, 0x0019): ("ItemNumber", "IS"),
63
+ (0x0020, 0x0020): ("PatientOrientation", "CS"),
64
+ (0x0020, 0x0030): ("ImagePosition", "CS"),
65
+ (0x0020, 0x0032): ("ImagePositionPatient", "CS"),
66
+ (0x0020, 0x0035): ("ImageOrientation", "CS"),
67
+ (0x0020, 0x0037): ("ImageOrientationPatient", "CS"),
68
+ # Patient information
69
+ (0x0010, 0x0010): ("PatientName", "PN"),
70
+ (0x0010, 0x0020): ("PatientID", "LO"),
71
+ (0x0010, 0x0030): ("PatientBirthDate", "DA"),
72
+ (0x0010, 0x0040): ("PatientSex", "CS"),
73
+ (0x0010, 0x1010): ("PatientAge", "AS"),
74
+ (0x0010, 0x1020): ("PatientSize", "DS"),
75
+ (0x0010, 0x1030): ("PatientWeight", "DS"),
76
+ # Image specific (required to construct numpy array)
77
+ (0x0028, 0x0002): ("SamplesPerPixel", "US"),
78
+ (0x0028, 0x0008): ("NumberOfFrames", "IS"),
79
+ (0x0028, 0x0100): ("BitsAllocated", "US"),
80
+ (0x0028, 0x0101): ("BitsStored", "US"),
81
+ (0x0028, 0x0102): ("HighBit", "US"),
82
+ (0x0028, 0x0103): ("PixelRepresentation", "US"),
83
+ (0x0028, 0x0010): ("Rows", "US"),
84
+ (0x0028, 0x0011): ("Columns", "US"),
85
+ (0x0028, 0x1052): ("RescaleIntercept", "DS"),
86
+ (0x0028, 0x1053): ("RescaleSlope", "DS"),
87
+ # Image specific (for the user)
88
+ (0x0028, 0x0030): ("PixelSpacing", "DS"),
89
+ (0x0018, 0x0088): ("SliceSpacing", "DS"),
90
+ }
91
+
92
+ # Define some special tags:
93
+ # See PS 3.5-2008 section 7.5 (p.40)
94
+ ItemTag = (0xFFFE, 0xE000) # start of Sequence Item
95
+ ItemDelimiterTag = (0xFFFE, 0xE00D) # end of Sequence Item
96
+ SequenceDelimiterTag = (0xFFFE, 0xE0DD) # end of Sequence of undefined length
97
+
98
+ # Define set of groups that we're interested in (so we can quickly skip others)
99
+ GROUPS = set([key[0] for key in MINIDICT.keys()])
100
+ VRS = set([val[1] for val in MINIDICT.values()])
101
+
102
+
103
+ class NotADicomFile(Exception):
104
+ pass
105
+
106
+
107
+ class CompressedDicom(RuntimeError):
108
+ pass
109
+
110
+
111
+ class SimpleDicomReader(object):
112
+ """
113
+ This class provides reading of pixel data from DICOM files. It is
114
+ focussed on getting the pixel data, not the meta info.
115
+
116
+ To use, first create an instance of this class (giving it
117
+ a file object or filename). Next use the info attribute to
118
+ get a dict of the meta data. The loading of pixel data is
119
+ deferred until get_numpy_array() is called.
120
+
121
+ Comparison with Pydicom
122
+ -----------------------
123
+
124
+ This code focusses on getting the pixel data out, which allows some
125
+ shortcuts, resulting in the code being much smaller.
126
+
127
+ Since the processing of data elements is much cheaper (it skips a lot
128
+ of tags), this code is about 3x faster than pydicom (except for the
129
+ deflated DICOM files).
130
+
131
+ This class does borrow some code (and ideas) from the pydicom
132
+ project, and (to the best of our knowledge) has the same limitations
133
+ as pydicom with regard to the type of files that it can handle.
134
+
135
+ Limitations
136
+ -----------
137
+
138
+ For more advanced DICOM processing, please check out pydicom.
139
+
140
+ * Only a predefined subset of data elements (meta information) is read.
141
+ * This is a reader; it can not write DICOM files.
142
+ * (just like pydicom) it can handle none of the compressed DICOM
143
+ formats except for "Deflated Explicit VR Little Endian"
144
+ (1.2.840.10008.1.2.1.99).
145
+
146
+ """
147
+
148
+ def __init__(self, file):
149
+ # Open file if filename given
150
+ if isinstance(file, str):
151
+ self._filename = file
152
+ self._file = open(file, "rb")
153
+ else:
154
+ self._filename = "<unknown file>"
155
+ self._file = file
156
+ # Init variable to store position and size of pixel data
157
+ self._pixel_data_loc = None
158
+ # The meta header is always explicit and little endian
159
+ self.is_implicit_VR = False
160
+ self.is_little_endian = True
161
+ self._unpackPrefix = "<"
162
+ # Dict to store data elements of interest in
163
+ self._info = {}
164
+ # VR Conversion
165
+ self._converters = {
166
+ # Numbers
167
+ "US": lambda x: self._unpack("H", x),
168
+ "UL": lambda x: self._unpack("L", x),
169
+ # Numbers encoded as strings
170
+ "DS": lambda x: self._splitValues(x, float, "\\"),
171
+ "IS": lambda x: self._splitValues(x, int, "\\"),
172
+ # strings
173
+ "AS": lambda x: x.decode("ascii", "ignore").strip("\x00"),
174
+ "DA": lambda x: x.decode("ascii", "ignore").strip("\x00"),
175
+ "TM": lambda x: x.decode("ascii", "ignore").strip("\x00"),
176
+ "UI": lambda x: x.decode("ascii", "ignore").strip("\x00"),
177
+ "LO": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
178
+ "CS": lambda x: self._splitValues(x, float, "\\"),
179
+ "PN": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
180
+ }
181
+
182
+ # Initiate reading
183
+ self._read()
184
+
185
+ @property
186
+ def info(self):
187
+ return self._info
188
+
189
+ def _splitValues(self, x, type, splitter):
190
+ s = x.decode("ascii").strip("\x00")
191
+ try:
192
+ if splitter in s:
193
+ return tuple([type(v) for v in s.split(splitter) if v.strip()])
194
+ else:
195
+ return type(s)
196
+ except ValueError:
197
+ return s
198
+
199
+ def _unpack(self, fmt, value):
200
+ return struct.unpack(self._unpackPrefix + fmt, value)[0]
201
+
202
+ # Really only so we need minimal changes to _pixel_data_numpy
203
+ def __iter__(self):
204
+ return iter(self._info.keys())
205
+
206
+ def __getattr__(self, key):
207
+ info = object.__getattribute__(self, "_info")
208
+ if key in info:
209
+ return info[key]
210
+ return object.__getattribute__(self, key) # pragma: no cover
211
+
212
+ def _read(self):
213
+ f = self._file
214
+ # Check prefix after peamble
215
+ f.seek(128)
216
+ if f.read(4) != b"DICM":
217
+ raise NotADicomFile("Not a valid DICOM file.")
218
+ # Read
219
+ self._read_header()
220
+ self._read_data_elements()
221
+ self._get_shape_and_sampling()
222
+ # Close if done, reopen if necessary to read pixel data
223
+ if os.path.isfile(self._filename):
224
+ self._file.close()
225
+ self._file = None
226
+
227
+ def _readDataElement(self):
228
+ f = self._file
229
+ # Get group and element
230
+ group = self._unpack("H", f.read(2))
231
+ element = self._unpack("H", f.read(2))
232
+ # Get value length
233
+ if self.is_implicit_VR:
234
+ vl = self._unpack("I", f.read(4))
235
+ else:
236
+ vr = f.read(2)
237
+ if vr in (b"OB", b"OW", b"SQ", b"UN"):
238
+ reserved = f.read(2) # noqa
239
+ vl = self._unpack("I", f.read(4))
240
+ else:
241
+ vl = self._unpack("H", f.read(2))
242
+ # Get value
243
+ if group == 0x7FE0 and element == 0x0010:
244
+ here = f.tell()
245
+ self._pixel_data_loc = here, vl
246
+ f.seek(here + vl)
247
+ return group, element, b"Deferred loading of pixel data"
248
+ else:
249
+ if vl == 0xFFFFFFFF:
250
+ value = self._read_undefined_length_value()
251
+ else:
252
+ value = f.read(vl)
253
+ return group, element, value
254
+
255
+ def _read_undefined_length_value(self, read_size=128):
256
+ """Copied (in compacted form) from PyDicom
257
+ Copyright Darcy Mason.
258
+ """
259
+ fp = self._file
260
+ # data_start = fp.tell()
261
+ search_rewind = 3
262
+ bytes_to_find = struct.pack(
263
+ self._unpackPrefix + "HH", SequenceDelimiterTag[0], SequenceDelimiterTag[1]
264
+ )
265
+
266
+ found = False
267
+ value_chunks = []
268
+ while not found:
269
+ chunk_start = fp.tell()
270
+ bytes_read = fp.read(read_size)
271
+ if len(bytes_read) < read_size:
272
+ # try again,
273
+ # if still don't get required amount, this is last block
274
+ new_bytes = fp.read(read_size - len(bytes_read))
275
+ bytes_read += new_bytes
276
+ if len(bytes_read) < read_size:
277
+ raise EOFError(
278
+ "End of file reached before sequence " "delimiter found."
279
+ )
280
+ index = bytes_read.find(bytes_to_find)
281
+ if index != -1:
282
+ found = True
283
+ value_chunks.append(bytes_read[:index])
284
+ fp.seek(chunk_start + index + 4) # rewind to end of delimiter
285
+ length = fp.read(4)
286
+ if length != b"\0\0\0\0":
287
+ logger.warning(
288
+ "Expected 4 zero bytes after undefined length " "delimiter"
289
+ )
290
+ else:
291
+ fp.seek(fp.tell() - search_rewind) # rewind a bit
292
+ # accumulate the bytes read (not including the rewind)
293
+ value_chunks.append(bytes_read[:-search_rewind])
294
+
295
+ # if get here then have found the byte string
296
+ return b"".join(value_chunks)
297
+
298
+ def _read_header(self):
299
+ f = self._file
300
+ TransferSyntaxUID = None
301
+
302
+ # Read all elements, store transferSyntax when we encounter it
303
+ try:
304
+ while True:
305
+ fp_save = f.tell()
306
+ # Get element
307
+ group, element, value = self._readDataElement()
308
+ if group == 0x02:
309
+ if group == 0x02 and element == 0x10:
310
+ TransferSyntaxUID = value.decode("ascii").strip("\x00")
311
+ else:
312
+ # No more group 2: rewind and break
313
+ # (don't trust group length)
314
+ f.seek(fp_save)
315
+ break
316
+ except (EOFError, struct.error): # pragma: no cover
317
+ raise RuntimeError("End of file reached while still in header.")
318
+
319
+ # Handle transfer syntax
320
+ self._info["TransferSyntaxUID"] = TransferSyntaxUID
321
+ #
322
+ if TransferSyntaxUID is None:
323
+ # Assume ExplicitVRLittleEndian
324
+ is_implicit_VR, is_little_endian = False, True
325
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.1":
326
+ # ExplicitVRLittleEndian
327
+ is_implicit_VR, is_little_endian = False, True
328
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.2":
329
+ # ExplicitVRBigEndian
330
+ is_implicit_VR, is_little_endian = False, False
331
+ elif TransferSyntaxUID == "1.2.840.10008.1.2":
332
+ # implicit VR little endian
333
+ is_implicit_VR, is_little_endian = True, True
334
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.1.99":
335
+ # DeflatedExplicitVRLittleEndian:
336
+ is_implicit_VR, is_little_endian = False, True
337
+ self._inflate()
338
+ else:
339
+ # http://www.dicomlibrary.com/dicom/transfer-syntax/
340
+ t, extra_info = TransferSyntaxUID, ""
341
+ if "1.2.840.10008.1.2.4.50" <= t < "1.2.840.10008.1.2.4.99":
342
+ extra_info = " (JPEG)"
343
+ if "1.2.840.10008.1.2.4.90" <= t < "1.2.840.10008.1.2.4.99":
344
+ extra_info = " (JPEG 2000)"
345
+ if t == "1.2.840.10008.1.2.5":
346
+ extra_info = " (RLE)"
347
+ if t == "1.2.840.10008.1.2.6.1":
348
+ extra_info = " (RFC 2557)"
349
+ raise CompressedDicom(
350
+ "The dicom reader can only read files with "
351
+ "uncompressed image data - not %r%s. You "
352
+ "can try using dcmtk or gdcm to convert the "
353
+ "image." % (t, extra_info)
354
+ )
355
+
356
+ # From hereon, use implicit/explicit big/little endian
357
+ self.is_implicit_VR = is_implicit_VR
358
+ self.is_little_endian = is_little_endian
359
+ self._unpackPrefix = "><"[is_little_endian]
360
+
361
+ def _read_data_elements(self):
362
+ info = self._info
363
+ try:
364
+ while True:
365
+ # Get element
366
+ group, element, value = self._readDataElement()
367
+ # Is it a group we are interested in?
368
+ if group in GROUPS:
369
+ key = (group, element)
370
+ name, vr = MINIDICT.get(key, (None, None))
371
+ # Is it an element we are interested in?
372
+ if name:
373
+ # Store value
374
+ converter = self._converters.get(vr, lambda x: x)
375
+ info[name] = converter(value)
376
+ except (EOFError, struct.error):
377
+ pass # end of file ...
378
+
379
+ def get_numpy_array(self):
380
+ """Get numpy arra for this DICOM file, with the correct shape,
381
+ and pixel values scaled appropriately.
382
+ """
383
+ # Is there pixel data at all?
384
+ if "PixelData" not in self:
385
+ raise TypeError("No pixel data found in this dataset.")
386
+
387
+ # Load it now if it was not already loaded
388
+ if self._pixel_data_loc and len(self.PixelData) < 100:
389
+ # Reopen file?
390
+ close_file = False
391
+ if self._file is None:
392
+ close_file = True
393
+ self._file = open(self._filename, "rb")
394
+ # Read data
395
+ self._file.seek(self._pixel_data_loc[0])
396
+ if self._pixel_data_loc[1] == 0xFFFFFFFF:
397
+ value = self._read_undefined_length_value()
398
+ else:
399
+ value = self._file.read(self._pixel_data_loc[1])
400
+ # Close file
401
+ if close_file:
402
+ self._file.close()
403
+ self._file = None
404
+ # Overwrite
405
+ self._info["PixelData"] = value
406
+
407
+ # Get data
408
+ data = self._pixel_data_numpy()
409
+ data = self._apply_slope_and_offset(data)
410
+
411
+ # Remove data again to preserve memory
412
+ # Note that the data for the original file is loaded twice ...
413
+ self._info["PixelData"] = (
414
+ b"Data converted to numpy array, " + b"raw data removed to preserve memory"
415
+ )
416
+ return data
417
+
418
+ def _get_shape_and_sampling(self):
419
+ """Get shape and sampling without actuall using the pixel data.
420
+ In this way, the user can get an idea what's inside without having
421
+ to load it.
422
+ """
423
+ # Get shape (in the same way that pydicom does)
424
+ if "NumberOfFrames" in self and self.NumberOfFrames > 1:
425
+ if self.SamplesPerPixel > 1:
426
+ shape = (
427
+ self.SamplesPerPixel,
428
+ self.NumberOfFrames,
429
+ self.Rows,
430
+ self.Columns,
431
+ )
432
+ else:
433
+ shape = self.NumberOfFrames, self.Rows, self.Columns
434
+ elif "SamplesPerPixel" in self:
435
+ if self.SamplesPerPixel > 1:
436
+ if self.BitsAllocated == 8:
437
+ shape = self.SamplesPerPixel, self.Rows, self.Columns
438
+ else:
439
+ raise NotImplementedError(
440
+ "DICOM plugin only handles "
441
+ "SamplesPerPixel > 1 if Bits "
442
+ "Allocated = 8"
443
+ )
444
+ else:
445
+ shape = self.Rows, self.Columns
446
+ else:
447
+ raise RuntimeError(
448
+ "DICOM file has no SamplesPerPixel " "(perhaps this is a report?)"
449
+ )
450
+
451
+ # Try getting sampling between pixels
452
+ if "PixelSpacing" in self:
453
+ sampling = float(self.PixelSpacing[0]), float(self.PixelSpacing[1])
454
+ else:
455
+ sampling = 1.0, 1.0
456
+ if "SliceSpacing" in self:
457
+ sampling = (abs(self.SliceSpacing),) + sampling
458
+
459
+ # Ensure that sampling has as many elements as shape
460
+ sampling = (1.0,) * (len(shape) - len(sampling)) + sampling[-len(shape) :]
461
+
462
+ # Set shape and sampling
463
+ self._info["shape"] = shape
464
+ self._info["sampling"] = sampling
465
+
466
+ def _pixel_data_numpy(self):
467
+ """Return a NumPy array of the pixel data."""
468
+ # Taken from pydicom
469
+ # Copyright (c) 2008-2012 Darcy Mason
470
+
471
+ if "PixelData" not in self:
472
+ raise TypeError("No pixel data found in this dataset.")
473
+
474
+ # determine the type used for the array
475
+ need_byteswap = self.is_little_endian != sys_is_little_endian
476
+
477
+ # Make NumPy format code, e.g. "uint16", "int32" etc
478
+ # from two pieces of info:
479
+ # self.PixelRepresentation -- 0 for unsigned, 1 for signed;
480
+ # self.BitsAllocated -- 8, 16, or 32
481
+ format_str = "%sint%d" % (
482
+ ("u", "")[self.PixelRepresentation],
483
+ self.BitsAllocated,
484
+ )
485
+ try:
486
+ numpy_format = np.dtype(format_str)
487
+ except TypeError: # pragma: no cover
488
+ raise TypeError(
489
+ "Data type not understood by NumPy: format='%s', "
490
+ " PixelRepresentation=%d, BitsAllocated=%d"
491
+ % (numpy_format, self.PixelRepresentation, self.BitsAllocated)
492
+ )
493
+
494
+ # Have correct Numpy format, so create the NumPy array
495
+ arr = np.frombuffer(self.PixelData, numpy_format).copy()
496
+
497
+ # XXX byte swap - may later handle this in read_file!!?
498
+ if need_byteswap:
499
+ arr.byteswap(True) # True means swap in-place, don't make new copy
500
+
501
+ # Note the following reshape operations return a new *view* onto arr,
502
+ # but don't copy the data
503
+ arr = arr.reshape(*self._info["shape"])
504
+ return arr
505
+
506
+ def _apply_slope_and_offset(self, data):
507
+ """
508
+ If RescaleSlope and RescaleIntercept are present in the data,
509
+ apply them. The data type of the data is changed if necessary.
510
+ """
511
+ # Obtain slope and offset
512
+ slope, offset = 1, 0
513
+ needFloats, needApplySlopeOffset = False, False
514
+ if "RescaleSlope" in self:
515
+ needApplySlopeOffset = True
516
+ slope = self.RescaleSlope
517
+ if "RescaleIntercept" in self:
518
+ needApplySlopeOffset = True
519
+ offset = self.RescaleIntercept
520
+ if int(slope) != slope or int(offset) != offset:
521
+ needFloats = True
522
+ if not needFloats:
523
+ slope, offset = int(slope), int(offset)
524
+
525
+ # Apply slope and offset
526
+ if needApplySlopeOffset:
527
+ # Maybe we need to change the datatype?
528
+ if data.dtype in [np.float32, np.float64]:
529
+ pass
530
+ elif needFloats:
531
+ data = data.astype(np.float32)
532
+ else:
533
+ # Determine required range
534
+ minReq, maxReq = data.min().item(), data.max().item()
535
+ minReq = min([minReq, minReq * slope + offset, maxReq * slope + offset])
536
+ maxReq = max([maxReq, minReq * slope + offset, maxReq * slope + offset])
537
+
538
+ # Determine required datatype from that
539
+ dtype = None
540
+ if minReq < 0:
541
+ # Signed integer type
542
+ maxReq = max([-minReq, maxReq])
543
+ if maxReq < 2**7:
544
+ dtype = np.int8
545
+ elif maxReq < 2**15:
546
+ dtype = np.int16
547
+ elif maxReq < 2**31:
548
+ dtype = np.int32
549
+ else:
550
+ dtype = np.float32
551
+ else:
552
+ # Unsigned integer type
553
+ if maxReq < 2**8:
554
+ dtype = np.int8
555
+ elif maxReq < 2**16:
556
+ dtype = np.int16
557
+ elif maxReq < 2**32:
558
+ dtype = np.int32
559
+ else:
560
+ dtype = np.float32
561
+ # Change datatype
562
+ if dtype != data.dtype:
563
+ data = data.astype(dtype)
564
+
565
+ # Apply slope and offset
566
+ data *= slope
567
+ data += offset
568
+
569
+ # Done
570
+ return data
571
+
572
+ def _inflate(self):
573
+ # Taken from pydicom
574
+ # Copyright (c) 2008-2012 Darcy Mason
575
+ import zlib
576
+ from io import BytesIO
577
+
578
+ # See PS3.6-2008 A.5 (p 71) -- when written, the entire dataset
579
+ # following the file metadata was prepared the normal way,
580
+ # then "deflate" compression applied.
581
+ # All that is needed here is to decompress and then
582
+ # use as normal in a file-like object
583
+ zipped = self._file.read()
584
+ # -MAX_WBITS part is from comp.lang.python answer:
585
+ # groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799
586
+ unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)
587
+ self._file = BytesIO(unzipped) # a file-like object
588
+
589
+
590
+ class DicomSeries(object):
591
+ """DicomSeries
592
+ This class represents a serie of dicom files (SimpleDicomReader
593
+ objects) that belong together. If these are multiple files, they
594
+ represent the slices of a volume (like for CT or MRI).
595
+ """
596
+
597
+ def __init__(self, suid, progressIndicator):
598
+ # Init dataset list and the callback
599
+ self._entries = []
600
+
601
+ # Init props
602
+ self._suid = suid
603
+ self._info = {}
604
+ self._progressIndicator = progressIndicator
605
+
606
+ def __len__(self):
607
+ return len(self._entries)
608
+
609
+ def __iter__(self):
610
+ return iter(self._entries)
611
+
612
+ def __getitem__(self, index):
613
+ return self._entries[index]
614
+
615
+ @property
616
+ def suid(self):
617
+ return self._suid
618
+
619
+ @property
620
+ def shape(self):
621
+ """The shape of the data (nz, ny, nx)."""
622
+ return self._info["shape"]
623
+
624
+ @property
625
+ def sampling(self):
626
+ """The sampling (voxel distances) of the data (dz, dy, dx)."""
627
+ return self._info["sampling"]
628
+
629
+ @property
630
+ def info(self):
631
+ """A dictionary containing the information as present in the
632
+ first dicomfile of this serie. None if there are no entries."""
633
+ return self._info
634
+
635
+ @property
636
+ def description(self):
637
+ """A description of the dicom series. Used fields are
638
+ PatientName, shape of the data, SeriesDescription, and
639
+ ImageComments.
640
+ """
641
+ info = self.info
642
+
643
+ # If no info available, return simple description
644
+ if not info: # pragma: no cover
645
+ return "DicomSeries containing %i images" % len(self)
646
+
647
+ fields = []
648
+ # Give patient name
649
+ if "PatientName" in info:
650
+ fields.append("" + info["PatientName"])
651
+ # Also add dimensions
652
+ if self.shape:
653
+ tmp = [str(d) for d in self.shape]
654
+ fields.append("x".join(tmp))
655
+ # Try adding more fields
656
+ if "SeriesDescription" in info:
657
+ fields.append("'" + info["SeriesDescription"] + "'")
658
+ if "ImageComments" in info:
659
+ fields.append("'" + info["ImageComments"] + "'")
660
+
661
+ # Combine
662
+ return " ".join(fields)
663
+
664
+ def __repr__(self):
665
+ adr = hex(id(self)).upper()
666
+ return "<DicomSeries with %i images at %s>" % (len(self), adr)
667
+
668
+ def get_numpy_array(self):
669
+ """Get (load) the data that this DicomSeries represents, and return
670
+ it as a numpy array. If this serie contains multiple images, the
671
+ resulting array is 3D, otherwise it's 2D.
672
+ """
673
+
674
+ # It's easy if no file or if just a single file
675
+ if len(self) == 0:
676
+ raise ValueError("Serie does not contain any files.")
677
+ elif len(self) == 1:
678
+ return self[0].get_numpy_array()
679
+
680
+ # Check info
681
+ if self.info is None:
682
+ raise RuntimeError("Cannot return volume if series not finished.")
683
+
684
+ # Init data (using what the dicom packaged produces as a reference)
685
+ slice = self[0].get_numpy_array()
686
+ vol = np.zeros(self.shape, dtype=slice.dtype)
687
+ vol[0] = slice
688
+
689
+ # Fill volume
690
+ self._progressIndicator.start("loading data", "", len(self))
691
+ for z in range(1, len(self)):
692
+ vol[z] = self[z].get_numpy_array()
693
+ self._progressIndicator.set_progress(z + 1)
694
+ self._progressIndicator.finish()
695
+
696
+ # Done
697
+ import gc
698
+
699
+ gc.collect()
700
+ return vol
701
+
702
+ def _append(self, dcm):
703
+ self._entries.append(dcm)
704
+
705
+ def _sort(self):
706
+ self._entries.sort(
707
+ key=lambda k: (
708
+ k.InstanceNumber,
709
+ (
710
+ k.ImagePositionPatient[2]
711
+ if hasattr(k, "ImagePositionPatient")
712
+ else None
713
+ ),
714
+ )
715
+ )
716
+
717
+ def _finish(self):
718
+ """
719
+ Evaluate the series of dicom files. Together they should make up
720
+ a volumetric dataset. This means the files should meet certain
721
+ conditions. Also some additional information has to be calculated,
722
+ such as the distance between the slices. This method sets the
723
+ attributes for "shape", "sampling" and "info".
724
+
725
+ This method checks:
726
+ * that there are no missing files
727
+ * that the dimensions of all images match
728
+ * that the pixel spacing of all images match
729
+ """
730
+
731
+ # The datasets list should be sorted by instance number
732
+ L = self._entries
733
+ if len(L) == 0:
734
+ return
735
+ elif len(L) == 1:
736
+ self._info = L[0].info
737
+ return
738
+
739
+ # Get previous
740
+ ds1 = L[0]
741
+ # Init measures to calculate average of
742
+ distance_sum = 0.0
743
+ # Init measures to check (these are in 2D)
744
+ dimensions = ds1.Rows, ds1.Columns
745
+ # sampling = float(ds1.PixelSpacing[0]), float(ds1.PixelSpacing[1])
746
+ sampling = ds1.info["sampling"][:2] # row, column
747
+
748
+ for index in range(len(L)):
749
+ # The first round ds1 and ds2 will be the same, for the
750
+ # distance calculation this does not matter
751
+ # Get current
752
+ ds2 = L[index]
753
+ # Get positions
754
+ pos1 = float(ds1.ImagePositionPatient[2])
755
+ pos2 = float(ds2.ImagePositionPatient[2])
756
+ # Update distance_sum to calculate distance later
757
+ distance_sum += abs(pos1 - pos2)
758
+ # Test measures
759
+ dimensions2 = ds2.Rows, ds2.Columns
760
+ # sampling2 = float(ds2.PixelSpacing[0]), float(ds2.PixelSpacing[1])
761
+ sampling2 = ds2.info["sampling"][:2] # row, column
762
+ if dimensions != dimensions2:
763
+ # We cannot produce a volume if the dimensions match
764
+ raise ValueError("Dimensions of slices does not match.")
765
+ if sampling != sampling2:
766
+ # We can still produce a volume, but we should notify the user
767
+ self._progressIndicator.write("Warn: sampling does not match.")
768
+ # Store previous
769
+ ds1 = ds2
770
+
771
+ # Finish calculating average distance
772
+ # (Note that there are len(L)-1 distances)
773
+ distance_mean = distance_sum / (len(L) - 1)
774
+
775
+ # Set info dict
776
+ self._info = L[0].info.copy()
777
+
778
+ # Store information that is specific for the serie
779
+ self._info["shape"] = (len(L),) + ds2.info["shape"]
780
+ self._info["sampling"] = (distance_mean,) + ds2.info["sampling"]
781
+
782
+
783
+ def list_files(files, path):
784
+ """List all files in the directory, recursively."""
785
+ for item in os.listdir(path):
786
+ item = os.path.join(path, item)
787
+ if os.path.isdir(item):
788
+ list_files(files, item)
789
+ elif os.path.isfile(item):
790
+ files.append(item)
791
+
792
+
793
+ def process_directory(request, progressIndicator, readPixelData=False):
794
+ """
795
+ Reads dicom files and returns a list of DicomSeries objects, which
796
+ contain information about the data, and can be used to load the
797
+ image or volume data.
798
+
799
+ if readPixelData is True, the pixel data of all series is read. By
800
+ default the loading of pixeldata is deferred until it is requested
801
+ using the DicomSeries.get_pixel_array() method. In general, both
802
+ methods should be equally fast.
803
+ """
804
+ # Get directory to examine
805
+ if os.path.isdir(request.filename):
806
+ path = request.filename
807
+ elif os.path.isfile(request.filename):
808
+ path = os.path.dirname(request.filename)
809
+ else: # pragma: no cover - tested earlier
810
+ raise ValueError("Dicom plugin needs a valid filename to examine the directory")
811
+
812
+ # Check files
813
+ files = []
814
+ list_files(files, path) # Find files recursively
815
+
816
+ # Gather file data and put in DicomSeries
817
+ series = {}
818
+ count = 0
819
+ progressIndicator.start("examining files", "files", len(files))
820
+ for filename in files:
821
+ # Show progress (note that we always start with a 0.0)
822
+ count += 1
823
+ progressIndicator.set_progress(count)
824
+ # Skip DICOMDIR files
825
+ if filename.count("DICOMDIR"): # pragma: no cover
826
+ continue
827
+ # Try loading dicom ...
828
+ try:
829
+ dcm = SimpleDicomReader(filename)
830
+ except NotADicomFile:
831
+ continue # skip non-dicom file
832
+ except Exception as why: # pragma: no cover
833
+ progressIndicator.write(str(why))
834
+ continue
835
+ # Get SUID and register the file with an existing or new series object
836
+ try:
837
+ suid = dcm.SeriesInstanceUID
838
+ except AttributeError: # pragma: no cover
839
+ continue # some other kind of dicom file
840
+ if suid not in series:
841
+ series[suid] = DicomSeries(suid, progressIndicator)
842
+ series[suid]._append(dcm)
843
+
844
+ # Finish progress
845
+ # progressIndicator.finish('Found %i series.' % len(series))
846
+
847
+ # Make a list and sort, so that the order is deterministic
848
+ series = list(series.values())
849
+ series.sort(key=lambda x: x.suid)
850
+
851
+ # Split series if necessary
852
+ for serie in reversed([serie for serie in series]):
853
+ splitSerieIfRequired(serie, series, progressIndicator)
854
+
855
+ # Finish all series
856
+ # progressIndicator.start('analyse series', '', len(series))
857
+ series_ = []
858
+ for i in range(len(series)):
859
+ try:
860
+ series[i]._finish()
861
+ series_.append(series[i])
862
+ except Exception as err: # pragma: no cover
863
+ progressIndicator.write(str(err))
864
+ pass # Skip serie (probably report-like file without pixels)
865
+ # progressIndicator.set_progress(i+1)
866
+ progressIndicator.finish("Found %i correct series." % len(series_))
867
+
868
+ # Done
869
+ return series_
870
+
871
+
872
+ def splitSerieIfRequired(serie, series, progressIndicator):
873
+ """
874
+ Split the serie in multiple series if this is required. The choice
875
+ is based on examing the image position relative to the previous
876
+ image. If it differs too much, it is assumed that there is a new
877
+ dataset. This can happen for example in unspitted gated CT data.
878
+ """
879
+
880
+ # Sort the original list and get local name
881
+ serie._sort()
882
+ L = serie._entries
883
+ # Init previous slice
884
+ ds1 = L[0]
885
+ # Check whether we can do this
886
+ if "ImagePositionPatient" not in ds1:
887
+ return
888
+ # Initialize a list of new lists
889
+ L2 = [[ds1]]
890
+ # Init slice distance estimate
891
+ distance = 0
892
+
893
+ for index in range(1, len(L)):
894
+ # Get current slice
895
+ ds2 = L[index]
896
+ # Get positions
897
+ pos1 = float(ds1.ImagePositionPatient[2])
898
+ pos2 = float(ds2.ImagePositionPatient[2])
899
+ # Get distances
900
+ newDist = abs(pos1 - pos2)
901
+ # deltaDist = abs(firstPos-pos2)
902
+ # If the distance deviates more than 2x from what we've seen,
903
+ # we can agree it's a new dataset.
904
+ if distance and newDist > 2.1 * distance:
905
+ L2.append([])
906
+ distance = 0
907
+ else:
908
+ # Test missing file
909
+ if distance and newDist > 1.5 * distance:
910
+ progressIndicator.write(
911
+ "Warning: missing file after %r" % ds1._filename
912
+ )
913
+ distance = newDist
914
+ # Add to last list
915
+ L2[-1].append(ds2)
916
+ # Store previous
917
+ ds1 = ds2
918
+
919
+ # Split if we should
920
+ if len(L2) > 1:
921
+ # At what position are we now?
922
+ i = series.index(serie)
923
+ # Create new series
924
+ series2insert = []
925
+ for L in L2:
926
+ newSerie = DicomSeries(serie.suid, progressIndicator)
927
+ newSerie._entries = L
928
+ series2insert.append(newSerie)
929
+ # Insert series and remove self
930
+ for newSerie in reversed(series2insert):
931
+ series.insert(i, newSerie)
932
+ series.remove(serie)
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/example.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Example plugin. You can use this as a template for your own plugin.
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ from .. import formats
10
+ from ..core import Format
11
+
12
+
13
+ class DummyFormat(Format):
14
+ """The dummy format is an example format that does nothing.
15
+ It will never indicate that it can read or write a file. When
16
+ explicitly asked to read, it will simply read the bytes. When
17
+ explicitly asked to write, it will raise an error.
18
+
19
+ This documentation is shown when the user does ``help('thisformat')``.
20
+
21
+ Parameters for reading
22
+ ----------------------
23
+ Specify arguments in numpy doc style here.
24
+
25
+ Parameters for saving
26
+ ---------------------
27
+ Specify arguments in numpy doc style here.
28
+
29
+ """
30
+
31
+ def _can_read(self, request):
32
+ # This method is called when the format manager is searching
33
+ # for a format to read a certain image. Return True if this format
34
+ # can do it.
35
+ #
36
+ # The format manager is aware of the extensions and the modes
37
+ # that each format can handle. It will first ask all formats
38
+ # that *seem* to be able to read it whether they can. If none
39
+ # can, it will ask the remaining formats if they can: the
40
+ # extension might be missing, and this allows formats to provide
41
+ # functionality for certain extensions, while giving preference
42
+ # to other plugins.
43
+ #
44
+ # If a format says it can, it should live up to it. The format
45
+ # would ideally check the request.firstbytes and look for a
46
+ # header of some kind.
47
+ #
48
+ # The request object has:
49
+ # request.filename: a representation of the source (only for reporting)
50
+ # request.firstbytes: the first 256 bytes of the file.
51
+ # request.mode[0]: read or write mode
52
+
53
+ if request.extension in self.extensions:
54
+ return True
55
+
56
+ def _can_write(self, request):
57
+ # This method is called when the format manager is searching
58
+ # for a format to write a certain image. It will first ask all
59
+ # formats that *seem* to be able to write it whether they can.
60
+ # If none can, it will ask the remaining formats if they can.
61
+ #
62
+ # Return True if the format can do it.
63
+
64
+ # In most cases, this code does suffice:
65
+ if request.extension in self.extensions:
66
+ return True
67
+
68
+ # -- reader
69
+
70
+ class Reader(Format.Reader):
71
+ def _open(self, some_option=False, length=1):
72
+ # Specify kwargs here. Optionally, the user-specified kwargs
73
+ # can also be accessed via the request.kwargs object.
74
+ #
75
+ # The request object provides two ways to get access to the
76
+ # data. Use just one:
77
+ # - Use request.get_file() for a file object (preferred)
78
+ # - Use request.get_local_filename() for a file on the system
79
+ self._fp = self.request.get_file()
80
+ self._length = length # passed as an arg in this case for testing
81
+ self._data = None
82
+
83
+ def _close(self):
84
+ # Close the reader.
85
+ # Note that the request object will close self._fp
86
+ pass
87
+
88
+ def _get_length(self):
89
+ # Return the number of images. Can be np.inf
90
+ return self._length
91
+
92
+ def _get_data(self, index):
93
+ # Return the data and meta data for the given index
94
+ if index >= self._length:
95
+ raise IndexError("Image index %i > %i" % (index, self._length))
96
+ # Read all bytes
97
+ if self._data is None:
98
+ self._data = self._fp.read()
99
+ # Put in a numpy array
100
+ im = np.frombuffer(self._data, "uint8")
101
+ im.shape = len(im), 1
102
+ # Return array and dummy meta data
103
+ return im, {}
104
+
105
+ def _get_meta_data(self, index):
106
+ # Get the meta data for the given index. If index is None, it
107
+ # should return the global meta data.
108
+ return {} # This format does not support meta data
109
+
110
+ # -- writer
111
+
112
+ class Writer(Format.Writer):
113
+ def _open(self, flags=0):
114
+ # Specify kwargs here. Optionally, the user-specified kwargs
115
+ # can also be accessed via the request.kwargs object.
116
+ #
117
+ # The request object provides two ways to write the data.
118
+ # Use just one:
119
+ # - Use request.get_file() for a file object (preferred)
120
+ # - Use request.get_local_filename() for a file on the system
121
+ self._fp = self.request.get_file()
122
+
123
+ def _close(self):
124
+ # Close the reader.
125
+ # Note that the request object will close self._fp
126
+ pass
127
+
128
+ def _append_data(self, im, meta):
129
+ # Process the given data and meta data.
130
+ raise RuntimeError("The dummy format cannot write image data.")
131
+
132
+ def set_meta_data(self, meta):
133
+ # Process the given meta data (global for all images)
134
+ # It is not mandatory to support this.
135
+ raise RuntimeError("The dummy format cannot write meta data.")
136
+
137
+
138
+ # Register. You register an *instance* of a Format class. Here specify:
139
+ format = DummyFormat(
140
+ "dummy", # short name
141
+ "An example format that does nothing.", # one line descr.
142
+ ".foobar .nonexistentext", # list of extensions
143
+ "iI", # modes, characters in iIvV
144
+ )
145
+ formats.add_format(format)
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/feisem.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
27
+ from .tifffile import TiffFormat
28
+
29
+
30
+ class FEISEMFormat(TiffFormat):
31
+ """See :mod:`imageio.plugins.feisem`"""
32
+
33
+ def _can_write(self, request):
34
+ return False # FEI-SEM only supports reading
35
+
36
+ class Reader(TiffFormat.Reader):
37
+ def _get_data(self, index=0, discard_watermark=True, watermark_height=70):
38
+ """Get image and metadata from given index.
39
+
40
+ FEI images usually (always?) contain a watermark at the
41
+ bottom of the image, 70 pixels high. We discard this by
42
+ default as it does not contain any information not present
43
+ in the metadata.
44
+ """
45
+ im, meta = super(FEISEMFormat.Reader, self)._get_data(index)
46
+ if discard_watermark:
47
+ im = im[:-watermark_height]
48
+ return im, meta
49
+
50
+ def _get_meta_data(self, index=None):
51
+ """Read the metadata from an FEI SEM TIFF.
52
+
53
+ This metadata is included as ASCII text at the end of the file.
54
+
55
+ The index, if provided, is ignored.
56
+
57
+ Returns
58
+ -------
59
+ metadata : dict
60
+ Dictionary of metadata.
61
+ """
62
+ if hasattr(self, "_fei_meta"):
63
+ return self._fei_meta
64
+
65
+ md = {"root": {}}
66
+ current_tag = "root"
67
+ reading_metadata = False
68
+ filename = self.request.get_local_filename()
69
+ with open(filename, encoding="utf8", errors="ignore") as fin:
70
+ for line in fin:
71
+ if not reading_metadata:
72
+ if not line.startswith("Date="):
73
+ continue
74
+ else:
75
+ reading_metadata = True
76
+ line = line.rstrip()
77
+ if line.startswith("["):
78
+ current_tag = line.lstrip("[").rstrip("]")
79
+ md[current_tag] = {}
80
+ else:
81
+ if "=" in line: # ignore empty and irrelevant lines
82
+ key, val = line.split("=", maxsplit=1)
83
+ for tag_type in (int, float):
84
+ try:
85
+ val = tag_type(val)
86
+ except ValueError:
87
+ continue
88
+ else:
89
+ break
90
+ md[current_tag][key] = val
91
+ if not md["root"] and len(md) == 1:
92
+ raise ValueError("Input file %s contains no FEI metadata." % filename)
93
+
94
+ self._fei_meta = md
95
+ return md
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/grab.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PIL-based formats to take screenshots and grab from the clipboard.
3
+ """
4
+
5
+ import threading
6
+
7
+ import numpy as np
8
+
9
+ from ..core import Format
10
+
11
+
12
+ class BaseGrabFormat(Format):
13
+ """Base format for grab formats."""
14
+
15
+ _pillow_imported = False
16
+ _ImageGrab = None
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super(BaseGrabFormat, self).__init__(*args, **kwargs)
20
+ self._lock = threading.RLock()
21
+
22
+ def _can_write(self, request):
23
+ return False
24
+
25
+ def _init_pillow(self):
26
+ with self._lock:
27
+ if not self._pillow_imported:
28
+ self._pillow_imported = True # more like tried to import
29
+ import PIL
30
+
31
+ if not hasattr(PIL, "__version__"): # pragma: no cover
32
+ raise ImportError("Imageio Pillow requires " "Pillow, not PIL!")
33
+ try:
34
+ from PIL import ImageGrab
35
+ except ImportError:
36
+ return None
37
+ self._ImageGrab = ImageGrab
38
+ return self._ImageGrab
39
+
40
+ class Reader(Format.Reader):
41
+ def _open(self):
42
+ pass
43
+
44
+ def _close(self):
45
+ pass
46
+
47
+ def _get_data(self, index):
48
+ return self.format._get_data(index)
49
+
50
+
51
+ class ScreenGrabFormat(BaseGrabFormat):
52
+ """The ScreenGrabFormat provided a means to grab screenshots using
53
+ the uri of "<screen>".
54
+
55
+ This functionality is provided via Pillow. Note that "<screen>" is
56
+ only supported on Windows and OS X.
57
+
58
+ Parameters for reading
59
+ ----------------------
60
+ No parameters.
61
+ """
62
+
63
+ def _can_read(self, request):
64
+ if request.filename != "<screen>":
65
+ return False
66
+ return bool(self._init_pillow())
67
+
68
+ def _get_data(self, index):
69
+ ImageGrab = self._init_pillow()
70
+ assert ImageGrab
71
+
72
+ pil_im = ImageGrab.grab()
73
+ assert pil_im is not None
74
+ im = np.asarray(pil_im)
75
+ return im, {}
76
+
77
+
78
+ class ClipboardGrabFormat(BaseGrabFormat):
79
+ """The ClipboardGrabFormat provided a means to grab image data from
80
+ the clipboard, using the uri "<clipboard>"
81
+
82
+ This functionality is provided via Pillow. Note that "<clipboard>" is
83
+ only supported on Windows.
84
+
85
+ Parameters for reading
86
+ ----------------------
87
+ No parameters.
88
+ """
89
+
90
+ def _can_read(self, request):
91
+ if request.filename != "<clipboard>":
92
+ return False
93
+ return bool(self._init_pillow())
94
+
95
+ def _get_data(self, index):
96
+ ImageGrab = self._init_pillow()
97
+ assert ImageGrab
98
+
99
+ pil_im = ImageGrab.grabclipboard()
100
+ if pil_im is None:
101
+ raise RuntimeError(
102
+ "There seems to be no image data on the " "clipboard now."
103
+ )
104
+ im = np.asarray(pil_im)
105
+ return im, {}
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/opencv.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read/Write images using OpenCV.
2
+
3
+ Backend Library: `OpenCV <https://opencv.org/>`_
4
+
5
+ This plugin wraps OpenCV (also known as ``cv2``), a popular image processing
6
+ library. Currently, it exposes OpenCVs image reading capability (no video or GIF
7
+ support yet); however, this may be added in future releases.
8
+
9
+ Methods
10
+ -------
11
+ .. note::
12
+ Check the respective function for a list of supported kwargs and their
13
+ documentation.
14
+
15
+ .. autosummary::
16
+ :toctree:
17
+
18
+ OpenCVPlugin.read
19
+ OpenCVPlugin.iter
20
+ OpenCVPlugin.write
21
+ OpenCVPlugin.properties
22
+ OpenCVPlugin.metadata
23
+
24
+ Pixel Formats (Colorspaces)
25
+ ---------------------------
26
+
27
+ OpenCV is known to process images in BGR; however, most of the python ecosystem
28
+ (in particular matplotlib and other pydata libraries) use the RGB. As such,
29
+ images are converted to RGB, RGBA, or grayscale (where applicable) by default.
30
+
31
+ """
32
+
33
+ import warnings
34
+ from pathlib import Path
35
+ from typing import Any, Dict, List, Optional, Union
36
+
37
+ import cv2
38
+ import numpy as np
39
+
40
+ from ..core import Request
41
+ from ..core.request import URI_BYTES, InitializationError, IOMode
42
+ from ..core.v3_plugin_api import ImageProperties, PluginV3
43
+ from ..typing import ArrayLike
44
+
45
+
46
+ class OpenCVPlugin(PluginV3):
47
+ def __init__(self, request: Request) -> None:
48
+ super().__init__(request)
49
+
50
+ self.file_handle = request.get_local_filename()
51
+ if request._uri_type is URI_BYTES:
52
+ self.filename = "<bytes>"
53
+ else:
54
+ self.filename = request.raw_uri
55
+
56
+ mode = request.mode.io_mode
57
+ if mode == IOMode.read and not cv2.haveImageReader(self.file_handle):
58
+ raise InitializationError(f"OpenCV can't read `{self.filename}`.")
59
+ elif mode == IOMode.write and not cv2.haveImageWriter(self.file_handle):
60
+ raise InitializationError(f"OpenCV can't write to `{self.filename}`.")
61
+
62
+ def read(
63
+ self,
64
+ *,
65
+ index: int = None,
66
+ colorspace: Union[int, str] = None,
67
+ flags: int = cv2.IMREAD_COLOR,
68
+ ) -> np.ndarray:
69
+ """Read an image from the ImageResource.
70
+
71
+ Parameters
72
+ ----------
73
+ index : int, Ellipsis
74
+ If int, read the index-th image from the ImageResource. If ``...``,
75
+ read all images from the ImageResource and stack them along a new,
76
+ prepended, batch dimension. If None (default), use ``index=0`` if
77
+ the image contains exactly one image and ``index=...`` otherwise.
78
+ colorspace : str, int
79
+ The colorspace to convert into after loading and before returning
80
+ the image. If None (default) keep grayscale images as is, convert
81
+ images with an alpha channel to ``RGBA`` and all other images to
82
+ ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs
83
+ `conversion flags
84
+ <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_
85
+ and use it for conversion. If str, convert the image into the given
86
+ colorspace. Possible string values are: ``"RGB"``, ``"BGR"``,
87
+ ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``.
88
+ flags : int
89
+ The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs
90
+ <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_
91
+ for details.
92
+
93
+ Returns
94
+ -------
95
+ ndimage : np.ndarray
96
+ The decoded image as a numpy array.
97
+
98
+ """
99
+
100
+ if index is None:
101
+ n_images = cv2.imcount(self.file_handle, flags)
102
+ index = 0 if n_images == 1 else ...
103
+
104
+ if index is ...:
105
+ retval, img = cv2.imreadmulti(self.file_handle, flags=flags)
106
+ is_batch = True
107
+ else:
108
+ retval, img = cv2.imreadmulti(self.file_handle, index, 1, flags=flags)
109
+ is_batch = False
110
+
111
+ if retval is False:
112
+ raise ValueError(f"Could not read index `{index}` from `{self.filename}`.")
113
+
114
+ if img[0].ndim == 2:
115
+ in_colorspace = "GRAY"
116
+ out_colorspace = colorspace or "GRAY"
117
+ elif img[0].shape[-1] == 4:
118
+ in_colorspace = "BGRA"
119
+ out_colorspace = colorspace or "RGBA"
120
+ else:
121
+ in_colorspace = "BGR"
122
+ out_colorspace = colorspace or "RGB"
123
+
124
+ if isinstance(colorspace, int):
125
+ cvt_space = colorspace
126
+ elif in_colorspace == out_colorspace.upper():
127
+ cvt_space = None
128
+ else:
129
+ out_colorspace = out_colorspace.upper()
130
+ cvt_space = getattr(cv2, f"COLOR_{in_colorspace}2{out_colorspace}")
131
+
132
+ if cvt_space is not None:
133
+ img = np.stack([cv2.cvtColor(x, cvt_space) for x in img])
134
+ else:
135
+ img = np.stack(img)
136
+
137
+ return img if is_batch else img[0]
138
+
139
+ def iter(
140
+ self,
141
+ colorspace: Union[int, str] = None,
142
+ flags: int = cv2.IMREAD_COLOR,
143
+ ) -> np.ndarray:
144
+ """Yield images from the ImageResource.
145
+
146
+ Parameters
147
+ ----------
148
+ colorspace : str, int
149
+ The colorspace to convert into after loading and before returning
150
+ the image. If None (default) keep grayscale images as is, convert
151
+ images with an alpha channel to ``RGBA`` and all other images to
152
+ ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs
153
+ `conversion flags
154
+ <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_
155
+ and use it for conversion. If str, convert the image into the given
156
+ colorspace. Possible string values are: ``"RGB"``, ``"BGR"``,
157
+ ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``.
158
+ flags : int
159
+ The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs
160
+ <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_
161
+ for details.
162
+
163
+ Yields
164
+ ------
165
+ ndimage : np.ndarray
166
+ The decoded image as a numpy array.
167
+
168
+ """
169
+ for idx in range(cv2.imcount(self.file_handle)):
170
+ yield self.read(index=idx, flags=flags, colorspace=colorspace)
171
+
172
+ def write(
173
+ self,
174
+ ndimage: Union[ArrayLike, List[ArrayLike]],
175
+ is_batch: bool = False,
176
+ params: List[int] = None,
177
+ ) -> Optional[bytes]:
178
+ """Save an ndimage in the ImageResource.
179
+
180
+ Parameters
181
+ ----------
182
+ ndimage : ArrayLike, List[ArrayLike]
183
+ The image data that will be written to the file. It is either a
184
+ single image, a batch of images, or a list of images.
185
+ is_batch : bool
186
+ If True, the provided ndimage is a batch of images. If False (default), the
187
+ provided ndimage is a single image. If the provided ndimage is a list of images,
188
+ this parameter has no effect.
189
+ params : List[int]
190
+ A list of parameters that will be passed to OpenCVs imwrite or
191
+ imwritemulti functions. Possible values are documented in the
192
+ `OpenCV documentation
193
+ <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#gabbc7ef1aa2edfaa87772f1202d67e0ce>`_.
194
+
195
+ Returns
196
+ -------
197
+ encoded_image : bytes, None
198
+ If the ImageResource is ``"<bytes>"`` the call to write returns the
199
+ encoded image as a bytes string. Otherwise it returns None.
200
+
201
+ """
202
+
203
+ if isinstance(ndimage, list):
204
+ ndimage = np.stack(ndimage, axis=0)
205
+ elif not is_batch:
206
+ ndimage = ndimage[None, ...]
207
+
208
+ if ndimage[0].ndim == 2:
209
+ n_channels = 1
210
+ else:
211
+ n_channels = ndimage[0].shape[-1]
212
+
213
+ if n_channels == 1:
214
+ ndimage_cv2 = [x for x in ndimage]
215
+ elif n_channels == 4:
216
+ ndimage_cv2 = [cv2.cvtColor(x, cv2.COLOR_RGBA2BGRA) for x in ndimage]
217
+ else:
218
+ ndimage_cv2 = [cv2.cvtColor(x, cv2.COLOR_RGB2BGR) for x in ndimage]
219
+
220
+ retval = cv2.imwritemulti(self.file_handle, ndimage_cv2, params)
221
+
222
+ if retval is False:
223
+ # not sure what scenario would trigger this, but
224
+ # it can occur theoretically.
225
+ raise IOError("OpenCV failed to write.") # pragma: no cover
226
+
227
+ if self.request._uri_type == URI_BYTES:
228
+ return Path(self.file_handle).read_bytes()
229
+
230
+ def properties(
231
+ self,
232
+ index: int = None,
233
+ colorspace: Union[int, str] = None,
234
+ flags: int = cv2.IMREAD_COLOR,
235
+ ) -> ImageProperties:
236
+ """Standardized image metadata.
237
+
238
+ Parameters
239
+ ----------
240
+ index : int, Ellipsis
241
+ If int, get the properties of the index-th image in the
242
+ ImageResource. If ``...``, get the properties of the image stack
243
+ that contains all images. If None (default), use ``index=0`` if the
244
+ image contains exactly one image and ``index=...`` otherwise.
245
+ colorspace : str, int
246
+ The colorspace to convert into after loading and before returning
247
+ the image. If None (default) keep grayscale images as is, convert
248
+ images with an alpha channel to ``RGBA`` and all other images to
249
+ ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs
250
+ `conversion flags
251
+ <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_
252
+ and use it for conversion. If str, convert the image into the given
253
+ colorspace. Possible string values are: ``"RGB"``, ``"BGR"``,
254
+ ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``.
255
+ flags : int
256
+ The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs
257
+ <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_
258
+ for details.
259
+
260
+ Returns
261
+ -------
262
+ props : ImageProperties
263
+ A dataclass filled with standardized image metadata.
264
+
265
+ Notes
266
+ -----
267
+ Reading properties with OpenCV involves decoding pixel data, because
268
+ OpenCV doesn't provide a direct way to access metadata.
269
+
270
+ """
271
+
272
+ if index is None:
273
+ n_images = cv2.imcount(self.file_handle, flags)
274
+ is_batch = n_images > 1
275
+ elif index is Ellipsis:
276
+ n_images = cv2.imcount(self.file_handle, flags)
277
+ is_batch = True
278
+ else:
279
+ is_batch = False
280
+
281
+ # unfortunately, OpenCV doesn't allow reading shape without reading pixel data
282
+ if is_batch:
283
+ img = self.read(index=0, flags=flags, colorspace=colorspace)
284
+ return ImageProperties(
285
+ shape=(n_images, *img.shape),
286
+ dtype=img.dtype,
287
+ n_images=n_images,
288
+ is_batch=True,
289
+ )
290
+
291
+ img = self.read(index=index, flags=flags, colorspace=colorspace)
292
+ return ImageProperties(shape=img.shape, dtype=img.dtype, is_batch=False)
293
+
294
+ def metadata(
295
+ self, index: int = None, exclude_applied: bool = True
296
+ ) -> Dict[str, Any]:
297
+ """Format-specific metadata.
298
+
299
+ .. warning::
300
+ OpenCV does not support reading metadata. When called, this function
301
+ will raise a ``NotImplementedError``.
302
+
303
+ Parameters
304
+ ----------
305
+ index : int
306
+ This parameter has no effect.
307
+ exclude_applied : bool
308
+ This parameter has no effect.
309
+
310
+ """
311
+
312
+ warnings.warn("OpenCV does not support reading metadata.", UserWarning)
313
+ return dict()
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/pillow_info.py ADDED
@@ -0,0 +1,1053 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # styletest: ignore E122 E123 E501
4
+
5
+ """
6
+ Module that contain info about the Pillow formats. The first part of
7
+ this module generates this info and writes it to its own bottom half
8
+ if run as a script.
9
+ """
10
+
11
+ import warnings
12
+
13
+ warnings.warn(
14
+ "The `PillowFormat` plugin is deprecated and will be removed in ImageIO v3."
15
+ " Use the new `PillowPlugin` instead.",
16
+ DeprecationWarning,
17
+ )
18
+
19
+
20
+ def generate_info(): # pragma: no cover
21
+ from urllib.request import urlopen
22
+ import PIL
23
+ from PIL import Image
24
+
25
+ Image.init()
26
+
27
+ ids = []
28
+ formats = []
29
+ docs = {}
30
+
31
+ # Collect formats and their summary from plugin modules
32
+ for mod_name in dir(PIL):
33
+ if "ImagePlugin" in mod_name:
34
+ mod = getattr(PIL, mod_name)
35
+ for ob_name in dir(mod):
36
+ ob = getattr(mod, ob_name)
37
+ if isinstance(ob, type) and issubclass(ob, Image.Image):
38
+ if ob.format in ids:
39
+ print("Found duplicate for", ob.format)
40
+ else:
41
+ ids.append(ob.format)
42
+ formats.append((ob.format, ob.format_description))
43
+
44
+ # Add extension info
45
+ for i in range(len(formats)):
46
+ id, summary = formats[i]
47
+ ext = " ".join([e for e in Image.EXTENSION if Image.EXTENSION[e] == id])
48
+ formats[i] = id, summary, ext
49
+
50
+ # Get documentation of formats
51
+ url = "https://raw.githubusercontent.com/python-pillow/Pillow/master/docs/handbook/image-file-formats.rst" # noqa
52
+ lines = urlopen(url).read().decode().splitlines()
53
+ lines.append("End")
54
+ lines.append("---") # for the end
55
+
56
+ # Parse documentation
57
+ cur_name = ""
58
+ cur_part = []
59
+ for i in range(len(lines)):
60
+ line = lines[i]
61
+ if line.startswith(("^^^", "---", "===")):
62
+ if cur_name and cur_name in ids:
63
+ text = "\n".join(cur_part[:-1])
64
+ text = text.replace("versionadded::", "versionadded:: Pillow ")
65
+ text = text.replace("Image.open`", "Image.write`")
66
+ docs[cur_name] = text
67
+ cur_part = []
68
+ cur_name = lines[i - 1].strip().replace(" ", "").upper()
69
+ else:
70
+ cur_part.append(" " + line)
71
+
72
+ # Fill in the blancs
73
+ for id in ids:
74
+ if id in docs:
75
+ docs[id] = "*From the Pillow docs:*\n\n" + docs[id]
76
+ else:
77
+ docs[id] = "No docs for %s." % id
78
+ print("no docs for", id)
79
+
80
+ # Sort before writing
81
+ formats.sort(key=lambda x: x[0])
82
+ ids.sort()
83
+
84
+ # Read file ...
85
+ code = open(__file__, "rb").read().decode()
86
+ code, divider, _ = code.partition("## BELOW IS " + "AUTOGENERATED")
87
+ code += divider + "\n\n"
88
+
89
+ # Write formats
90
+ code += "pillow_formats = [\n"
91
+ for i in range(len(formats)):
92
+ print(formats[i])
93
+ code += " (%r, %r, %r),\n" % formats[i]
94
+ code += " ]\n\n\n"
95
+
96
+ # Write docs
97
+ code += "pillow_docs = {\n"
98
+ for id in ids:
99
+ code += '%r:\nu"""%s""",\n' % (id, docs[id])
100
+ code += "}\n"
101
+
102
+ # Write back
103
+ with open(__file__, "wb") as f:
104
+ f.write(code.encode())
105
+
106
+
107
+ if __name__ == "__main__":
108
+ generate_info()
109
+
110
+
111
+ # BELOW IS AUTOGENERATED
112
+
113
+ pillow_formats = [
114
+ ("BMP", "Windows Bitmap", ".bmp"),
115
+ ("BUFR", "BUFR", ".bufr"),
116
+ ("CUR", "Windows Cursor", ".cur"),
117
+ ("DCX", "Intel DCX", ".dcx"),
118
+ ("DDS", "DirectDraw Surface", ".dds"),
119
+ ("DIB", "Windows Bitmap", ""),
120
+ ("EPS", "Encapsulated Postscript", ".ps .eps"),
121
+ ("FITS", "FITS", ".fit .fits"),
122
+ ("FLI", "Autodesk FLI/FLC Animation", ".fli .flc"),
123
+ ("FPX", "FlashPix", ".fpx"),
124
+ ("FTEX", "Texture File Format (IW2:EOC)", ".ftc .ftu"),
125
+ ("GBR", "GIMP brush file", ".gbr"),
126
+ ("GIF", "Compuserve GIF", ".gif"),
127
+ ("GRIB", "GRIB", ".grib"),
128
+ ("HDF5", "HDF5", ".h5 .hdf"),
129
+ ("ICNS", "Mac OS icns resource", ".icns"),
130
+ ("ICO", "Windows Icon", ".ico"),
131
+ ("IM", "IFUNC Image Memory", ".im"),
132
+ ("IMT", "IM Tools", ""),
133
+ ("IPTC", "IPTC/NAA", ".iim"),
134
+ ("JPEG", "JPEG (ISO 10918)", ".jfif .jpe .jpg .jpeg"),
135
+ ("JPEG2000", "JPEG 2000 (ISO 15444)", ".jp2 .j2k .jpc .jpf .jpx .j2c"),
136
+ ("MCIDAS", "McIdas area file", ""),
137
+ ("MIC", "Microsoft Image Composer", ".mic"),
138
+ ("MPEG", "MPEG", ".mpg .mpeg"),
139
+ ("MPO", "MPO (CIPA DC-007)", ".mpo"),
140
+ ("MSP", "Windows Paint", ".msp"),
141
+ ("PCD", "Kodak PhotoCD", ".pcd"),
142
+ ("PCX", "Paintbrush", ".pcx"),
143
+ ("PIXAR", "PIXAR raster image", ".pxr"),
144
+ ("PNG", "Portable network graphics", ".png"),
145
+ ("PPM", "Pbmplus image", ".pbm .pgm .ppm"),
146
+ ("PSD", "Adobe Photoshop", ".psd"),
147
+ ("SGI", "SGI Image File Format", ".bw .rgb .rgba .sgi"),
148
+ ("SPIDER", "Spider 2D image", ""),
149
+ ("SUN", "Sun Raster File", ".ras"),
150
+ ("TGA", "Targa", ".tga"),
151
+ ("TIFF", "Adobe TIFF", ".tif .tiff"),
152
+ ("WMF", "Windows Metafile", ".wmf .emf"),
153
+ ("XBM", "X11 Bitmap", ".xbm"),
154
+ ("XPM", "X11 Pixel Map", ".xpm"),
155
+ ("XVThumb", "XV thumbnail image", ""),
156
+ ]
157
+
158
+
159
+ pillow_docs = {
160
+ "BMP": """*From the Pillow docs:*
161
+
162
+
163
+ PIL reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``,
164
+ or ``RGB`` data. 16-colour images are read as ``P`` images. Run-length encoding
165
+ is not supported.
166
+
167
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
168
+ :py:attr:`~PIL.Image.Image.info` properties:
169
+
170
+ **compression**
171
+ Set to ``bmp_rle`` if the file is run-length encoded.
172
+ """,
173
+ "BUFR": """*From the Pillow docs:*
174
+
175
+
176
+ .. versionadded:: Pillow 1.1.3
177
+
178
+ PIL provides a stub driver for BUFR files.
179
+
180
+ To add read or write support to your application, use
181
+ :py:func:`PIL.BufrStubImagePlugin.register_handler`.
182
+ """,
183
+ "CUR": """*From the Pillow docs:*
184
+
185
+
186
+ CUR is used to store cursors on Windows. The CUR decoder reads the largest
187
+ available cursor. Animated cursors are not supported.
188
+ """,
189
+ "DCX": """*From the Pillow docs:*
190
+
191
+
192
+ DCX is a container file format for PCX files, defined by Intel. The DCX format
193
+ is commonly used in fax applications. The DCX decoder can read files containing
194
+ ``1``, ``L``, ``P``, or ``RGB`` data.
195
+
196
+ When the file is opened, only the first image is read. You can use
197
+ :py:meth:`~file.seek` or :py:mod:`~PIL.ImageSequence` to read other images.
198
+
199
+ """,
200
+ "DDS": """*From the Pillow docs:*
201
+
202
+
203
+ DDS is a popular container texture format used in video games and natively
204
+ supported by DirectX.
205
+ Currently, DXT1, DXT3, and DXT5 pixel formats are supported and only in ``RGBA``
206
+ mode.
207
+
208
+ .. versionadded:: Pillow 3.4.0 DXT3
209
+ """,
210
+ "DIB": """No docs for DIB.""",
211
+ "EPS": """*From the Pillow docs:*
212
+
213
+
214
+ PIL identifies EPS files containing image data, and can read files that contain
215
+ embedded raster images (ImageData descriptors). If Ghostscript is available,
216
+ other EPS files can be read as well. The EPS driver can also write EPS
217
+ images. The EPS driver can read EPS images in ``L``, ``LAB``, ``RGB`` and
218
+ ``CMYK`` mode, but Ghostscript may convert the images to ``RGB`` mode rather
219
+ than leaving them in the original color space. The EPS driver can write images
220
+ in ``L``, ``RGB`` and ``CMYK`` modes.
221
+
222
+ If Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`
223
+ method with the following parameter to affect how Ghostscript renders the EPS
224
+
225
+ **scale**
226
+ Affects the scale of the resultant rasterized image. If the EPS suggests
227
+ that the image be rendered at 100px x 100px, setting this parameter to
228
+ 2 will make the Ghostscript render a 200px x 200px image instead. The
229
+ relative position of the bounding box is maintained::
230
+
231
+ im = Image.open(...)
232
+ im.size #(100,100)
233
+ im.load(scale=2)
234
+ im.size #(200,200)
235
+ """,
236
+ "FITS": """*From the Pillow docs:*
237
+
238
+
239
+ .. versionadded:: Pillow 1.1.5
240
+
241
+ PIL provides a stub driver for FITS files.
242
+
243
+ To add read or write support to your application, use
244
+ :py:func:`PIL.FitsStubImagePlugin.register_handler`.
245
+ """,
246
+ "FLI": """No docs for FLI.""",
247
+ "FPX": """*From the Pillow docs:*
248
+
249
+
250
+ PIL reads Kodak FlashPix files. In the current version, only the highest
251
+ resolution image is read from the file, and the viewing transform is not taken
252
+ into account.
253
+
254
+ .. note::
255
+
256
+ To enable full FlashPix support, you need to build and install the IJG JPEG
257
+ library before building the Python Imaging Library. See the distribution
258
+ README for details.
259
+ """,
260
+ "FTEX": """*From the Pillow docs:*
261
+
262
+
263
+ .. versionadded:: Pillow 3.2.0
264
+
265
+ The FTEX decoder reads textures used for 3D objects in
266
+ Independence War 2: Edge Of Chaos. The plugin reads a single texture
267
+ per file, in the compressed and uncompressed formats.
268
+ """,
269
+ "GBR": """*From the Pillow docs:*
270
+
271
+
272
+ The GBR decoder reads GIMP brush files, version 1 and 2.
273
+
274
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
275
+ :py:attr:`~PIL.Image.Image.info` properties:
276
+
277
+ **comment**
278
+ The brush name.
279
+
280
+ **spacing**
281
+ The spacing between the brushes, in pixels. Version 2 only.
282
+
283
+ GD
284
+ ^^
285
+
286
+ PIL reads uncompressed GD files. Note that this file format cannot be
287
+ automatically identified, so you must use :py:func:`PIL.GdImageFile.open` to
288
+ read such a file.
289
+
290
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
291
+ :py:attr:`~PIL.Image.Image.info` properties:
292
+
293
+ **transparency**
294
+ Transparency color index. This key is omitted if the image is not
295
+ transparent.
296
+ """,
297
+ "GIF": """*From the Pillow docs:*
298
+
299
+
300
+ PIL reads GIF87a and GIF89a versions of the GIF file format. The library writes
301
+ run-length encoded files in GIF87a by default, unless GIF89a features
302
+ are used or GIF89a is already in use.
303
+
304
+ Note that GIF files are always read as grayscale (``L``)
305
+ or palette mode (``P``) images.
306
+
307
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
308
+ :py:attr:`~PIL.Image.Image.info` properties:
309
+
310
+ **background**
311
+ Default background color (a palette color index).
312
+
313
+ **transparency**
314
+ Transparency color index. This key is omitted if the image is not
315
+ transparent.
316
+
317
+ **version**
318
+ Version (either ``GIF87a`` or ``GIF89a``).
319
+
320
+ **duration**
321
+ May not be present. The time to display the current frame
322
+ of the GIF, in milliseconds.
323
+
324
+ **loop**
325
+ May not be present. The number of times the GIF should loop.
326
+
327
+ Reading sequences
328
+ ~~~~~~~~~~~~~~~~~
329
+
330
+ The GIF loader supports the :py:meth:`~file.seek` and :py:meth:`~file.tell`
331
+ methods. You can seek to the next frame (``im.seek(im.tell() + 1)``), or rewind
332
+ the file by seeking to the first frame. Random access is not supported.
333
+
334
+ ``im.seek()`` raises an ``EOFError`` if you try to seek after the last frame.
335
+
336
+ Saving
337
+ ~~~~~~
338
+
339
+ When calling :py:meth:`~PIL.Image.Image.save`, the following options
340
+ are available::
341
+
342
+ im.save(out, save_all=True, append_images=[im1, im2, ...])
343
+
344
+ **save_all**
345
+ If present and true, all frames of the image will be saved. If
346
+ not, then only the first frame of a multiframe image will be saved.
347
+
348
+ **append_images**
349
+ A list of images to append as additional frames. Each of the
350
+ images in the list can be single or multiframe images.
351
+ This is currently only supported for GIF, PDF, TIFF, and WebP.
352
+
353
+ **duration**
354
+ The display duration of each frame of the multiframe gif, in
355
+ milliseconds. Pass a single integer for a constant duration, or a
356
+ list or tuple to set the duration for each frame separately.
357
+
358
+ **loop**
359
+ Integer number of times the GIF should loop.
360
+
361
+ **optimize**
362
+ If present and true, attempt to compress the palette by
363
+ eliminating unused colors. This is only useful if the palette can
364
+ be compressed to the next smaller power of 2 elements.
365
+
366
+ **palette**
367
+ Use the specified palette for the saved image. The palette should
368
+ be a bytes or bytearray object containing the palette entries in
369
+ RGBRGB... form. It should be no more than 768 bytes. Alternately,
370
+ the palette can be passed in as an
371
+ :py:class:`PIL.ImagePalette.ImagePalette` object.
372
+
373
+ **disposal**
374
+ Indicates the way in which the graphic is to be treated after being displayed.
375
+
376
+ * 0 - No disposal specified.
377
+ * 1 - Do not dispose.
378
+ * 2 - Restore to background color.
379
+ * 3 - Restore to previous content.
380
+
381
+ Pass a single integer for a constant disposal, or a list or tuple
382
+ to set the disposal for each frame separately.
383
+
384
+ Reading local images
385
+ ~~~~~~~~~~~~~~~~~~~~
386
+
387
+ The GIF loader creates an image memory the same size as the GIF file’s *logical
388
+ screen size*, and pastes the actual pixel data (the *local image*) into this
389
+ image. If you only want the actual pixel rectangle, you can manipulate the
390
+ :py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.tile`
391
+ attributes before loading the file::
392
+
393
+ im = Image.open(...)
394
+
395
+ if im.tile[0][0] == "gif":
396
+ # only read the first "local image" from this GIF file
397
+ tag, (x0, y0, x1, y1), offset, extra = im.tile[0]
398
+ im.size = (x1 - x0, y1 - y0)
399
+ im.tile = [(tag, (0, 0) + im.size, offset, extra)]
400
+ """,
401
+ "GRIB": """*From the Pillow docs:*
402
+
403
+
404
+ .. versionadded:: Pillow 1.1.5
405
+
406
+ PIL provides a stub driver for GRIB files.
407
+
408
+ The driver requires the file to start with a GRIB header. If you have files
409
+ with embedded GRIB data, or files with multiple GRIB fields, your application
410
+ has to seek to the header before passing the file handle to PIL.
411
+
412
+ To add read or write support to your application, use
413
+ :py:func:`PIL.GribStubImagePlugin.register_handler`.
414
+ """,
415
+ "HDF5": """*From the Pillow docs:*
416
+
417
+
418
+ .. versionadded:: Pillow 1.1.5
419
+
420
+ PIL provides a stub driver for HDF5 files.
421
+
422
+ To add read or write support to your application, use
423
+ :py:func:`PIL.Hdf5StubImagePlugin.register_handler`.
424
+ """,
425
+ "ICNS": """*From the Pillow docs:*
426
+
427
+
428
+ PIL reads and (macOS only) writes macOS ``.icns`` files. By default, the
429
+ largest available icon is read, though you can override this by setting the
430
+ :py:attr:`~PIL.Image.Image.size` property before calling
431
+ :py:meth:`~PIL.Image.Image.load`. The :py:meth:`~PIL.Image.Image.write` method
432
+ sets the following :py:attr:`~PIL.Image.Image.info` property:
433
+
434
+ **sizes**
435
+ A list of supported sizes found in this icon file; these are a
436
+ 3-tuple, ``(width, height, scale)``, where ``scale`` is 2 for a retina
437
+ icon and 1 for a standard icon. You *are* permitted to use this 3-tuple
438
+ format for the :py:attr:`~PIL.Image.Image.size` property if you set it
439
+ before calling :py:meth:`~PIL.Image.Image.load`; after loading, the size
440
+ will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you
441
+ ask for ``(512, 512, 2)``, the final value of
442
+ :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).
443
+ """,
444
+ "ICO": """*From the Pillow docs:*
445
+
446
+
447
+ ICO is used to store icons on Windows. The largest available icon is read.
448
+
449
+ The :py:meth:`~PIL.Image.Image.save` method supports the following options:
450
+
451
+ **sizes**
452
+ A list of sizes including in this ico file; these are a 2-tuple,
453
+ ``(width, height)``; Default to ``[(16, 16), (24, 24), (32, 32), (48, 48),
454
+ (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original
455
+ size or 256 will be ignored.
456
+
457
+ IM
458
+ ^^
459
+
460
+ IM is a format used by LabEye and other applications based on the IFUNC image
461
+ processing library. The library reads and writes most uncompressed interchange
462
+ versions of this format.
463
+
464
+ IM is the only format that can store all internal PIL formats.
465
+ """,
466
+ "IM": """No docs for IM.""",
467
+ "IMT": """*From the Pillow docs:*
468
+
469
+
470
+ PIL reads Image Tools images containing ``L`` data.
471
+ """,
472
+ "IPTC": """No docs for IPTC.""",
473
+ "JPEG": """*From the Pillow docs:*
474
+
475
+
476
+ PIL reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or
477
+ ``CMYK`` data. It writes standard and progressive JFIF files.
478
+
479
+ Using the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by
480
+ converting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of
481
+ their original size while loading them.
482
+
483
+ The :py:meth:`~PIL.Image.Image.write` method may set the following
484
+ :py:attr:`~PIL.Image.Image.info` properties if available:
485
+
486
+ **jfif**
487
+ JFIF application marker found. If the file is not a JFIF file, this key is
488
+ not present.
489
+
490
+ **jfif_version**
491
+ A tuple representing the jfif version, (major version, minor version).
492
+
493
+ **jfif_density**
494
+ A tuple representing the pixel density of the image, in units specified
495
+ by jfif_unit.
496
+
497
+ **jfif_unit**
498
+ Units for the jfif_density:
499
+
500
+ * 0 - No Units
501
+ * 1 - Pixels per Inch
502
+ * 2 - Pixels per Centimeter
503
+
504
+ **dpi**
505
+ A tuple representing the reported pixel density in pixels per inch, if
506
+ the file is a jfif file and the units are in inches.
507
+
508
+ **adobe**
509
+ Adobe application marker found. If the file is not an Adobe JPEG file, this
510
+ key is not present.
511
+
512
+ **adobe_transform**
513
+ Vendor Specific Tag.
514
+
515
+ **progression**
516
+ Indicates that this is a progressive JPEG file.
517
+
518
+ **icc_profile**
519
+ The ICC color profile for the image.
520
+
521
+ **exif**
522
+ Raw EXIF data from the image.
523
+
524
+
525
+ The :py:meth:`~PIL.Image.Image.save` method supports the following options:
526
+
527
+ **quality**
528
+ The image quality, on a scale from 1 (worst) to 95 (best). The default is
529
+ 75. Values above 95 should be avoided; 100 disables portions of the JPEG
530
+ compression algorithm, and results in large files with hardly any gain in
531
+ image quality.
532
+
533
+ **optimize**
534
+ If present and true, indicates that the encoder should make an extra pass
535
+ over the image in order to select optimal encoder settings.
536
+
537
+ **progressive**
538
+ If present and true, indicates that this image should be stored as a
539
+ progressive JPEG file.
540
+
541
+ **dpi**
542
+ A tuple of integers representing the pixel density, ``(x,y)``.
543
+
544
+ **icc_profile**
545
+ If present and true, the image is stored with the provided ICC profile.
546
+ If this parameter is not provided, the image will be saved with no profile
547
+ attached. To preserve the existing profile::
548
+
549
+ im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))
550
+
551
+ **exif**
552
+ If present, the image will be stored with the provided raw EXIF data.
553
+
554
+ **subsampling**
555
+ If present, sets the subsampling for the encoder.
556
+
557
+ * ``keep``: Only valid for JPEG files, will retain the original image setting.
558
+ * ``4:4:4``, ``4:2:2``, ``4:2:0``: Specific sampling values
559
+ * ``-1``: equivalent to ``keep``
560
+ * ``0``: equivalent to ``4:4:4``
561
+ * ``1``: equivalent to ``4:2:2``
562
+ * ``2``: equivalent to ``4:2:0``
563
+
564
+ **qtables**
565
+ If present, sets the qtables for the encoder. This is listed as an
566
+ advanced option for wizards in the JPEG documentation. Use with
567
+ caution. ``qtables`` can be one of several types of values:
568
+
569
+ * a string, naming a preset, e.g. ``keep``, ``web_low``, or ``web_high``
570
+ * a list, tuple, or dictionary (with integer keys =
571
+ range(len(keys))) of lists of 64 integers. There must be
572
+ between 2 and 4 tables.
573
+
574
+ .. versionadded:: Pillow 2.5.0
575
+
576
+
577
+ .. note::
578
+
579
+ To enable JPEG support, you need to build and install the IJG JPEG library
580
+ before building the Python Imaging Library. See the distribution README for
581
+ details.
582
+ """,
583
+ "JPEG2000": """*From the Pillow docs:*
584
+
585
+
586
+ .. versionadded:: Pillow 2.4.0
587
+
588
+ PIL reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB`` or
589
+ ``RGBA`` data. It can also read files containing ``YCbCr`` data, which it
590
+ converts on read into ``RGB`` or ``RGBA`` depending on whether or not there is
591
+ an alpha channel. PIL supports JPEG 2000 raw codestreams (``.j2k`` files), as
592
+ well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files). PIL does *not*
593
+ support files whose components have different sampling frequencies.
594
+
595
+ When loading, if you set the ``mode`` on the image prior to the
596
+ :py:meth:`~PIL.Image.Image.load` method being invoked, you can ask PIL to
597
+ convert the image to either ``RGB`` or ``RGBA`` rather than choosing for
598
+ itself. It is also possible to set ``reduce`` to the number of resolutions to
599
+ discard (each one reduces the size of the resulting image by a factor of 2),
600
+ and ``layers`` to specify the number of quality layers to load.
601
+
602
+ The :py:meth:`~PIL.Image.Image.save` method supports the following options:
603
+
604
+ **offset**
605
+ The image offset, as a tuple of integers, e.g. (16, 16)
606
+
607
+ **tile_offset**
608
+ The tile offset, again as a 2-tuple of integers.
609
+
610
+ **tile_size**
611
+ The tile size as a 2-tuple. If not specified, or if set to None, the
612
+ image will be saved without tiling.
613
+
614
+ **quality_mode**
615
+ Either `"rates"` or `"dB"` depending on the units you want to use to
616
+ specify image quality.
617
+
618
+ **quality_layers**
619
+ A sequence of numbers, each of which represents either an approximate size
620
+ reduction (if quality mode is `"rates"`) or a signal to noise ratio value
621
+ in decibels. If not specified, defaults to a single layer of full quality.
622
+
623
+ **num_resolutions**
624
+ The number of different image resolutions to be stored (which corresponds
625
+ to the number of Discrete Wavelet Transform decompositions plus one).
626
+
627
+ **codeblock_size**
628
+ The code-block size as a 2-tuple. Minimum size is 4 x 4, maximum is 1024 x
629
+ 1024, with the additional restriction that no code-block may have more
630
+ than 4096 coefficients (i.e. the product of the two numbers must be no
631
+ greater than 4096).
632
+
633
+ **precinct_size**
634
+ The precinct size as a 2-tuple. Must be a power of two along both axes,
635
+ and must be greater than the code-block size.
636
+
637
+ **irreversible**
638
+ If ``True``, use the lossy Irreversible Color Transformation
639
+ followed by DWT 9-7. Defaults to ``False``, which means to use the
640
+ Reversible Color Transformation with DWT 5-3.
641
+
642
+ **progression**
643
+ Controls the progression order; must be one of ``"LRCP"``, ``"RLCP"``,
644
+ ``"RPCL"``, ``"PCRL"``, ``"CPRL"``. The letters stand for Component,
645
+ Position, Resolution and Layer respectively and control the order of
646
+ encoding, the idea being that e.g. an image encoded using LRCP mode can
647
+ have its quality layers decoded as they arrive at the decoder, while one
648
+ encoded using RLCP mode will have increasing resolutions decoded as they
649
+ arrive, and so on.
650
+
651
+ **cinema_mode**
652
+ Set the encoder to produce output compliant with the digital cinema
653
+ specifications. The options here are ``"no"`` (the default),
654
+ ``"cinema2k-24"`` for 24fps 2K, ``"cinema2k-48"`` for 48fps 2K, and
655
+ ``"cinema4k-24"`` for 24fps 4K. Note that for compliant 2K files,
656
+ *at least one* of your image dimensions must match 2048 x 1080, while
657
+ for compliant 4K files, *at least one* of the dimensions must match
658
+ 4096 x 2160.
659
+
660
+ .. note::
661
+
662
+ To enable JPEG 2000 support, you need to build and install the OpenJPEG
663
+ library, version 2.0.0 or higher, before building the Python Imaging
664
+ Library.
665
+
666
+ Windows users can install the OpenJPEG binaries available on the
667
+ OpenJPEG website, but must add them to their PATH in order to use PIL (if
668
+ you fail to do this, you will get errors about not being able to load the
669
+ ``_imaging`` DLL).
670
+ """,
671
+ "MCIDAS": """*From the Pillow docs:*
672
+
673
+
674
+ PIL identifies and reads 8-bit McIdas area files.
675
+ """,
676
+ "MIC": """*From the Pillow docs:*
677
+
678
+
679
+ PIL identifies and reads Microsoft Image Composer (MIC) files. When opened, the
680
+ first sprite in the file is loaded. You can use :py:meth:`~file.seek` and
681
+ :py:meth:`~file.tell` to read other sprites from the file.
682
+
683
+ Note that there may be an embedded gamma of 2.2 in MIC files.
684
+ """,
685
+ "MPEG": """*From the Pillow docs:*
686
+
687
+
688
+ PIL identifies MPEG files.
689
+ """,
690
+ "MPO": """*From the Pillow docs:*
691
+
692
+
693
+ Pillow identifies and reads Multi Picture Object (MPO) files, loading the primary
694
+ image when first opened. The :py:meth:`~file.seek` and :py:meth:`~file.tell`
695
+ methods may be used to read other pictures from the file. The pictures are
696
+ zero-indexed and random access is supported.
697
+ """,
698
+ "MSP": """*From the Pillow docs:*
699
+
700
+
701
+ PIL identifies and reads MSP files from Windows 1 and 2. The library writes
702
+ uncompressed (Windows 1) versions of this format.
703
+ """,
704
+ "PCD": """*From the Pillow docs:*
705
+
706
+
707
+ PIL reads PhotoCD files containing ``RGB`` data. This only reads the 768x512
708
+ resolution image from the file. Higher resolutions are encoded in a proprietary
709
+ encoding.
710
+ """,
711
+ "PCX": """*From the Pillow docs:*
712
+
713
+
714
+ PIL reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data.
715
+ """,
716
+ "PIXAR": """*From the Pillow docs:*
717
+
718
+
719
+ PIL provides limited support for PIXAR raster files. The library can identify
720
+ and read “dumped” RGB files.
721
+
722
+ The format code is ``PIXAR``.
723
+ """,
724
+ "PNG": """*From the Pillow docs:*
725
+
726
+
727
+ PIL identifies, reads, and writes PNG files containing ``1``, ``L``, ``P``,
728
+ ``RGB``, or ``RGBA`` data. Interlaced files are supported as of v1.1.7.
729
+
730
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
731
+ :py:attr:`~PIL.Image.Image.info` properties, when appropriate:
732
+
733
+ **chromaticity**
734
+ The chromaticity points, as an 8 tuple of floats. (``White Point
735
+ X``, ``White Point Y``, ``Red X``, ``Red Y``, ``Green X``, ``Green
736
+ Y``, ``Blue X``, ``Blue Y``)
737
+
738
+ **gamma**
739
+ Gamma, given as a floating point number.
740
+
741
+ **srgb**
742
+ The sRGB rendering intent as an integer.
743
+
744
+ * 0 Perceptual
745
+ * 1 Relative Colorimetric
746
+ * 2 Saturation
747
+ * 3 Absolute Colorimetric
748
+
749
+ **transparency**
750
+ For ``P`` images: Either the palette index for full transparent pixels,
751
+ or a byte string with alpha values for each palette entry.
752
+
753
+ For ``L`` and ``RGB`` images, the color that represents full transparent
754
+ pixels in this image.
755
+
756
+ This key is omitted if the image is not a transparent palette image.
757
+
758
+ ``Open`` also sets ``Image.text`` to a list of the values of the
759
+ ``tEXt``, ``zTXt``, and ``iTXt`` chunks of the PNG image. Individual
760
+ compressed chunks are limited to a decompressed size of
761
+ ``PngImagePlugin.MAX_TEXT_CHUNK``, by default 1MB, to prevent
762
+ decompression bombs. Additionally, the total size of all of the text
763
+ chunks is limited to ``PngImagePlugin.MAX_TEXT_MEMORY``, defaulting to
764
+ 64MB.
765
+
766
+ The :py:meth:`~PIL.Image.Image.save` method supports the following options:
767
+
768
+ **optimize**
769
+ If present and true, instructs the PNG writer to make the output file as
770
+ small as possible. This includes extra processing in order to find optimal
771
+ encoder settings.
772
+
773
+ **transparency**
774
+ For ``P``, ``L``, and ``RGB`` images, this option controls what
775
+ color image to mark as transparent.
776
+
777
+ For ``P`` images, this can be a either the palette index,
778
+ or a byte string with alpha values for each palette entry.
779
+
780
+ **dpi**
781
+ A tuple of two numbers corresponding to the desired dpi in each direction.
782
+
783
+ **pnginfo**
784
+ A :py:class:`PIL.PngImagePlugin.PngInfo` instance containing text tags.
785
+
786
+ **compress_level**
787
+ ZLIB compression level, a number between 0 and 9: 1 gives best speed,
788
+ 9 gives best compression, 0 gives no compression at all. Default is 6.
789
+ When ``optimize`` option is True ``compress_level`` has no effect
790
+ (it is set to 9 regardless of a value passed).
791
+
792
+ **icc_profile**
793
+ The ICC Profile to include in the saved file.
794
+
795
+ **bits (experimental)**
796
+ For ``P`` images, this option controls how many bits to store. If omitted,
797
+ the PNG writer uses 8 bits (256 colors).
798
+
799
+ **dictionary (experimental)**
800
+ Set the ZLIB encoder dictionary.
801
+
802
+ .. note::
803
+
804
+ To enable PNG support, you need to build and install the ZLIB compression
805
+ library before building the Python Imaging Library. See the installation
806
+ documentation for details.
807
+ """,
808
+ "PPM": """*From the Pillow docs:*
809
+
810
+
811
+ PIL reads and writes PBM, PGM and PPM files containing ``1``, ``L`` or ``RGB``
812
+ data.
813
+ """,
814
+ "PSD": """*From the Pillow docs:*
815
+
816
+
817
+ PIL identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.
818
+
819
+ """,
820
+ "SGI": """*From the Pillow docs:*
821
+
822
+
823
+ Pillow reads and writes uncompressed ``L``, ``RGB``, and ``RGBA`` files.
824
+
825
+ """,
826
+ "SPIDER": """*From the Pillow docs:*
827
+
828
+
829
+ PIL reads and writes SPIDER image files of 32-bit floating point data
830
+ ("F;32F").
831
+
832
+ PIL also reads SPIDER stack files containing sequences of SPIDER images. The
833
+ :py:meth:`~file.seek` and :py:meth:`~file.tell` methods are supported, and
834
+ random access is allowed.
835
+
836
+ The :py:meth:`~PIL.Image.Image.write` method sets the following attributes:
837
+
838
+ **format**
839
+ Set to ``SPIDER``
840
+
841
+ **istack**
842
+ Set to 1 if the file is an image stack, else 0.
843
+
844
+ **nimages**
845
+ Set to the number of images in the stack.
846
+
847
+ A convenience method, :py:meth:`~PIL.Image.Image.convert2byte`, is provided for
848
+ converting floating point data to byte data (mode ``L``)::
849
+
850
+ im = Image.open('image001.spi').convert2byte()
851
+
852
+ Writing files in SPIDER format
853
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
854
+
855
+ The extension of SPIDER files may be any 3 alphanumeric characters. Therefore
856
+ the output format must be specified explicitly::
857
+
858
+ im.save('newimage.spi', format='SPIDER')
859
+
860
+ For more information about the SPIDER image processing package, see the
861
+ `SPIDER homepage`_ at `Wadsworth Center`_.
862
+
863
+ .. _SPIDER homepage: https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
864
+ .. _Wadsworth Center: https://www.wadsworth.org/
865
+ """,
866
+ "SUN": """No docs for SUN.""",
867
+ "TGA": """*From the Pillow docs:*
868
+
869
+
870
+ PIL reads 24- and 32-bit uncompressed and run-length encoded TGA files.
871
+ """,
872
+ "TIFF": """*From the Pillow docs:*
873
+
874
+
875
+ Pillow reads and writes TIFF files. It can read both striped and tiled
876
+ images, pixel and plane interleaved multi-band images. If you have
877
+ libtiff and its headers installed, PIL can read and write many kinds
878
+ of compressed TIFF files. If not, PIL will only read and write
879
+ uncompressed files.
880
+
881
+ .. note::
882
+
883
+ Beginning in version 5.0.0, Pillow requires libtiff to read or
884
+ write compressed files. Prior to that release, Pillow had buggy
885
+ support for reading Packbits, LZW and JPEG compressed TIFFs
886
+ without using libtiff.
887
+
888
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
889
+ :py:attr:`~PIL.Image.Image.info` properties:
890
+
891
+ **compression**
892
+ Compression mode.
893
+
894
+ .. versionadded:: Pillow 2.0.0
895
+
896
+ **dpi**
897
+ Image resolution as an ``(xdpi, ydpi)`` tuple, where applicable. You can use
898
+ the :py:attr:`~PIL.Image.Image.tag` attribute to get more detailed
899
+ information about the image resolution.
900
+
901
+ .. versionadded:: Pillow 1.1.5
902
+
903
+ **resolution**
904
+ Image resolution as an ``(xres, yres)`` tuple, where applicable. This is a
905
+ measurement in whichever unit is specified by the file.
906
+
907
+ .. versionadded:: Pillow 1.1.5
908
+
909
+
910
+ The :py:attr:`~PIL.Image.Image.tag_v2` attribute contains a dictionary
911
+ of TIFF metadata. The keys are numerical indexes from
912
+ :py:attr:`~PIL.TiffTags.TAGS_V2`. Values are strings or numbers for single
913
+ items, multiple values are returned in a tuple of values. Rational
914
+ numbers are returned as a :py:class:`~PIL.TiffImagePlugin.IFDRational`
915
+ object.
916
+
917
+ .. versionadded:: Pillow 3.0.0
918
+
919
+ For compatibility with legacy code, the
920
+ :py:attr:`~PIL.Image.Image.tag` attribute contains a dictionary of
921
+ decoded TIFF fields as returned prior to version 3.0.0. Values are
922
+ returned as either strings or tuples of numeric values. Rational
923
+ numbers are returned as a tuple of ``(numerator, denominator)``.
924
+
925
+ .. deprecated:: 3.0.0
926
+
927
+
928
+ Saving Tiff Images
929
+ ~~~~~~~~~~~~~~~~~~
930
+
931
+ The :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:
932
+
933
+ **save_all**
934
+ If true, Pillow will save all frames of the image to a multiframe tiff document.
935
+
936
+ .. versionadded:: Pillow 3.4.0
937
+
938
+ **tiffinfo**
939
+ A :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` object or dict
940
+ object containing tiff tags and values. The TIFF field type is
941
+ autodetected for Numeric and string values, any other types
942
+ require using an :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
943
+ object and setting the type in
944
+ :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` with
945
+ the appropriate numerical value from
946
+ ``TiffTags.TYPES``.
947
+
948
+ .. versionadded:: Pillow 2.3.0
949
+
950
+ Metadata values that are of the rational type should be passed in
951
+ using a :py:class:`~PIL.TiffImagePlugin.IFDRational` object.
952
+
953
+ .. versionadded:: Pillow 3.1.0
954
+
955
+ For compatibility with legacy code, a
956
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` object may
957
+ be passed in this field. However, this is deprecated.
958
+
959
+ .. versionadded:: Pillow 3.0.0
960
+
961
+ .. note::
962
+
963
+ Only some tags are currently supported when writing using
964
+ libtiff. The supported list is found in
965
+ :py:attr:`~PIL:TiffTags.LIBTIFF_CORE`.
966
+
967
+ **compression**
968
+ A string containing the desired compression method for the
969
+ file. (valid only with libtiff installed) Valid compression
970
+ methods are: ``None``, ``"tiff_ccitt"``, ``"group3"``,
971
+ ``"group4"``, ``"tiff_jpeg"``, ``"tiff_adobe_deflate"``,
972
+ ``"tiff_thunderscan"``, ``"tiff_deflate"``, ``"tiff_sgilog"``,
973
+ ``"tiff_sgilog24"``, ``"tiff_raw_16"``
974
+
975
+ These arguments to set the tiff header fields are an alternative to
976
+ using the general tags available through tiffinfo.
977
+
978
+ **description**
979
+
980
+ **software**
981
+
982
+ **date_time**
983
+
984
+ **artist**
985
+
986
+ **copyright**
987
+ Strings
988
+
989
+ **resolution_unit**
990
+ A string of "inch", "centimeter" or "cm"
991
+
992
+ **resolution**
993
+
994
+ **x_resolution**
995
+
996
+ **y_resolution**
997
+
998
+ **dpi**
999
+ Either a Float, 2 tuple of (numerator, denominator) or a
1000
+ :py:class:`~PIL.TiffImagePlugin.IFDRational`. Resolution implies
1001
+ an equal x and y resolution, dpi also implies a unit of inches.
1002
+
1003
+ """,
1004
+ "WMF": """*From the Pillow docs:*
1005
+
1006
+
1007
+ PIL can identify playable WMF files.
1008
+
1009
+ In PIL 1.1.4 and earlier, the WMF driver provides some limited rendering
1010
+ support, but not enough to be useful for any real application.
1011
+
1012
+ In PIL 1.1.5 and later, the WMF driver is a stub driver. To add WMF read or
1013
+ write support to your application, use
1014
+ :py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF handler.
1015
+
1016
+ ::
1017
+
1018
+ from PIL import Image
1019
+ from PIL import WmfImagePlugin
1020
+
1021
+ class WmfHandler:
1022
+ def open(self, im):
1023
+ ...
1024
+ def load(self, im):
1025
+ ...
1026
+ return image
1027
+ def save(self, im, fp, filename):
1028
+ ...
1029
+
1030
+ wmf_handler = WmfHandler()
1031
+
1032
+ WmfImagePlugin.register_handler(wmf_handler)
1033
+
1034
+ im = Image.open("sample.wmf")""",
1035
+ "XBM": """*From the Pillow docs:*
1036
+
1037
+
1038
+ PIL reads and writes X bitmap files (mode ``1``).
1039
+ """,
1040
+ "XPM": """*From the Pillow docs:*
1041
+
1042
+
1043
+ PIL reads X pixmap files (mode ``P``) with 256 colors or less.
1044
+
1045
+ The :py:meth:`~PIL.Image.Image.write` method sets the following
1046
+ :py:attr:`~PIL.Image.Image.info` properties:
1047
+
1048
+ **transparency**
1049
+ Transparency color index. This key is omitted if the image is not
1050
+ transparent.
1051
+ """,
1052
+ "XVThumb": """No docs for XVThumb.""",
1053
+ }
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/pillow_legacy.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write images using pillow/PIL (legacy).
5
+
6
+ Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_
7
+
8
+ Pillow is a friendly fork of PIL (Python Image Library) and supports
9
+ reading and writing of common formats (jpg, png, gif, tiff, ...). While
10
+ these docs provide an overview of some of its features, pillow is
11
+ constantly improving. Hence, the complete list of features can be found
12
+ in pillows official docs (see the Backend Library link).
13
+
14
+ Parameters for Reading
15
+ ----------------------
16
+ pilmode : str
17
+ (Available for all formats except GIF-PIL)
18
+ From the Pillow documentation:
19
+
20
+ * 'L' (8-bit pixels, grayscale)
21
+ * 'P' (8-bit pixels, mapped to any other mode using a color palette)
22
+ * 'RGB' (3x8-bit pixels, true color)
23
+ * 'RGBA' (4x8-bit pixels, true color with transparency mask)
24
+ * 'CMYK' (4x8-bit pixels, color separation)
25
+ * 'YCbCr' (3x8-bit pixels, color video format)
26
+ * 'I' (32-bit signed integer pixels)
27
+ * 'F' (32-bit floating point pixels)
28
+
29
+ PIL also provides limited support for a few special modes, including
30
+ 'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
31
+ (true color with premultiplied alpha).
32
+
33
+ When translating a color image to grayscale (mode 'L', 'I' or 'F'),
34
+ the library uses the ITU-R 601-2 luma transform::
35
+
36
+ L = R * 299/1000 + G * 587/1000 + B * 114/1000
37
+ as_gray : bool
38
+ (Available for all formats except GIF-PIL)
39
+ If True, the image is converted using mode 'F'. When `mode` is
40
+ not None and `as_gray` is True, the image is first converted
41
+ according to `mode`, and the result is then "flattened" using
42
+ mode 'F'.
43
+ ignoregamma : bool
44
+ (Only available in PNG-PIL)
45
+ Avoid gamma correction. Default True.
46
+ exifrotate : bool
47
+ (Only available in JPEG-PIL)
48
+ Automatically rotate the image according to exif flag. Default True.
49
+
50
+
51
+ Parameters for saving
52
+ ---------------------
53
+ optimize : bool
54
+ (Only available in PNG-PIL)
55
+ If present and true, instructs the PNG writer to make the output file
56
+ as small as possible. This includes extra processing in order to find
57
+ optimal encoder settings.
58
+ transparency:
59
+ (Only available in PNG-PIL)
60
+ This option controls what color image to mark as transparent.
61
+ dpi: tuple of two scalars
62
+ (Only available in PNG-PIL)
63
+ The desired dpi in each direction.
64
+ pnginfo: PIL.PngImagePlugin.PngInfo
65
+ (Only available in PNG-PIL)
66
+ Object containing text tags.
67
+ compress_level: int
68
+ (Only available in PNG-PIL)
69
+ ZLIB compression level, a number between 0 and 9: 1 gives best speed,
70
+ 9 gives best compression, 0 gives no compression at all. Default is 9.
71
+ When ``optimize`` option is True ``compress_level`` has no effect
72
+ (it is set to 9 regardless of a value passed).
73
+ compression: int
74
+ (Only available in PNG-PIL)
75
+ Compatibility with the freeimage PNG format. If given, it overrides
76
+ compress_level.
77
+ icc_profile:
78
+ (Only available in PNG-PIL)
79
+ The ICC Profile to include in the saved file.
80
+ bits (experimental): int
81
+ (Only available in PNG-PIL)
82
+ This option controls how many bits to store. If omitted,
83
+ the PNG writer uses 8 bits (256 colors).
84
+ quantize:
85
+ (Only available in PNG-PIL)
86
+ Compatibility with the freeimage PNG format. If given, it overrides
87
+ bits. In this case, given as a number between 1-256.
88
+ dictionary (experimental): dict
89
+ (Only available in PNG-PIL)
90
+ Set the ZLIB encoder dictionary.
91
+ prefer_uint8: bool
92
+ (Only available in PNG-PIL)
93
+ Let the PNG writer truncate uint16 image arrays to uint8 if their values fall
94
+ within the range [0, 255]. Defaults to true for legacy compatibility, however
95
+ it is recommended to set this to false to avoid unexpected behavior when
96
+ saving e.g. weakly saturated images.
97
+
98
+ quality : scalar
99
+ (Only available in JPEG-PIL)
100
+ The compression factor of the saved image (1..100), higher
101
+ numbers result in higher quality but larger file size. Default 75.
102
+ progressive : bool
103
+ (Only available in JPEG-PIL)
104
+ Save as a progressive JPEG file (e.g. for images on the web).
105
+ Default False.
106
+ optimize : bool
107
+ (Only available in JPEG-PIL)
108
+ On saving, compute optimal Huffman coding tables (can reduce a few
109
+ percent of file size). Default False.
110
+ dpi : tuple of int
111
+ (Only available in JPEG-PIL)
112
+ The pixel density, ``(x,y)``.
113
+ icc_profile : object
114
+ (Only available in JPEG-PIL)
115
+ If present and true, the image is stored with the provided ICC profile.
116
+ If this parameter is not provided, the image will be saved with no
117
+ profile attached.
118
+ exif : dict
119
+ (Only available in JPEG-PIL)
120
+ If present, the image will be stored with the provided raw EXIF data.
121
+ subsampling : str
122
+ (Only available in JPEG-PIL)
123
+ Sets the subsampling for the encoder. See Pillow docs for details.
124
+ qtables : object
125
+ (Only available in JPEG-PIL)
126
+ Set the qtables for the encoder. See Pillow docs for details.
127
+ quality_mode : str
128
+ (Only available in JPEG2000-PIL)
129
+ Either `"rates"` or `"dB"` depending on the units you want to use to
130
+ specify image quality.
131
+ quality : float
132
+ (Only available in JPEG2000-PIL)
133
+ Approximate size reduction (if quality mode is `rates`) or a signal to noise ratio
134
+ in decibels (if quality mode is `dB`).
135
+ loop : int
136
+ (Only available in GIF-PIL)
137
+ The number of iterations. Default 0 (meaning loop indefinitely).
138
+ duration : {float, list}
139
+ (Only available in GIF-PIL)
140
+ The duration (in milliseconds) of each frame. Either specify one value
141
+ that is used for all frames, or one value for each frame.
142
+ fps : float
143
+ (Only available in GIF-PIL)
144
+ The number of frames per second. If duration is not given, the
145
+ duration for each frame is set to 1/fps. Default 10.
146
+ palettesize : int
147
+ (Only available in GIF-PIL)
148
+ The number of colors to quantize the image to. Is rounded to
149
+ the nearest power of two. Default 256.
150
+ subrectangles : bool
151
+ (Only available in GIF-PIL)
152
+ If True, will try and optimize the GIF by storing only the
153
+ rectangular parts of each frame that change with respect to the
154
+ previous. Default False.
155
+
156
+ Notes
157
+ -----
158
+ To enable JPEG 2000 support, you need to build and install the OpenJPEG library,
159
+ version 2.0.0 or higher, before building the Python Imaging Library. Windows
160
+ users can install the OpenJPEG binaries available on the OpenJPEG website, but
161
+ must add them to their PATH in order to use PIL (if you fail to do this, you
162
+ will get errors about not being able to load the ``_imaging`` DLL).
163
+
164
+ GIF images read with this plugin are always RGBA. The alpha channel is ignored
165
+ when saving RGB images.
166
+ """
167
+
168
+ import logging
169
+ import threading
170
+
171
+ import numpy as np
172
+
173
+ from ..core import Format, image_as_uint
174
+ from ..core.request import URI_FILE, URI_BYTES
175
+
176
+
177
+ logger = logging.getLogger(__name__)
178
+
179
+
180
+ # todo: Pillow ImageGrab module supports grabbing the screen on Win and OSX.
181
+
182
+
183
+ GENERIC_DOCS = """
184
+ Parameters for reading
185
+ ----------------------
186
+
187
+ pilmode : str
188
+ From the Pillow documentation:
189
+
190
+ * 'L' (8-bit pixels, grayscale)
191
+ * 'P' (8-bit pixels, mapped to any other mode using a color palette)
192
+ * 'RGB' (3x8-bit pixels, true color)
193
+ * 'RGBA' (4x8-bit pixels, true color with transparency mask)
194
+ * 'CMYK' (4x8-bit pixels, color separation)
195
+ * 'YCbCr' (3x8-bit pixels, color video format)
196
+ * 'I' (32-bit signed integer pixels)
197
+ * 'F' (32-bit floating point pixels)
198
+
199
+ PIL also provides limited support for a few special modes, including
200
+ 'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
201
+ (true color with premultiplied alpha).
202
+
203
+ When translating a color image to grayscale (mode 'L', 'I' or 'F'),
204
+ the library uses the ITU-R 601-2 luma transform::
205
+
206
+ L = R * 299/1000 + G * 587/1000 + B * 114/1000
207
+ as_gray : bool
208
+ If True, the image is converted using mode 'F'. When `mode` is
209
+ not None and `as_gray` is True, the image is first converted
210
+ according to `mode`, and the result is then "flattened" using
211
+ mode 'F'.
212
+ """
213
+
214
+
215
+ class PillowFormat(Format):
216
+ """
217
+ Base format class for Pillow formats.
218
+ """
219
+
220
+ _pillow_imported = False
221
+ _Image = None
222
+ _modes = "i"
223
+ _description = ""
224
+
225
+ def __init__(self, *args, plugin_id: str = None, **kwargs):
226
+ super(PillowFormat, self).__init__(*args, **kwargs)
227
+ # Used to synchronize _init_pillow(), see #244
228
+ self._lock = threading.RLock()
229
+
230
+ self._plugin_id = plugin_id
231
+
232
+ @property
233
+ def plugin_id(self):
234
+ """The PIL plugin id."""
235
+ return self._plugin_id # Set when format is created
236
+
237
+ def _init_pillow(self):
238
+ with self._lock:
239
+ if not self._pillow_imported:
240
+ self._pillow_imported = True # more like tried to import
241
+ import PIL
242
+
243
+ if not hasattr(PIL, "__version__"): # pragma: no cover
244
+ raise ImportError(
245
+ "Imageio Pillow plugin requires " "Pillow, not PIL!"
246
+ )
247
+ from PIL import Image
248
+
249
+ self._Image = Image
250
+ elif self._Image is None: # pragma: no cover
251
+ raise RuntimeError("Imageio Pillow plugin requires " "Pillow lib.")
252
+ Image = self._Image
253
+
254
+ if self.plugin_id in ("PNG", "JPEG", "BMP", "GIF", "PPM"):
255
+ Image.preinit()
256
+ else:
257
+ Image.init()
258
+ return Image
259
+
260
+ def _can_read(self, request):
261
+ Image = self._init_pillow()
262
+ if self.plugin_id in Image.OPEN:
263
+ factory, accept = Image.OPEN[self.plugin_id]
264
+ if accept:
265
+ if request.firstbytes and accept(request.firstbytes):
266
+ return True
267
+
268
+ def _can_write(self, request):
269
+ Image = self._init_pillow()
270
+ if request.extension in self.extensions or request._uri_type in [
271
+ URI_FILE,
272
+ URI_BYTES,
273
+ ]:
274
+ if self.plugin_id in Image.SAVE:
275
+ return True
276
+
277
+ class Reader(Format.Reader):
278
+ def _open(self, pilmode=None, as_gray=False):
279
+ Image = self.format._init_pillow()
280
+ try:
281
+ factory, accept = Image.OPEN[self.format.plugin_id]
282
+ except KeyError:
283
+ raise RuntimeError("Format %s cannot read images." % self.format.name)
284
+ self._fp = self._get_file()
285
+ self._im = factory(self._fp, "")
286
+ if hasattr(Image, "_decompression_bomb_check"):
287
+ Image._decompression_bomb_check(self._im.size)
288
+ # Save the raw mode used by the palette for a BMP because it may not be the number of channels
289
+ # When the data is read, imageio hands the palette to PIL to handle and clears the rawmode argument
290
+ # However, there is a bug in PIL with handling animated GIFs with a different color palette on each frame.
291
+ # This issue is resolved by using the raw palette data but the rawmode information is now lost. So we
292
+ # store the raw mode for later use
293
+ if self._im.palette and self._im.palette.dirty:
294
+ self._im.palette.rawmode_saved = self._im.palette.rawmode
295
+ pil_try_read(self._im)
296
+ # Store args
297
+ self._kwargs = dict(
298
+ as_gray=as_gray, is_gray=_palette_is_grayscale(self._im)
299
+ )
300
+ # setting mode=None is not the same as just not providing it
301
+ if pilmode is not None:
302
+ self._kwargs["mode"] = pilmode
303
+ # Set length
304
+ self._length = 1
305
+ if hasattr(self._im, "n_frames"):
306
+ self._length = self._im.n_frames
307
+
308
+ def _get_file(self):
309
+ self._we_own_fp = False
310
+ return self.request.get_file()
311
+
312
+ def _close(self):
313
+ save_pillow_close(self._im)
314
+ if self._we_own_fp:
315
+ self._fp.close()
316
+ # else: request object handles closing the _fp
317
+
318
+ def _get_length(self):
319
+ return self._length
320
+
321
+ def _seek(self, index):
322
+ try:
323
+ self._im.seek(index)
324
+ except EOFError:
325
+ raise IndexError("Could not seek to index %i" % index)
326
+
327
+ def _get_data(self, index):
328
+ if index >= self._length:
329
+ raise IndexError("Image index %i > %i" % (index, self._length))
330
+ i = self._im.tell()
331
+ if i > index:
332
+ self._seek(index) # just try
333
+ else:
334
+ while i < index: # some formats need to be read in sequence
335
+ i += 1
336
+ self._seek(i)
337
+ if self._im.palette and self._im.palette.dirty:
338
+ self._im.palette.rawmode_saved = self._im.palette.rawmode
339
+ self._im.getdata()[0]
340
+ im = pil_get_frame(self._im, **self._kwargs)
341
+ return im, self._im.info
342
+
343
+ def _get_meta_data(self, index):
344
+ if not (index is None or index == 0):
345
+ raise IndexError()
346
+ return self._im.info
347
+
348
+ class Writer(Format.Writer):
349
+ def _open(self):
350
+ Image = self.format._init_pillow()
351
+ try:
352
+ self._save_func = Image.SAVE[self.format.plugin_id]
353
+ except KeyError:
354
+ raise RuntimeError("Format %s cannot write images." % self.format.name)
355
+ self._fp = self.request.get_file()
356
+ self._meta = {}
357
+ self._written = False
358
+
359
+ def _close(self):
360
+ pass # request object handled closing _fp
361
+
362
+ def _append_data(self, im, meta):
363
+ if self._written:
364
+ raise RuntimeError(
365
+ "Format %s only supports single images." % self.format.name
366
+ )
367
+ # Pop unit dimension for grayscale images
368
+ if im.ndim == 3 and im.shape[-1] == 1:
369
+ im = im[:, :, 0]
370
+ self._written = True
371
+ self._meta.update(meta)
372
+ img = ndarray_to_pil(
373
+ im, self.format.plugin_id, self._meta.pop("prefer_uint8", True)
374
+ )
375
+ if "bits" in self._meta:
376
+ img = img.quantize() # Make it a P image, so bits arg is used
377
+ img.save(self._fp, format=self.format.plugin_id, **self._meta)
378
+ save_pillow_close(img)
379
+
380
+ def set_meta_data(self, meta):
381
+ self._meta.update(meta)
382
+
383
+
384
+ class PNGFormat(PillowFormat):
385
+ """See :mod:`imageio.plugins.pillow_legacy`"""
386
+
387
+ class Reader(PillowFormat.Reader):
388
+ def _open(self, pilmode=None, as_gray=False, ignoregamma=True):
389
+ return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
390
+
391
+ def _get_data(self, index):
392
+ im, info = PillowFormat.Reader._get_data(self, index)
393
+ if not self.request.kwargs.get("ignoregamma", True):
394
+ # The gamma value in the file represents the gamma factor for the
395
+ # hardware on the system where the file was created, and is meant
396
+ # to be able to match the colors with the system on which the
397
+ # image is shown. See also issue #366
398
+ try:
399
+ gamma = float(info["gamma"])
400
+ except (KeyError, ValueError):
401
+ pass
402
+ else:
403
+ scale = float(65536 if im.dtype == np.uint16 else 255)
404
+ gain = 1.0
405
+ im[:] = ((im / scale) ** gamma) * scale * gain + 0.4999
406
+ return im, info
407
+
408
+ # --
409
+
410
+ class Writer(PillowFormat.Writer):
411
+ def _open(self, compression=None, quantize=None, interlaced=False, **kwargs):
412
+ # Better default for compression
413
+ kwargs["compress_level"] = kwargs.get("compress_level", 9)
414
+
415
+ if compression is not None:
416
+ if compression < 0 or compression > 9:
417
+ raise ValueError("Invalid PNG compression level: %r" % compression)
418
+ kwargs["compress_level"] = compression
419
+ if quantize is not None:
420
+ for bits in range(1, 9):
421
+ if 2**bits == quantize:
422
+ break
423
+ else:
424
+ raise ValueError(
425
+ "PNG quantize must be power of two, " "not %r" % quantize
426
+ )
427
+ kwargs["bits"] = bits
428
+ if interlaced:
429
+ logger.warning("PIL PNG writer cannot produce interlaced images.")
430
+
431
+ ok_keys = (
432
+ "optimize",
433
+ "transparency",
434
+ "dpi",
435
+ "pnginfo",
436
+ "bits",
437
+ "compress_level",
438
+ "icc_profile",
439
+ "dictionary",
440
+ "prefer_uint8",
441
+ )
442
+ for key in kwargs:
443
+ if key not in ok_keys:
444
+ raise TypeError("Invalid arg for PNG writer: %r" % key)
445
+
446
+ PillowFormat.Writer._open(self)
447
+ self._meta.update(kwargs)
448
+
449
+ def _append_data(self, im, meta):
450
+ if str(im.dtype) == "uint16" and (im.ndim == 2 or im.shape[-1] == 1):
451
+ im = image_as_uint(im, bitdepth=16)
452
+ else:
453
+ im = image_as_uint(im, bitdepth=8)
454
+ PillowFormat.Writer._append_data(self, im, meta)
455
+
456
+
457
+ class JPEGFormat(PillowFormat):
458
+ """See :mod:`imageio.plugins.pillow_legacy`"""
459
+
460
+ class Reader(PillowFormat.Reader):
461
+ def _open(self, pilmode=None, as_gray=False, exifrotate=True):
462
+ return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
463
+
464
+ def _get_file(self):
465
+ # Pillow uses seek for JPG, so we cannot directly stream from web
466
+ if self.request.filename.startswith(
467
+ ("http://", "https://")
468
+ ) or ".zip/" in self.request.filename.replace("\\", "/"):
469
+ self._we_own_fp = True
470
+ return open(self.request.get_local_filename(), "rb")
471
+ else:
472
+ self._we_own_fp = False
473
+ return self.request.get_file()
474
+
475
+ def _get_data(self, index):
476
+ im, info = PillowFormat.Reader._get_data(self, index)
477
+
478
+ # Handle exif
479
+ if "exif" in info:
480
+ from PIL.ExifTags import TAGS
481
+
482
+ info["EXIF_MAIN"] = {}
483
+ for tag, value in self._im._getexif().items():
484
+ decoded = TAGS.get(tag, tag)
485
+ info["EXIF_MAIN"][decoded] = value
486
+
487
+ im = self._rotate(im, info)
488
+ return im, info
489
+
490
+ def _rotate(self, im, meta):
491
+ """Use Orientation information from EXIF meta data to
492
+ orient the image correctly. Similar code as in FreeImage plugin.
493
+ """
494
+ if self.request.kwargs.get("exifrotate", True):
495
+ try:
496
+ ori = meta["EXIF_MAIN"]["Orientation"]
497
+ except KeyError: # pragma: no cover
498
+ pass # Orientation not available
499
+ else: # pragma: no cover - we cannot touch all cases
500
+ # www.impulseadventure.com/photo/exif-orientation.html
501
+ if ori in [1, 2]:
502
+ pass
503
+ if ori in [3, 4]:
504
+ im = np.rot90(im, 2)
505
+ if ori in [5, 6]:
506
+ im = np.rot90(im, 3)
507
+ if ori in [7, 8]:
508
+ im = np.rot90(im)
509
+ if ori in [2, 4, 5, 7]: # Flipped cases (rare)
510
+ im = np.fliplr(im)
511
+ return im
512
+
513
+ # --
514
+
515
+ class Writer(PillowFormat.Writer):
516
+ def _open(self, quality=75, progressive=False, optimize=False, **kwargs):
517
+ # The JPEG quality can be between 0 (worst) and 100 (best)
518
+ quality = int(quality)
519
+ if quality < 0 or quality > 100:
520
+ raise ValueError("JPEG quality should be between 0 and 100.")
521
+
522
+ kwargs["quality"] = quality
523
+ kwargs["progressive"] = bool(progressive)
524
+ kwargs["optimize"] = bool(progressive)
525
+
526
+ PillowFormat.Writer._open(self)
527
+ self._meta.update(kwargs)
528
+
529
+ def _append_data(self, im, meta):
530
+ if im.ndim == 3 and im.shape[-1] == 4:
531
+ raise IOError("JPEG does not support alpha channel.")
532
+ im = image_as_uint(im, bitdepth=8)
533
+ PillowFormat.Writer._append_data(self, im, meta)
534
+ return
535
+
536
+
537
+ class JPEG2000Format(PillowFormat):
538
+ """See :mod:`imageio.plugins.pillow_legacy`"""
539
+
540
+ class Reader(PillowFormat.Reader):
541
+ def _open(self, pilmode=None, as_gray=False):
542
+ return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
543
+
544
+ def _get_file(self):
545
+ # Pillow uses seek for JPG, so we cannot directly stream from web
546
+ if self.request.filename.startswith(
547
+ ("http://", "https://")
548
+ ) or ".zip/" in self.request.filename.replace("\\", "/"):
549
+ self._we_own_fp = True
550
+ return open(self.request.get_local_filename(), "rb")
551
+ else:
552
+ self._we_own_fp = False
553
+ return self.request.get_file()
554
+
555
+ def _get_data(self, index):
556
+ im, info = PillowFormat.Reader._get_data(self, index)
557
+
558
+ # Handle exif
559
+ if "exif" in info:
560
+ from PIL.ExifTags import TAGS
561
+
562
+ info["EXIF_MAIN"] = {}
563
+ for tag, value in self._im._getexif().items():
564
+ decoded = TAGS.get(tag, tag)
565
+ info["EXIF_MAIN"][decoded] = value
566
+
567
+ im = self._rotate(im, info)
568
+ return im, info
569
+
570
+ def _rotate(self, im, meta):
571
+ """Use Orientation information from EXIF meta data to
572
+ orient the image correctly. Similar code as in FreeImage plugin.
573
+ """
574
+ if self.request.kwargs.get("exifrotate", True):
575
+ try:
576
+ ori = meta["EXIF_MAIN"]["Orientation"]
577
+ except KeyError: # pragma: no cover
578
+ pass # Orientation not available
579
+ else: # pragma: no cover - we cannot touch all cases
580
+ # www.impulseadventure.com/photo/exif-orientation.html
581
+ if ori in [1, 2]:
582
+ pass
583
+ if ori in [3, 4]:
584
+ im = np.rot90(im, 2)
585
+ if ori in [5, 6]:
586
+ im = np.rot90(im, 3)
587
+ if ori in [7, 8]:
588
+ im = np.rot90(im)
589
+ if ori in [2, 4, 5, 7]: # Flipped cases (rare)
590
+ im = np.fliplr(im)
591
+ return im
592
+
593
+ # --
594
+
595
+ class Writer(PillowFormat.Writer):
596
+ def _open(self, quality_mode="rates", quality=5, **kwargs):
597
+ # Check quality - in Pillow it should be no higher than 95
598
+ if quality_mode not in {"rates", "dB"}:
599
+ raise ValueError("Quality mode should be either 'rates' or 'dB'")
600
+
601
+ quality = float(quality)
602
+
603
+ if quality_mode == "rates" and (quality < 1 or quality > 1000):
604
+ raise ValueError(
605
+ "The quality value {} seems to be an invalid rate!".format(quality)
606
+ )
607
+ elif quality_mode == "dB" and (quality < 15 or quality > 100):
608
+ raise ValueError(
609
+ "The quality value {} seems to be an invalid PSNR!".format(quality)
610
+ )
611
+
612
+ kwargs["quality_mode"] = quality_mode
613
+ kwargs["quality_layers"] = [quality]
614
+
615
+ PillowFormat.Writer._open(self)
616
+ self._meta.update(kwargs)
617
+
618
+ def _append_data(self, im, meta):
619
+ if im.ndim == 3 and im.shape[-1] == 4:
620
+ raise IOError(
621
+ "The current implementation of JPEG 2000 does not support alpha channel."
622
+ )
623
+ im = image_as_uint(im, bitdepth=8)
624
+ PillowFormat.Writer._append_data(self, im, meta)
625
+ return
626
+
627
+
628
+ def save_pillow_close(im):
629
+ # see issue #216 and #300
630
+ if hasattr(im, "close"):
631
+ if hasattr(getattr(im, "fp", None), "close"):
632
+ im.close()
633
+
634
+
635
+ # Func from skimage
636
+
637
+ # This cells contains code from scikit-image, in particular from
638
+ # http://github.com/scikit-image/scikit-image/blob/master/
639
+ # skimage/io/_plugins/pil_plugin.py
640
+ # The scikit-image license applies.
641
+
642
+
643
+ def pil_try_read(im):
644
+ try:
645
+ # this will raise an IOError if the file is not readable
646
+ im.getdata()[0]
647
+ except IOError as e:
648
+ site = "http://pillow.readthedocs.io/en/latest/installation.html"
649
+ site += "#external-libraries"
650
+ pillow_error_message = str(e)
651
+ error_message = (
652
+ 'Could not load "%s" \n'
653
+ 'Reason: "%s"\n'
654
+ "Please see documentation at: %s"
655
+ % (im.filename, pillow_error_message, site)
656
+ )
657
+ raise ValueError(error_message)
658
+
659
+
660
+ def _palette_is_grayscale(pil_image):
661
+ if pil_image.mode != "P":
662
+ return False
663
+ elif pil_image.info.get("transparency", None): # see issue #475
664
+ return False
665
+ # get palette as an array with R, G, B columns
666
+ # Note: starting in pillow 9.1 palettes may have less than 256 entries
667
+ palette = np.asarray(pil_image.getpalette()).reshape((-1, 3))
668
+ # Not all palette colors are used; unused colors have junk values.
669
+ start, stop = pil_image.getextrema()
670
+ valid_palette = palette[start : stop + 1]
671
+ # Image is grayscale if channel differences (R - G and G - B)
672
+ # are all zero.
673
+ return np.allclose(np.diff(valid_palette), 0)
674
+
675
+
676
+ def pil_get_frame(im, is_gray=None, as_gray=None, mode=None, dtype=None):
677
+ """
678
+ is_gray: Whether the image *is* gray (by inspecting its palette).
679
+ as_gray: Whether the resulting image must be converted to gaey.
680
+ mode: The mode to convert to.
681
+ """
682
+
683
+ if is_gray is None:
684
+ is_gray = _palette_is_grayscale(im)
685
+
686
+ frame = im
687
+
688
+ # Convert ...
689
+ if mode is not None:
690
+ # Mode is explicitly given ...
691
+ if mode != im.mode:
692
+ frame = im.convert(mode)
693
+ elif as_gray:
694
+ pass # don't do any auto-conversions (but do the explicit one above)
695
+ elif im.mode == "P" and is_gray:
696
+ # Paletted images that are already gray by their palette
697
+ # are converted so that the resulting numpy array is 2D.
698
+ frame = im.convert("L")
699
+ elif im.mode == "P":
700
+ # Paletted images are converted to RGB/RGBA. We jump some loops to make
701
+ # this work well.
702
+ if im.info.get("transparency", None) is not None:
703
+ # Let Pillow apply the transparency, see issue #210 and #246
704
+ frame = im.convert("RGBA")
705
+ elif im.palette.mode in ("RGB", "RGBA"):
706
+ # We can do this ourselves. Pillow seems to sometimes screw
707
+ # this up if a multi-gif has a palette for each frame ...
708
+ # Create palette array
709
+ p = np.frombuffer(im.palette.getdata()[1], np.uint8)
710
+ # Restore the raw mode that was saved to be used to parse the palette
711
+ if hasattr(im.palette, "rawmode_saved"):
712
+ im.palette.rawmode = im.palette.rawmode_saved
713
+ mode = im.palette.rawmode if im.palette.rawmode else im.palette.mode
714
+ nchannels = len(mode)
715
+ # Shape it.
716
+ p.shape = -1, nchannels
717
+ if p.shape[1] == 3 or (p.shape[1] == 4 and mode[-1] == "X"):
718
+ p = np.column_stack((p[:, :3], 255 * np.ones(p.shape[0], p.dtype)))
719
+ # Swap the axes if the mode is in BGR and not RGB
720
+ if mode.startswith("BGR"):
721
+ p = p[:, [2, 1, 0]] if p.shape[1] == 3 else p[:, [2, 1, 0, 3]]
722
+ # Apply palette
723
+ frame_paletted = np.array(im, np.uint8)
724
+ try:
725
+ frame = p[frame_paletted]
726
+ except Exception:
727
+ # Ok, let PIL do it. The introduction of the branch that
728
+ # tests `im.info['transparency']` should make this happen
729
+ # much less often, but let's keep it, to be safe.
730
+ frame = im.convert("RGBA")
731
+ else:
732
+ # Let Pillow do it. Unlinke skimage, we always convert
733
+ # to RGBA; palettes can be RGBA.
734
+ if True: # im.format == 'PNG' and 'transparency' in im.info:
735
+ frame = im.convert("RGBA")
736
+ else:
737
+ frame = im.convert("RGB")
738
+ elif "A" in im.mode:
739
+ frame = im.convert("RGBA")
740
+ elif im.mode == "CMYK":
741
+ frame = im.convert("RGB")
742
+ elif im.format == "GIF" and im.mode == "RGB":
743
+ # pillow9 returns RGBA images for subsequent frames so that it can deal
744
+ # with multi-frame GIF that use frame-level palettes and don't dispose
745
+ # all areas.
746
+
747
+ # For backwards compatibility, we promote everything to RGBA.
748
+ frame = im.convert("RGBA")
749
+
750
+ # Apply a post-convert if necessary
751
+ if as_gray:
752
+ frame = frame.convert("F") # Scipy compat
753
+ elif not isinstance(frame, np.ndarray) and frame.mode == "1":
754
+ # Workaround for crash in PIL. When im is 1-bit, the call array(im)
755
+ # can cause a segfault, or generate garbage. See
756
+ # https://github.com/scipy/scipy/issues/2138 and
757
+ # https://github.com/python-pillow/Pillow/issues/350.
758
+ #
759
+ # This converts im from a 1-bit image to an 8-bit image.
760
+ frame = frame.convert("L")
761
+
762
+ # Convert to numpy array
763
+ if im.mode.startswith("I;16"):
764
+ # e.g. in16 PNG's
765
+ shape = im.size
766
+ dtype = ">u2" if im.mode.endswith("B") else "<u2"
767
+ if "S" in im.mode:
768
+ dtype = dtype.replace("u", "i")
769
+ frame = np.frombuffer(frame.tobytes(), dtype).copy()
770
+ frame.shape = shape[::-1]
771
+ else:
772
+ # Use uint16 for PNG's in mode I
773
+ if im.format == "PNG" and im.mode == "I" and dtype is None:
774
+ dtype = "uint16"
775
+ frame = np.array(frame, dtype=dtype)
776
+
777
+ return frame
778
+
779
+
780
+ def ndarray_to_pil(arr, format_str=None, prefer_uint8=True):
781
+ from PIL import Image
782
+
783
+ if arr.ndim == 3:
784
+ arr = image_as_uint(arr, bitdepth=8)
785
+ mode = {3: "RGB", 4: "RGBA"}[arr.shape[2]]
786
+
787
+ elif format_str in ["png", "PNG"]:
788
+ mode = "I;16"
789
+ mode_base = "I"
790
+
791
+ if arr.dtype.kind == "f":
792
+ arr = image_as_uint(arr)
793
+
794
+ elif prefer_uint8 and arr.max() < 256 and arr.min() >= 0:
795
+ arr = arr.astype(np.uint8)
796
+ mode = mode_base = "L"
797
+
798
+ else:
799
+ arr = image_as_uint(arr, bitdepth=16)
800
+
801
+ else:
802
+ arr = image_as_uint(arr, bitdepth=8)
803
+ mode = "L"
804
+ mode_base = "L"
805
+
806
+ if mode == "I;16" and int(getattr(Image, "__version__", "0").split(".")[0]) < 6:
807
+ # Pillow < v6.0.0 has limited support for the "I;16" mode,
808
+ # requiring us to fall back to this expensive workaround.
809
+ # tobytes actually creates a copy of the image, which is costly.
810
+ array_buffer = arr.tobytes()
811
+ if arr.ndim == 2:
812
+ im = Image.new(mode_base, arr.T.shape)
813
+ im.frombytes(array_buffer, "raw", mode)
814
+ else:
815
+ image_shape = (arr.shape[1], arr.shape[0])
816
+ im = Image.frombytes(mode, image_shape, array_buffer)
817
+ return im
818
+ else:
819
+ return Image.fromarray(arr, mode)
820
+
821
+
822
+ # imported for backwards compatibility
823
+ from .pillowmulti import GIFFormat, TIFFFormat # noqa: E402, F401
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/simpleitk.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write images using SimpleITK.
5
+
6
+ Backend: `Insight Toolkit <https://itk.org/>`_
7
+
8
+ .. note::
9
+ To use this plugin you have to install its backend::
10
+
11
+ pip install imageio[itk]
12
+
13
+ The ItkFormat uses the ITK or SimpleITK library to support a range of
14
+ ITK-related formats. It also supports a few common formats (e.g. PNG and JPEG).
15
+
16
+ Parameters
17
+ ----------
18
+ None
19
+
20
+ """
21
+
22
+ from ..core import Format, has_module
23
+
24
+ _itk = None # Defer loading to load_lib() function.
25
+
26
+
27
+ def load_lib():
28
+ global _itk, _read_function, _write_function
29
+ try:
30
+ import itk as _itk
31
+
32
+ _read_function = _itk.imread
33
+ _write_function = _itk.imwrite
34
+ except ImportError:
35
+ try:
36
+ import SimpleITK as _itk
37
+
38
+ _read_function = _itk.ReadImage
39
+ _write_function = _itk.WriteImage
40
+ except ImportError:
41
+ raise ImportError(
42
+ "itk could not be found. "
43
+ "Please try "
44
+ " python -m pip install itk "
45
+ "or "
46
+ " python -m pip install simpleitk "
47
+ "or refer to "
48
+ " https://itkpythonpackage.readthedocs.io/ "
49
+ "for further instructions."
50
+ )
51
+ return _itk
52
+
53
+
54
+ # Split up in real ITK and all supported formats.
55
+ ITK_FORMATS = (
56
+ ".gipl",
57
+ ".ipl",
58
+ ".mha",
59
+ ".mhd",
60
+ ".nhdr",
61
+ "nia",
62
+ "hdr",
63
+ ".nrrd",
64
+ ".nii",
65
+ ".nii.gz",
66
+ ".img",
67
+ ".img.gz",
68
+ ".vtk",
69
+ "hdf5",
70
+ "lsm",
71
+ "mnc",
72
+ "mnc2",
73
+ "mgh",
74
+ "mnc",
75
+ "pic",
76
+ )
77
+ ALL_FORMATS = ITK_FORMATS + (
78
+ ".bmp",
79
+ ".jpeg",
80
+ ".jpg",
81
+ ".png",
82
+ ".tiff",
83
+ ".tif",
84
+ ".dicom",
85
+ ".dcm",
86
+ ".gdcm",
87
+ )
88
+
89
+
90
+ class ItkFormat(Format):
91
+ """See :mod:`imageio.plugins.simpleitk`"""
92
+
93
+ def _can_read(self, request):
94
+ # If the request is a format that only this plugin can handle,
95
+ # we report that we can do it; a useful error will be raised
96
+ # when simpleitk is not installed. For the more common formats
97
+ # we only report that we can read if the library is installed.
98
+ if request.extension in ITK_FORMATS:
99
+ return True
100
+ if has_module("itk.ImageIOBase") or has_module("SimpleITK"):
101
+ return request.extension in ALL_FORMATS
102
+
103
+ def _can_write(self, request):
104
+ if request.extension in ITK_FORMATS:
105
+ return True
106
+ if has_module("itk.ImageIOBase") or has_module("SimpleITK"):
107
+ return request.extension in ALL_FORMATS
108
+
109
+ # -- reader
110
+
111
+ class Reader(Format.Reader):
112
+ def _open(self, pixel_type=None, fallback_only=None, **kwargs):
113
+ if not _itk:
114
+ load_lib()
115
+ args = ()
116
+ if pixel_type is not None:
117
+ args += (pixel_type,)
118
+ if fallback_only is not None:
119
+ args += (fallback_only,)
120
+ self._img = _read_function(self.request.get_local_filename(), *args)
121
+
122
+ def _get_length(self):
123
+ return 1
124
+
125
+ def _close(self):
126
+ pass
127
+
128
+ def _get_data(self, index):
129
+ # Get data
130
+ if index != 0:
131
+ error_msg = "Index out of range while reading from itk file"
132
+ raise IndexError(error_msg)
133
+
134
+ # Return array and empty meta data
135
+ return _itk.GetArrayFromImage(self._img), {}
136
+
137
+ def _get_meta_data(self, index):
138
+ error_msg = "The itk plugin does not support meta data, currently."
139
+ raise RuntimeError(error_msg)
140
+
141
+ # -- writer
142
+ class Writer(Format.Writer):
143
+ def _open(self):
144
+ if not _itk:
145
+ load_lib()
146
+
147
+ def _close(self):
148
+ pass
149
+
150
+ def _append_data(self, im, meta):
151
+ _itk_img = _itk.GetImageFromArray(im)
152
+ _write_function(_itk_img, self.request.get_local_filename())
153
+
154
+ def set_meta_data(self, meta):
155
+ error_msg = "The itk plugin does not support meta data, currently."
156
+ raise RuntimeError(error_msg)
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/swf.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write SWF files.
5
+
6
+ Backend: internal
7
+
8
+ Shockwave flash (SWF) is a media format designed for rich and
9
+ interactive animations. This plugin makes use of this format to
10
+ store a series of images in a lossless format with good compression
11
+ (zlib). The resulting images can be shown as an animation using
12
+ a flash player (such as the browser).
13
+
14
+ SWF stores images in RGBA format. RGB or grayscale images are
15
+ automatically converted. SWF does not support meta data.
16
+
17
+ Parameters for reading
18
+ ----------------------
19
+ loop : bool
20
+ If True, the video will rewind as soon as a frame is requested
21
+ beyond the last frame. Otherwise, IndexError is raised. Default False.
22
+
23
+ Parameters for saving
24
+ ---------------------
25
+ fps : int
26
+ The speed to play the animation. Default 12.
27
+ loop : bool
28
+ If True, add a tag to the end of the file to play again from
29
+ the first frame. Most flash players will then play the movie
30
+ in a loop. Note that the imageio SWF Reader does not check this
31
+ tag. Default True.
32
+ html : bool
33
+ If the output is a file on the file system, write an html file
34
+ (in HTML5) that shows the animation. Default False.
35
+ compress : bool
36
+ Whether to compress the swf file. Default False. You probably don't
37
+ want to use this. This does not decrease the file size since
38
+ the images are already compressed. It will result in slower
39
+ read and write time. The only purpose of this feature is to
40
+ create compressed SWF files, so that we can test the
41
+ functionality to read them.
42
+
43
+ """
44
+
45
+ import os
46
+ import zlib
47
+ import logging
48
+ from io import BytesIO
49
+
50
+ import numpy as np
51
+
52
+ from ..core import Format, read_n_bytes, image_as_uint
53
+
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ _swf = None # lazily loaded in lib()
58
+
59
+
60
+ def load_lib():
61
+ global _swf
62
+ from . import _swf
63
+
64
+ return _swf
65
+
66
+
67
+ class SWFFormat(Format):
68
+ """See :mod:`imageio.plugins.swf`"""
69
+
70
+ def _can_read(self, request):
71
+ tmp = request.firstbytes[0:3].decode("ascii", "ignore")
72
+ if tmp in ("FWS", "CWS"):
73
+ return True
74
+
75
+ def _can_write(self, request):
76
+ if request.extension in self.extensions:
77
+ return True
78
+
79
+ # -- reader
80
+
81
+ class Reader(Format.Reader):
82
+ def _open(self, loop=False):
83
+ if not _swf:
84
+ load_lib()
85
+
86
+ self._arg_loop = bool(loop)
87
+
88
+ self._fp = self.request.get_file()
89
+
90
+ # Check file ...
91
+ tmp = self.request.firstbytes[0:3].decode("ascii", "ignore")
92
+ if tmp == "FWS":
93
+ pass # OK
94
+ elif tmp == "CWS":
95
+ # Compressed, we need to decompress
96
+ bb = self._fp.read()
97
+ bb = bb[:8] + zlib.decompress(bb[8:])
98
+ # Wrap up in a file object
99
+ self._fp = BytesIO(bb)
100
+ else:
101
+ raise IOError("This does not look like a valid SWF file")
102
+
103
+ # Skip first bytes. This also tests support got seeking ...
104
+ try:
105
+ self._fp.seek(8)
106
+ self._streaming_mode = False
107
+ except Exception:
108
+ self._streaming_mode = True
109
+ self._fp_read(8)
110
+
111
+ # Skip header
112
+ # Note that the number of frames is there, which we could
113
+ # potentially use, but the number of frames does not necessarily
114
+ # correspond to the number of images.
115
+ nbits = _swf.bits2int(self._fp_read(1), 5)
116
+ nbits = 5 + nbits * 4
117
+ Lrect = nbits / 8.0
118
+ if Lrect % 1:
119
+ Lrect += 1
120
+ Lrect = int(Lrect)
121
+ self._fp_read(Lrect + 3)
122
+
123
+ # Now the rest is basically tags ...
124
+ self._imlocs = [] # tuple (loc, sze, T, L1)
125
+ if not self._streaming_mode:
126
+ # Collect locations of frame, while skipping through the data
127
+ # This does not read any of the tag *data*.
128
+ try:
129
+ while True:
130
+ isimage, sze, T, L1 = self._read_one_tag()
131
+ loc = self._fp.tell()
132
+ if isimage:
133
+ # Still need to check if the format is right
134
+ format = ord(self._fp_read(3)[2:])
135
+ if format == 5: # RGB or RGBA lossless
136
+ self._imlocs.append((loc, sze, T, L1))
137
+ self._fp.seek(loc + sze) # Skip over tag
138
+ except IndexError:
139
+ pass # done reading
140
+
141
+ def _fp_read(self, n):
142
+ return read_n_bytes(self._fp, n)
143
+
144
+ def _close(self):
145
+ pass
146
+
147
+ def _get_length(self):
148
+ if self._streaming_mode:
149
+ return np.inf
150
+ else:
151
+ return len(self._imlocs)
152
+
153
+ def _get_data(self, index):
154
+ # Check index
155
+ if index < 0:
156
+ raise IndexError("Index in swf file must be > 0")
157
+ if not self._streaming_mode:
158
+ if self._arg_loop and self._imlocs:
159
+ index = index % len(self._imlocs)
160
+ if index >= len(self._imlocs):
161
+ raise IndexError("Index out of bounds")
162
+
163
+ if self._streaming_mode:
164
+ # Walk over tags until we find an image
165
+ while True:
166
+ isimage, sze, T, L1 = self._read_one_tag()
167
+ bb = self._fp_read(sze) # always read data
168
+ if isimage:
169
+ im = _swf.read_pixels(bb, 0, T, L1) # can be None
170
+ if im is not None:
171
+ return im, {}
172
+
173
+ else:
174
+ # Go to corresponding location, read data, and convert to image
175
+ loc, sze, T, L1 = self._imlocs[index]
176
+ self._fp.seek(loc)
177
+ bb = self._fp_read(sze)
178
+ # Read_pixels should return ndarry, since we checked format
179
+ im = _swf.read_pixels(bb, 0, T, L1)
180
+ return im, {}
181
+
182
+ def _read_one_tag(self):
183
+ """
184
+ Return (True, loc, size, T, L1) if an image that we can read.
185
+ Return (False, loc, size, T, L1) if any other tag.
186
+ """
187
+
188
+ # Get head
189
+ head = self._fp_read(6)
190
+ if not head: # pragma: no cover
191
+ raise IndexError("Reached end of swf movie")
192
+
193
+ # Determine type and length
194
+ T, L1, L2 = _swf.get_type_and_len(head)
195
+ if not L2: # pragma: no cover
196
+ raise RuntimeError("Invalid tag length, could not proceed")
197
+
198
+ # Read data
199
+ isimage = False
200
+ sze = L2 - 6
201
+ # bb = self._fp_read(L2 - 6)
202
+
203
+ # Parse tag
204
+ if T == 0:
205
+ raise IndexError("Reached end of swf movie")
206
+ elif T in [20, 36]:
207
+ isimage = True
208
+ # im = _swf.read_pixels(bb, 0, T, L1) # can be None
209
+ elif T in [6, 21, 35, 90]: # pragma: no cover
210
+ logger.warning("Ignoring JPEG image: cannot read JPEG.")
211
+ else:
212
+ pass # Not an image tag
213
+
214
+ # Done. Return image. Can be None
215
+ # return im
216
+ return isimage, sze, T, L1
217
+
218
+ def _get_meta_data(self, index):
219
+ return {} # This format does not support meta data
220
+
221
+ # -- writer
222
+
223
+ class Writer(Format.Writer):
224
+ def _open(self, fps=12, loop=True, html=False, compress=False):
225
+ if not _swf:
226
+ load_lib()
227
+
228
+ self._arg_fps = int(fps)
229
+ self._arg_loop = bool(loop)
230
+ self._arg_html = bool(html)
231
+ self._arg_compress = bool(compress)
232
+
233
+ self._fp = self.request.get_file()
234
+ self._framecounter = 0
235
+ self._framesize = (100, 100)
236
+
237
+ # For compress, we use an in-memory file object
238
+ if self._arg_compress:
239
+ self._fp_real = self._fp
240
+ self._fp = BytesIO()
241
+
242
+ def _close(self):
243
+ self._complete()
244
+ # Get size of (uncompressed) file
245
+ sze = self._fp.tell()
246
+ # set nframes, this is in the potentially compressed region
247
+ self._fp.seek(self._location_to_save_nframes)
248
+ self._fp.write(_swf.int2uint16(self._framecounter))
249
+ # Compress body?
250
+ if self._arg_compress:
251
+ bb = self._fp.getvalue()
252
+ self._fp = self._fp_real
253
+ self._fp.write(bb[:8])
254
+ self._fp.write(zlib.compress(bb[8:]))
255
+ sze = self._fp.tell() # renew sze value
256
+ # set size
257
+ self._fp.seek(4)
258
+ self._fp.write(_swf.int2uint32(sze))
259
+ self._fp = None # Disable
260
+
261
+ # Write html?
262
+ if self._arg_html and os.path.isfile(self.request.filename):
263
+ dirname, fname = os.path.split(self.request.filename)
264
+ filename = os.path.join(dirname, fname[:-4] + ".html")
265
+ w, h = self._framesize
266
+ html = HTML % (fname, w, h, fname)
267
+ with open(filename, "wb") as f:
268
+ f.write(html.encode("utf-8"))
269
+
270
+ def _write_header(self, framesize, fps):
271
+ self._framesize = framesize
272
+ # Called as soon as we know framesize; when we get first frame
273
+ bb = b""
274
+ bb += "FC"[self._arg_compress].encode("ascii")
275
+ bb += "WS".encode("ascii") # signature bytes
276
+ bb += _swf.int2uint8(8) # version
277
+ bb += "0000".encode("ascii") # FileLength (leave open for now)
278
+ bb += (
279
+ _swf.Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes()
280
+ )
281
+ bb += _swf.int2uint8(0) + _swf.int2uint8(fps) # FrameRate
282
+ self._location_to_save_nframes = len(bb)
283
+ bb += "00".encode("ascii") # nframes (leave open for now)
284
+ self._fp.write(bb)
285
+
286
+ # Write some initial tags
287
+ taglist = _swf.FileAttributesTag(), _swf.SetBackgroundTag(0, 0, 0)
288
+ for tag in taglist:
289
+ self._fp.write(tag.get_tag())
290
+
291
+ def _complete(self):
292
+ # What if no images were saved?
293
+ if not self._framecounter:
294
+ self._write_header((10, 10), self._arg_fps)
295
+ # Write stop tag if we do not loop
296
+ if not self._arg_loop:
297
+ self._fp.write(_swf.DoActionTag("stop").get_tag())
298
+ # finish with end tag
299
+ self._fp.write("\x00\x00".encode("ascii"))
300
+
301
+ def _append_data(self, im, meta):
302
+ # Correct shape and type
303
+ if im.ndim == 3 and im.shape[-1] == 1:
304
+ im = im[:, :, 0]
305
+ im = image_as_uint(im, bitdepth=8)
306
+ # Get frame size
307
+ wh = im.shape[1], im.shape[0]
308
+ # Write header on first frame
309
+ isfirstframe = False
310
+ if self._framecounter == 0:
311
+ isfirstframe = True
312
+ self._write_header(wh, self._arg_fps)
313
+ # Create tags
314
+ bm = _swf.BitmapTag(im)
315
+ sh = _swf.ShapeTag(bm.id, (0, 0), wh)
316
+ po = _swf.PlaceObjectTag(1, sh.id, move=(not isfirstframe))
317
+ sf = _swf.ShowFrameTag()
318
+ # Write tags
319
+ for tag in [bm, sh, po, sf]:
320
+ self._fp.write(tag.get_tag())
321
+ self._framecounter += 1
322
+
323
+ def set_meta_data(self, meta):
324
+ pass
325
+
326
+
327
+ HTML = """
328
+ <!DOCTYPE html>
329
+ <html>
330
+ <head>
331
+ <title>Show Flash animation %s</title>
332
+ </head>
333
+ <body>
334
+ <embed width="%i" height="%i" src="%s">
335
+ </html>
336
+ """
evalkit_tf437/lib/python3.10/site-packages/imageio/plugins/tifffile.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write TIFF files.
5
+
6
+ Backend: internal
7
+
8
+ Provides support for a wide range of Tiff images using the tifffile
9
+ backend.
10
+
11
+ Parameters for reading
12
+ ----------------------
13
+ offset : int
14
+ Optional start position of embedded file. By default this is
15
+ the current file position.
16
+ size : int
17
+ Optional size of embedded file. By default this is the number
18
+ of bytes from the 'offset' to the end of the file.
19
+ multifile : bool
20
+ If True (default), series may include pages from multiple files.
21
+ Currently applies to OME-TIFF only.
22
+ multifile_close : bool
23
+ If True (default), keep the handles of other files in multifile
24
+ series closed. This is inefficient when few files refer to
25
+ many pages. If False, the C runtime may run out of resources.
26
+
27
+ Parameters for saving
28
+ ---------------------
29
+ bigtiff : bool
30
+ If True, the BigTIFF format is used.
31
+ byteorder : {'<', '>'}
32
+ The endianness of the data in the file.
33
+ By default this is the system's native byte order.
34
+ software : str
35
+ Name of the software used to create the image.
36
+ Saved with the first page only.
37
+
38
+ Metadata for reading
39
+ --------------------
40
+ planar_configuration : {'contig', 'planar'}
41
+ Specifies if samples are stored contiguous or in separate planes.
42
+ By default this setting is inferred from the data shape.
43
+ 'contig': last dimension contains samples.
44
+ 'planar': third last dimension contains samples.
45
+ resolution_unit : int
46
+ The resolution unit stored in the TIFF tag. Usually 1 means no/unknown unit,
47
+ 2 means dpi (inch), 3 means dpc (centimeter).
48
+ resolution : (float, float, str)
49
+ A tuple formatted as (X_resolution, Y_resolution, unit). The unit is a
50
+ string representing one of the following units::
51
+
52
+ NONE # No unit or unit unknown
53
+ INCH # dpi
54
+ CENTIMETER # cpi
55
+ MILLIMETER
56
+ MICROMETER
57
+
58
+ compression : int
59
+ Value indicating the compression algorithm used, e.g. 5 is LZW,
60
+ 7 is JPEG, 8 is deflate.
61
+ If 1, data are uncompressed.
62
+ predictor : int
63
+ Value 2 indicates horizontal differencing was used before compression,
64
+ while 3 indicates floating point horizontal differencing.
65
+ If 1, no prediction scheme was used before compression.
66
+ orientation : {'top_left', 'bottom_right', ...}
67
+ Oriented of image array.
68
+ is_rgb : bool
69
+ True if page contains a RGB image.
70
+ is_contig : bool
71
+ True if page contains a contiguous image.
72
+ is_tiled : bool
73
+ True if page contains tiled image.
74
+ is_palette : bool
75
+ True if page contains a palette-colored image and not OME or STK.
76
+ is_reduced : bool
77
+ True if page is a reduced image of another image.
78
+ is_shaped : bool
79
+ True if page contains shape in image_description tag.
80
+ is_fluoview : bool
81
+ True if page contains FluoView MM_STAMP tag.
82
+ is_nih : bool
83
+ True if page contains NIH image header.
84
+ is_micromanager : bool
85
+ True if page contains Micro-Manager metadata.
86
+ is_ome : bool
87
+ True if page contains OME-XML in image_description tag.
88
+ is_sgi : bool
89
+ True if page contains SGI image and tile depth tags.
90
+ is_mdgel : bool
91
+ True if page contains md_file_tag tag.
92
+ is_mediacy : bool
93
+ True if page contains Media Cybernetics Id tag.
94
+ is_stk : bool
95
+ True if page contains UIC2Tag tag.
96
+ is_lsm : bool
97
+ True if page contains LSM CZ_LSM_INFO tag.
98
+ description : str
99
+ Image description
100
+ description1 : str
101
+ Additional description
102
+ is_imagej : None or str
103
+ ImageJ metadata
104
+ software : str
105
+ Software used to create the TIFF file
106
+ datetime : datetime.datetime
107
+ Creation date and time
108
+
109
+ Metadata for writing
110
+ --------------------
111
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
112
+ The color space of the image data.
113
+ By default this setting is inferred from the data shape.
114
+ planarconfig : {'contig', 'planar'}
115
+ Specifies if samples are stored contiguous or in separate planes.
116
+ By default this setting is inferred from the data shape.
117
+ 'contig': last dimension contains samples.
118
+ 'planar': third last dimension contains samples.
119
+ resolution : (float, float) or ((int, int), (int, int))
120
+ X and Y resolution in dots per inch as float or rational numbers.
121
+ description : str
122
+ The subject of the image. Saved with the first page only.
123
+ compress : int
124
+ Values from 0 to 9 controlling the level of zlib (deflate) compression.
125
+ If 0, data are written uncompressed (default).
126
+ compression : str, (int, int)
127
+ Compression scheme used while writing the image. If omitted (default) the
128
+ image is not uncompressed. Compression cannot be used to write contiguous
129
+ series. Compressors may require certain data shapes, types or value ranges.
130
+ For example, JPEG compression requires grayscale or RGB(A), uint8 or 12-bit
131
+ uint16. JPEG compression is experimental. JPEG markers and TIFF tags may not
132
+ match. Only a limited set of compression schemes are implemented. 'ZLIB' is
133
+ short for ADOBE_DEFLATE. The value is written to the Compression tag.
134
+ compressionargs:
135
+ Extra arguments passed to compression codec, e.g., compression level. Refer
136
+ to the Imagecodecs implementation for supported arguments.
137
+ predictor : bool
138
+ If True, horizontal differencing is applied before compression.
139
+ Note that using an int literal 1 actually means no prediction scheme
140
+ will be used.
141
+ volume : bool
142
+ If True, volume data are stored in one tile (if applicable) using
143
+ the SGI image_depth and tile_depth tags.
144
+ Image width and depth must be multiple of 16.
145
+ Few software can read this format, e.g. MeVisLab.
146
+ writeshape : bool
147
+ If True, write the data shape to the image_description tag
148
+ if necessary and no other description is given.
149
+ extratags: sequence of tuples
150
+ Additional tags as [(code, dtype, count, value, writeonce)].
151
+
152
+ code : int
153
+ The TIFF tag Id.
154
+ dtype : str
155
+ Data type of items in 'value' in Python struct format.
156
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
157
+ count : int
158
+ Number of data values. Not used for string values.
159
+ value : sequence
160
+ 'Count' values compatible with 'dtype'.
161
+ writeonce : bool
162
+ If True, the tag is written to the first page only.
163
+
164
+ Notes
165
+ -----
166
+ Global metadata is stored with the first frame in a TIFF file.
167
+ Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
168
+ was written has no effect. Also, global metadata is ignored if metadata is
169
+ provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
170
+
171
+ If you have installed tifffile as a Python package, imageio will attempt
172
+ to use that as backend instead of the bundled backend. Doing so can
173
+ provide access to new performance improvements and bug fixes.
174
+
175
+ """
176
+
177
+ import datetime
178
+
179
+ from ..core import Format
180
+ from ..core.request import URI_BYTES, URI_FILE
181
+
182
+ import numpy as np
183
+ import warnings
184
+
185
+
186
+ try:
187
+ import tifffile as _tifffile
188
+ except ImportError:
189
+ warnings.warn(
190
+ "ImageIO's vendored tifffile backend is deprecated and will be"
191
+ " removed in ImageIO v3. Install the tifffile directly:"
192
+ " `pip install imageio[tifffile]`",
193
+ DeprecationWarning,
194
+ )
195
+ from . import _tifffile
196
+
197
+
198
+ TIFF_FORMATS = (".tif", ".tiff", ".stk", ".lsm")
199
+ WRITE_METADATA_KEYS = (
200
+ "photometric",
201
+ "planarconfig",
202
+ "resolution",
203
+ "description",
204
+ "compress",
205
+ "compression",
206
+ "compressionargs",
207
+ "predictor",
208
+ "volume",
209
+ "writeshape",
210
+ "extratags",
211
+ "datetime",
212
+ )
213
+ READ_METADATA_KEYS = (
214
+ "planar_configuration",
215
+ "is_fluoview",
216
+ "is_nih",
217
+ "is_contig",
218
+ "is_micromanager",
219
+ "is_ome",
220
+ "is_lsm",
221
+ "is_palette",
222
+ "is_reduced",
223
+ "is_rgb",
224
+ "is_sgi",
225
+ "is_shaped",
226
+ "is_stk",
227
+ "is_tiled",
228
+ "is_mdgel",
229
+ "resolution_unit",
230
+ "compression",
231
+ "predictor",
232
+ "is_mediacy",
233
+ "orientation",
234
+ "description",
235
+ "description1",
236
+ "is_imagej",
237
+ "software",
238
+ )
239
+
240
+
241
+ class TiffFormat(Format):
242
+ """Provides support for a wide range of Tiff images using the tifffile
243
+ backend.
244
+
245
+ Images that contain multiple pages can be read using ``imageio.mimread()``
246
+ to read the individual pages, or ``imageio.volread()`` to obtain a
247
+ single (higher dimensional) array.
248
+
249
+ Note that global metadata is stored with the first frame in a TIFF file.
250
+ Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
251
+ was written has no effect. Also, global metadata is ignored if metadata is
252
+ provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
253
+
254
+ If you have installed tifffile as a Python package, imageio will attempt
255
+ to use that as backend instead of the bundled backend. Doing so can
256
+ provide access to new performance improvements and bug fixes.
257
+
258
+ Parameters for reading
259
+ ----------------------
260
+ offset : int
261
+ Optional start position of embedded file. By default this is
262
+ the current file position.
263
+ size : int
264
+ Optional size of embedded file. By default this is the number
265
+ of bytes from the 'offset' to the end of the file.
266
+ multifile : bool
267
+ If True (default), series may include pages from multiple files.
268
+ Currently applies to OME-TIFF only.
269
+ multifile_close : bool
270
+ If True (default), keep the handles of other files in multifile
271
+ series closed. This is inefficient when few files refer to
272
+ many pages. If False, the C runtime may run out of resources.
273
+
274
+ Parameters for saving
275
+ ---------------------
276
+ bigtiff : bool
277
+ If True, the BigTIFF format is used.
278
+ byteorder : {'<', '>'}
279
+ The endianness of the data in the file.
280
+ By default this is the system's native byte order.
281
+ software : str
282
+ Name of the software used to create the image.
283
+ Saved with the first page only.
284
+
285
+ Metadata for reading
286
+ --------------------
287
+ planar_configuration : {'contig', 'planar'}
288
+ Specifies if samples are stored contiguous or in separate planes.
289
+ By default this setting is inferred from the data shape.
290
+ 'contig': last dimension contains samples.
291
+ 'planar': third last dimension contains samples.
292
+ resolution_unit : (float, float) or ((int, int), (int, int))
293
+ X and Y resolution in dots per inch as float or rational numbers.
294
+ compression : int
295
+ Value indicating the compression algorithm used, e.g. 5 is LZW,
296
+ 7 is JPEG, 8 is deflate.
297
+ If 1, data are uncompressed.
298
+ predictor : int
299
+ Value 2 indicates horizontal differencing was used before compression,
300
+ while 3 indicates floating point horizontal differencing.
301
+ If 1, no prediction scheme was used before compression.
302
+ orientation : {'top_left', 'bottom_right', ...}
303
+ Oriented of image array.
304
+ is_rgb : bool
305
+ True if page contains a RGB image.
306
+ is_contig : bool
307
+ True if page contains a contiguous image.
308
+ is_tiled : bool
309
+ True if page contains tiled image.
310
+ is_palette : bool
311
+ True if page contains a palette-colored image and not OME or STK.
312
+ is_reduced : bool
313
+ True if page is a reduced image of another image.
314
+ is_shaped : bool
315
+ True if page contains shape in image_description tag.
316
+ is_fluoview : bool
317
+ True if page contains FluoView MM_STAMP tag.
318
+ is_nih : bool
319
+ True if page contains NIH image header.
320
+ is_micromanager : bool
321
+ True if page contains Micro-Manager metadata.
322
+ is_ome : bool
323
+ True if page contains OME-XML in image_description tag.
324
+ is_sgi : bool
325
+ True if page contains SGI image and tile depth tags.
326
+ is_stk : bool
327
+ True if page contains UIC2Tag tag.
328
+ is_mdgel : bool
329
+ True if page contains md_file_tag tag.
330
+ is_mediacy : bool
331
+ True if page contains Media Cybernetics Id tag.
332
+ is_stk : bool
333
+ True if page contains UIC2Tag tag.
334
+ is_lsm : bool
335
+ True if page contains LSM CZ_LSM_INFO tag.
336
+ description : str
337
+ Image description
338
+ description1 : str
339
+ Additional description
340
+ is_imagej : None or str
341
+ ImageJ metadata
342
+ software : str
343
+ Software used to create the TIFF file
344
+ datetime : datetime.datetime
345
+ Creation date and time
346
+
347
+ Metadata for writing
348
+ --------------------
349
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
350
+ The color space of the image data.
351
+ By default this setting is inferred from the data shape.
352
+ planarconfig : {'contig', 'planar'}
353
+ Specifies if samples are stored contiguous or in separate planes.
354
+ By default this setting is inferred from the data shape.
355
+ 'contig': last dimension contains samples.
356
+ 'planar': third last dimension contains samples.
357
+ resolution : (float, float) or ((int, int), (int, int))
358
+ X and Y resolution in dots per inch as float or rational numbers.
359
+ description : str
360
+ The subject of the image. Saved with the first page only.
361
+ compress : int
362
+ Values from 0 to 9 controlling the level of zlib (deflate) compression.
363
+ If 0, data are written uncompressed (default).
364
+ predictor : bool
365
+ If True, horizontal differencing is applied before compression.
366
+ Note that using an int literal 1 actually means no prediction scheme
367
+ will be used.
368
+ volume : bool
369
+ If True, volume data are stored in one tile (if applicable) using
370
+ the SGI image_depth and tile_depth tags.
371
+ Image width and depth must be multiple of 16.
372
+ Few software can read this format, e.g. MeVisLab.
373
+ writeshape : bool
374
+ If True, write the data shape to the image_description tag
375
+ if necessary and no other description is given.
376
+ extratags: sequence of tuples
377
+ Additional tags as [(code, dtype, count, value, writeonce)].
378
+
379
+ code : int
380
+ The TIFF tag Id.
381
+ dtype : str
382
+ Data type of items in 'value' in Python struct format.
383
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
384
+ count : int
385
+ Number of data values. Not used for string values.
386
+ value : sequence
387
+ 'Count' values compatible with 'dtype'.
388
+ writeonce : bool
389
+ If True, the tag is written to the first page only.
390
+ """
391
+
392
+ def _can_read(self, request):
393
+ try:
394
+ _tifffile.TiffFile(request.get_file(), **request.kwargs)
395
+ except ValueError:
396
+ # vendored backend raises value exception
397
+ return False
398
+ except _tifffile.TiffFileError: # pragma: no-cover
399
+ # current version raises custom exception
400
+ return False
401
+ finally:
402
+ request.get_file().seek(0)
403
+
404
+ return True
405
+
406
+ def _can_write(self, request):
407
+ if request._uri_type in [URI_FILE, URI_BYTES]:
408
+ pass # special URI
409
+ elif request.extension not in self.extensions:
410
+ return False
411
+
412
+ try:
413
+ _tifffile.TiffWriter(request.get_file(), **request.kwargs)
414
+ except ValueError:
415
+ # vendored backend raises value exception
416
+ return False
417
+ except _tifffile.TiffFileError: # pragma: no-cover
418
+ # current version raises custom exception
419
+ return False
420
+ finally:
421
+ request.get_file().seek(0)
422
+ return True
423
+
424
+ # -- reader
425
+
426
+ class Reader(Format.Reader):
427
+ def _open(self, **kwargs):
428
+ # Allow loading from http; tifffile uses seek, so download first
429
+ if self.request.filename.startswith(("http://", "https://")):
430
+ self._f = f = open(self.request.get_local_filename(), "rb")
431
+ else:
432
+ self._f = None
433
+ f = self.request.get_file()
434
+ self._tf = _tifffile.TiffFile(f, **kwargs)
435
+
436
+ def _close(self):
437
+ self._tf.close()
438
+ if self._f is not None:
439
+ self._f.close()
440
+
441
+ def _get_length(self):
442
+ return len(self._tf.series)
443
+
444
+ def _get_data(self, index):
445
+ if index < 0 or index >= self._get_length():
446
+ raise IndexError("Index out of range while reading from tiff file")
447
+
448
+ im = self._tf.asarray(series=index)
449
+ meta = self._get_meta_data(index)
450
+
451
+ return im, meta
452
+
453
+ def _get_meta_data(self, index):
454
+ meta = {}
455
+ page = self._tf.pages[index or 0]
456
+ for key in READ_METADATA_KEYS:
457
+ try:
458
+ meta[key] = getattr(page, key)
459
+ except Exception:
460
+ pass
461
+
462
+ # tifffile <= 0.12.1 use datetime, newer use DateTime
463
+ for key in ("datetime", "DateTime"):
464
+ try:
465
+ meta["datetime"] = datetime.datetime.strptime(
466
+ page.tags[key].value, "%Y:%m:%d %H:%M:%S"
467
+ )
468
+ break
469
+ except Exception:
470
+ pass
471
+
472
+ if 296 in page.tags:
473
+ meta["resolution_unit"] = page.tags[296].value.value
474
+
475
+ if 282 in page.tags and 283 in page.tags and 296 in page.tags:
476
+ resolution_x = page.tags[282].value
477
+ resolution_y = page.tags[283].value
478
+ if resolution_x[1] == 0 or resolution_y[1] == 0:
479
+ warnings.warn(
480
+ "Ignoring resolution metadata, "
481
+ "because at least one direction has a 0 denominator.",
482
+ RuntimeWarning,
483
+ )
484
+ else:
485
+ meta["resolution"] = (
486
+ resolution_x[0] / resolution_x[1],
487
+ resolution_y[0] / resolution_y[1],
488
+ page.tags[296].value.name,
489
+ )
490
+
491
+ return meta
492
+
493
+ # -- writer
494
+ class Writer(Format.Writer):
495
+ def _open(self, bigtiff=None, byteorder=None, software=None):
496
+ try:
497
+ self._tf = _tifffile.TiffWriter(
498
+ self.request.get_file(),
499
+ bigtiff=bigtiff,
500
+ byteorder=byteorder,
501
+ software=software,
502
+ )
503
+ self._software = None
504
+ except TypeError:
505
+ # In tifffile >= 0.15, the `software` arg is passed to
506
+ # TiffWriter.save
507
+ self._tf = _tifffile.TiffWriter(
508
+ self.request.get_file(), bigtiff=bigtiff, byteorder=byteorder
509
+ )
510
+ self._software = software
511
+
512
+ self._meta = {}
513
+ self._frames_written = 0
514
+
515
+ def _close(self):
516
+ self._tf.close()
517
+
518
+ def _append_data(self, im, meta):
519
+ if meta is not None:
520
+ meta = self._sanitize_meta(meta)
521
+ else:
522
+ # Use global metadata for first frame
523
+ meta = self._meta if self._frames_written == 0 else {}
524
+ if self._software is not None and self._frames_written == 0:
525
+ meta["software"] = self._software
526
+ # No need to check self.request.mode; tifffile figures out whether
527
+ # this is a single page, or all page data at once.
528
+ try:
529
+ # TiffWriter.save has been deprecated in version 2020.9.30
530
+ write_meth = self._tf.write
531
+ except AttributeError:
532
+ write_meth = self._tf.save
533
+ write_meth(np.asanyarray(im), contiguous=False, **meta)
534
+ self._frames_written += 1
535
+
536
+ @staticmethod
537
+ def _sanitize_meta(meta):
538
+ ret = {}
539
+ for key, value in meta.items():
540
+ if key in WRITE_METADATA_KEYS:
541
+ # Special case of previously read `predictor` int value
542
+ # 1(=NONE) translation to False expected by TiffWriter.save
543
+ if key == "predictor" and not isinstance(value, bool):
544
+ ret[key] = value > 1
545
+ elif key == "compress" and value != 0:
546
+ warnings.warn(
547
+ "The use of `compress` is deprecated. Use `compression` and `compressionargs` instead.",
548
+ DeprecationWarning,
549
+ )
550
+
551
+ if _tifffile.__version__ < "2022":
552
+ ret["compression"] = (8, value)
553
+ else:
554
+ ret["compression"] = "zlib"
555
+ ret["compressionargs"] = {"level": value}
556
+ else:
557
+ ret[key] = value
558
+ return ret
559
+
560
+ def set_meta_data(self, meta):
561
+ self._meta = self._sanitize_meta(meta)
evalkit_tf437/lib/python3.10/site-packages/imageio/v3.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from .core.imopen import imopen
4
+
5
+
6
+ def imread(uri, *, index=None, plugin=None, extension=None, format_hint=None, **kwargs):
7
+ """Read an ndimage from a URI.
8
+
9
+ Opens the given URI and reads an ndimage from it. The exact behavior
10
+ depends on both the file type and plugin used to open the file. To learn
11
+ about the exact behavior, check the documentation of the relevant plugin.
12
+ Typically, imread attempts to read all data stored in the URI.
13
+
14
+ Parameters
15
+ ----------
16
+ uri : {str, pathlib.Path, bytes, file}
17
+ The resource to load the image from, e.g. a filename, pathlib.Path,
18
+ http address or file object, see the docs for more info.
19
+ index : {int, Ellipsis, None}
20
+ If the ImageResource contains multiple ndimages, and index is an
21
+ integer, select the index-th ndimage from among them and return it. If
22
+ index is an ellipsis (...), read all ndimages in the file and stack them
23
+ along a new batch dimension. If index is None, let the plugin decide.
24
+ plugin : {str, None}
25
+ The plugin to use. If set to None (default) imread will perform a
26
+ search for a matching plugin. If not None, this takes priority over
27
+ the provided format hint (if present).
28
+ extension : str
29
+ If not None, treat the provided ImageResource as if it had the given
30
+ extension. This affects the order in which backends are considered.
31
+ format_hint : str
32
+ Deprecated. Use `extension` instead.
33
+ **kwargs :
34
+ Additional keyword arguments will be passed to the plugin's read call.
35
+
36
+ Returns
37
+ -------
38
+ image : ndimage
39
+ The ndimage located at the given URI.
40
+ """
41
+
42
+ plugin_kwargs = {
43
+ "legacy_mode": False,
44
+ "plugin": plugin,
45
+ "format_hint": format_hint,
46
+ "extension": extension,
47
+ }
48
+
49
+ call_kwargs = kwargs
50
+ if index is not None:
51
+ call_kwargs["index"] = index
52
+
53
+ with imopen(uri, "r", **plugin_kwargs) as img_file:
54
+ return np.asarray(img_file.read(**call_kwargs))
55
+
56
+
57
+ def imiter(uri, *, plugin=None, extension=None, format_hint=None, **kwargs):
58
+ """Read a sequence of ndimages from a URI.
59
+
60
+ Returns an iterable that yields ndimages from the given URI. The exact
61
+ behavior depends on both, the file type and plugin used to open the file.
62
+ To learn about the exact behavior, check the documentation of the relevant
63
+ plugin.
64
+
65
+ Parameters
66
+ ----------
67
+ uri : {str, pathlib.Path, bytes, file}
68
+ The resource to load the image from, e.g. a filename, pathlib.Path,
69
+ http address or file object, see the docs for more info.
70
+ plugin : {str, None}
71
+ The plugin to use. If set to None (default) imiter will perform a
72
+ search for a matching plugin. If not None, this takes priority over
73
+ the provided format hint (if present).
74
+ extension : str
75
+ If not None, treat the provided ImageResource as if it had the given
76
+ extension. This affects the order in which backends are considered.
77
+ format_hint : str
78
+ Deprecated. Use `extension` instead.
79
+ **kwargs :
80
+ Additional keyword arguments will be passed to the plugin's ``iter``
81
+ call.
82
+
83
+ Yields
84
+ ------
85
+ image : ndimage
86
+ The next ndimage located at the given URI.
87
+
88
+ """
89
+
90
+ with imopen(
91
+ uri,
92
+ "r",
93
+ legacy_mode=False,
94
+ plugin=plugin,
95
+ format_hint=format_hint,
96
+ extension=extension,
97
+ ) as img_file:
98
+ for image in img_file.iter(**kwargs):
99
+ # Note: casting to ndarray here to ensure compatibility
100
+ # with the v2.9 API
101
+ yield np.asarray(image)
102
+
103
+
104
+ def imwrite(uri, image, *, plugin=None, extension=None, format_hint=None, **kwargs):
105
+ """Write an ndimage to the given URI.
106
+
107
+ The exact behavior depends on the file type and plugin used. To learn about
108
+ the exact behavior, check the documentation of the relevant plugin.
109
+
110
+ Parameters
111
+ ----------
112
+ uri : {str, pathlib.Path, bytes, file}
113
+ The resource to save the image to, e.g. a filename, pathlib.Path,
114
+ http address or file object, check the docs for more info.
115
+ image : np.ndarray
116
+ The image to write to disk.
117
+ plugin : {str, None}
118
+ The plugin to use. If set to None (default) imwrite will perform a
119
+ search for a matching plugin. If not None, this takes priority over
120
+ the provided format hint (if present).
121
+ extension : str
122
+ If not None, treat the provided ImageResource as if it had the given
123
+ extension. This affects the order in which backends are considered, and
124
+ may also influence the format used when encoding.
125
+ format_hint : str
126
+ Deprecated. Use `extension` instead.
127
+ **kwargs :
128
+ Additional keyword arguments will be passed to the plugin's ``write``
129
+ call.
130
+
131
+ Returns
132
+ -------
133
+ encoded_image : None or Bytes
134
+ Returns ``None`` in all cases, except when ``uri`` is set to ``<bytes>``.
135
+ In this case it returns the encoded ndimage as a bytes string.
136
+
137
+ """
138
+
139
+ with imopen(
140
+ uri,
141
+ "w",
142
+ legacy_mode=False,
143
+ plugin=plugin,
144
+ format_hint=format_hint,
145
+ extension=extension,
146
+ ) as img_file:
147
+ encoded = img_file.write(image, **kwargs)
148
+
149
+ return encoded
150
+
151
+
152
+ def improps(uri, *, index=None, plugin=None, extension=None, **kwargs):
153
+ """Read standardized metadata.
154
+
155
+ Opens the given URI and reads the properties of an ndimage from it. The
156
+ properties represent standardized metadata. This means that they will have
157
+ the same name regardless of the format being read or plugin/backend being
158
+ used. Further, any field will be, where possible, populated with a sensible
159
+ default (may be `None`) if the ImageResource does not declare a value in its
160
+ metadata.
161
+
162
+ Parameters
163
+ ----------
164
+ index : int
165
+ If the ImageResource contains multiple ndimages, and index is an
166
+ integer, select the index-th ndimage from among them and return its
167
+ properties. If index is an ellipsis (...), read all ndimages in the file
168
+ and stack them along a new batch dimension and return their properties.
169
+ If index is None, let the plugin decide.
170
+ plugin : {str, None}
171
+ The plugin to be used. If None, performs a search for a matching
172
+ plugin.
173
+ extension : str
174
+ If not None, treat the provided ImageResource as if it had the given
175
+ extension. This affects the order in which backends are considered.
176
+ **kwargs :
177
+ Additional keyword arguments will be passed to the plugin's ``properties``
178
+ call.
179
+
180
+ Returns
181
+ -------
182
+ properties : ImageProperties
183
+ A dataclass filled with standardized image metadata.
184
+
185
+ Notes
186
+ -----
187
+ Where possible, this will avoid loading pixel data.
188
+
189
+ See Also
190
+ --------
191
+ imageio.core.v3_plugin_api.ImageProperties
192
+
193
+ """
194
+
195
+ plugin_kwargs = {"legacy_mode": False, "plugin": plugin, "extension": extension}
196
+
197
+ call_kwargs = kwargs
198
+ if index is not None:
199
+ call_kwargs["index"] = index
200
+
201
+ with imopen(uri, "r", **plugin_kwargs) as img_file:
202
+ properties = img_file.properties(**call_kwargs)
203
+
204
+ return properties
205
+
206
+
207
+ def immeta(
208
+ uri, *, index=None, plugin=None, extension=None, exclude_applied=True, **kwargs
209
+ ):
210
+ """Read format-specific metadata.
211
+
212
+ Opens the given URI and reads metadata for an ndimage from it. The contents
213
+ of the returned metadata dictionary is specific to both the image format and
214
+ plugin used to open the ImageResource. To learn about the exact behavior,
215
+ check the documentation of the relevant plugin. Typically, immeta returns a
216
+ dictionary specific to the image format, where keys match metadata field
217
+ names and values are a field's contents.
218
+
219
+ Parameters
220
+ ----------
221
+ uri : {str, pathlib.Path, bytes, file}
222
+ The resource to load the image from, e.g. a filename, pathlib.Path, http
223
+ address or file object, see the docs for more info.
224
+ index : {int, None}
225
+ If the ImageResource contains multiple ndimages, and index is an
226
+ integer, select the index-th ndimage from among them and return its
227
+ metadata. If index is an ellipsis (...), return global metadata. If
228
+ index is None, let the plugin decide the default.
229
+ plugin : {str, None}
230
+ The plugin to be used. If None (default), performs a search for a
231
+ matching plugin.
232
+ extension : str
233
+ If not None, treat the provided ImageResource as if it had the given
234
+ extension. This affects the order in which backends are considered.
235
+ **kwargs :
236
+ Additional keyword arguments will be passed to the plugin's metadata
237
+ method.
238
+
239
+ Returns
240
+ -------
241
+ image : ndimage
242
+ The ndimage located at the given URI.
243
+
244
+ """
245
+
246
+ plugin_kwargs = {"legacy_mode": False, "plugin": plugin, "extension": extension}
247
+
248
+ call_kwargs = kwargs
249
+ call_kwargs["exclude_applied"] = exclude_applied
250
+ if index is not None:
251
+ call_kwargs["index"] = index
252
+
253
+ with imopen(uri, "r", **plugin_kwargs) as img_file:
254
+ metadata = img_file.metadata(**call_kwargs)
255
+
256
+ return metadata
257
+
258
+
259
+ __all__ = ["imopen", "imread", "imwrite", "imiter", "improps", "immeta"]
falcon/bin/accelerate-merge-weights ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/root/envs/falcon/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from accelerate.commands.merge import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
falcon/bin/bzgrep ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ # Bzgrep wrapped for bzip2,
4
+ # adapted from zgrep by Philippe Troin <[email protected]> for Debian GNU/Linux.
5
+ ## zgrep notice:
6
+ ## zgrep -- a wrapper around a grep program that decompresses files as needed
7
+ ## Adapted from a version sent by Charles Levert <[email protected]>
8
+
9
+ PATH="/usr/bin:$PATH"; export PATH
10
+
11
+ prog=`echo $0 | sed 's|.*/||'`
12
+ case "$prog" in
13
+ *egrep) grep=${EGREP-egrep} ;;
14
+ *fgrep) grep=${FGREP-fgrep} ;;
15
+ *) grep=${GREP-grep} ;;
16
+ esac
17
+ pat=""
18
+ while test $# -ne 0; do
19
+ case "$1" in
20
+ -e | -f) opt="$opt $1"; shift; pat="$1"
21
+ if test "$grep" = grep; then # grep is buggy with -e on SVR4
22
+ grep=egrep
23
+ fi;;
24
+ -A | -B) opt="$opt $1 $2"; shift;;
25
+ -*) opt="$opt $1";;
26
+ *) if test -z "$pat"; then
27
+ pat="$1"
28
+ else
29
+ break;
30
+ fi;;
31
+ esac
32
+ shift
33
+ done
34
+
35
+ if test -z "$pat"; then
36
+ echo "grep through bzip2 files"
37
+ echo "usage: $prog [grep_options] pattern [files]"
38
+ exit 1
39
+ fi
40
+
41
+ list=0
42
+ silent=0
43
+ op=`echo "$opt" | sed -e 's/ //g' -e 's/-//g'`
44
+ case "$op" in
45
+ *l*) list=1
46
+ esac
47
+ case "$op" in
48
+ *h*) silent=1
49
+ esac
50
+
51
+ if test $# -eq 0; then
52
+ bzip2 -cdfq | $grep $opt "$pat"
53
+ exit $?
54
+ fi
55
+
56
+ res=0
57
+ for i do
58
+ if test -f "$i"; then :; else if test -f "$i.bz2"; then i="$i.bz2"; fi; fi
59
+ if test $list -eq 1; then
60
+ bzip2 -cdfq "$i" | $grep $opt "$pat" 2>&1 > /dev/null && echo $i
61
+ r=$?
62
+ elif test $# -eq 1 -o $silent -eq 1; then
63
+ bzip2 -cdfq "$i" | $grep $opt "$pat"
64
+ r=$?
65
+ else
66
+ j=$(echo "$i" | sed 's/\\/&&/g;s/|/\\&/g;s/&/\\&/g')
67
+ j=`printf "%s" "$j" | tr '\n' ' '`
68
+ # A trick adapted from
69
+ # https://groups.google.com/forum/#!original/comp.unix.shell/x1345iu10eg/Nn1n-1r1uU0J
70
+ # that has the same effect as the following bash code:
71
+ # bzip2 -cdfq "$i" | $grep $opt "$pat" | sed "s|^|${j}:|"
72
+ # r=${PIPESTATUS[1]}
73
+ exec 3>&1
74
+ eval `
75
+ exec 4>&1 >&3 3>&-
76
+ {
77
+ bzip2 -cdfq "$i" 4>&-
78
+ } | {
79
+ $grep $opt "$pat" 4>&-; echo "r=$?;" >&4
80
+ } | sed "s|^|${j}:|"
81
+ `
82
+ fi
83
+ test "$r" -ne 0 && res="$r"
84
+ done
85
+ exit $res
falcon/bin/convert-caffe2-to-onnx ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/root/envs/falcon/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from caffe2.python.onnx.bin.conversion import caffe2_to_onnx
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(caffe2_to_onnx())
falcon/bin/gradio ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/root/envs/falcon/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from gradio.cli import cli
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(cli())
falcon/bin/httpx ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/root/envs/falcon/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from httpx import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
falcon/bin/infocmp ADDED
Binary file (63.5 kB). View file
 
falcon/bin/infotocap ADDED
Binary file (92.2 kB). View file
 
falcon/bin/lzless ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # SPDX-License-Identifier: GPL-2.0-or-later
3
+
4
+ # Copyright (C) 1998, 2002, 2006, 2007 Free Software Foundation
5
+
6
+ # The original version for gzip was written by Paul Eggert.
7
+ # Modified for XZ Utils by Andrew Dudman and Lasse Collin.
8
+
9
+ # This program is free software; you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation; either version 2 of the License, or
12
+ # (at your option) any later version.
13
+
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+
19
+
20
+ #SET_PATH - This line is a placeholder to ease patching this script.
21
+
22
+ # Instead of unsetting XZ_OPT, just make sure that xz will use file format
23
+ # autodetection. This way memory usage limit and thread limit can be
24
+ # specified via XZ_OPT.
25
+ xz='xz --format=auto'
26
+
27
+ version='xzless (XZ Utils) 5.6.4'
28
+
29
+ usage="Usage: ${0##*/} [OPTION]... [FILE]...
30
+ Like 'less', but operate on the uncompressed contents of xz compressed FILEs.
31
+
32
+ Options are the same as for 'less'.
33
+
34
+ Report bugs to <[email protected]>."
35
+
36
+ case $1 in
37
+ --help) printf '%s\n' "$usage" || exit 2; exit;;
38
+ --version) printf '%s\n' "$version" || exit 2; exit;;
39
+ esac
40
+
41
+ if test "${LESSMETACHARS+set}" != set; then
42
+ # Work around a bug in less 394 and earlier;
43
+ # it mishandles the metacharacters '$%=~'.
44
+ space=' '
45
+ tab=' '
46
+ nl='
47
+ '
48
+ LESSMETACHARS="$space$tab$nl'"';*?"()<>[|&^`#\$%=~'
49
+ fi
50
+
51
+ VER=$(less -V | { read _ ver _ && echo ${ver%%.*}; })
52
+ if test "$VER" -ge 451; then
53
+ # less 451 or later: If the compressed file is valid but has
54
+ # zero bytes of uncompressed data, using two vertical bars ||- makes
55
+ # "less" check the exit status of xz and if it is zero then display
56
+ # an empty file. With a single vertical bar |- and no output from xz,
57
+ # "less" would attempt to display the raw input file instead.
58
+ LESSOPEN="||-$xz -cdfqQ -- %s"
59
+ elif test "$VER" -ge 429; then
60
+ # less 429 or later: LESSOPEN pipe will be used on
61
+ # standard input if $LESSOPEN begins with |-.
62
+ LESSOPEN="|-$xz -cdfqQ -- %s"
63
+ else
64
+ LESSOPEN="|$xz -cdfqQ -- %s"
65
+ fi
66
+
67
+ SHOW_PREPROC_ERRORS=
68
+ if test "$VER" -ge 632; then
69
+ SHOW_PREPROC_ERRORS=--show-preproc-errors
70
+ fi
71
+
72
+ export LESSMETACHARS LESSOPEN
73
+
74
+ exec less $SHOW_PREPROC_ERRORS "$@"
falcon/bin/lzmainfo ADDED
Binary file (17 kB). View file