ZTWHHH commited on
Commit
f30af9a
·
verified ·
1 Parent(s): 40c0305

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. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/INSTALLER +1 -0
  2. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/METADATA +256 -0
  3. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/RECORD +0 -0
  4. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/REQUESTED +0 -0
  5. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/WHEEL +4 -0
  6. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/entry_points.txt +3 -0
  7. evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/licenses/LICENSE +201 -0
  8. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/INSTALLER +1 -0
  9. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/LICENSE.txt +20 -0
  10. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/METADATA +216 -0
  11. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/RECORD +41 -0
  12. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/REQUESTED +0 -0
  13. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/WHEEL +6 -0
  14. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/entry_points.txt +3 -0
  15. evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/top_level.txt +1 -0
  16. evalkit_tf446/lib/python3.10/site-packages/imageio/__init__.py +131 -0
  17. evalkit_tf446/lib/python3.10/site-packages/imageio/__main__.py +169 -0
  18. evalkit_tf446/lib/python3.10/site-packages/imageio/config/__init__.py +16 -0
  19. evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc +0 -0
  20. evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc +0 -0
  21. evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc +0 -0
  22. evalkit_tf446/lib/python3.10/site-packages/imageio/config/extensions.py +2002 -0
  23. evalkit_tf446/lib/python3.10/site-packages/imageio/config/extensions.pyi +24 -0
  24. evalkit_tf446/lib/python3.10/site-packages/imageio/config/plugins.py +782 -0
  25. evalkit_tf446/lib/python3.10/site-packages/imageio/config/plugins.pyi +28 -0
  26. evalkit_tf446/lib/python3.10/site-packages/imageio/freeze.py +11 -0
  27. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/__init__.py +103 -0
  28. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/_dicom.py +932 -0
  29. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/_freeimage.py +1312 -0
  30. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/bsdf.py +324 -0
  31. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/dicom.py +333 -0
  32. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/fits.py +126 -0
  33. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/npz.py +85 -0
  34. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/opencv.py +313 -0
  35. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/pillowmulti.py +338 -0
  36. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/pyav.py +1199 -0
  37. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/rawpy.py +191 -0
  38. evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/swf.py +336 -0
  39. evalkit_tf446/lib/python3.10/site-packages/imageio/py.typed +0 -0
  40. evalkit_tf446/lib/python3.10/site-packages/imageio/testing.py +69 -0
  41. evalkit_tf446/lib/python3.10/site-packages/imageio/typing.py +17 -0
  42. evalkit_tf446/lib/python3.10/site-packages/imageio/v2.py +676 -0
  43. evalkit_tf446/lib/python3.10/site-packages/imageio/v2.pyi +75 -0
  44. evalkit_tf446/lib/python3.10/site-packages/imageio/v3.py +259 -0
  45. evalkit_tf446/lib/python3.10/site-packages/imageio/v3.pyi +62 -0
  46. evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/__init__.cpython-310.pyc +0 -0
  47. evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc +0 -0
  48. evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-310.pyc +0 -0
  49. evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-310.pyc +0 -0
  50. evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-310.pyc +0 -0
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/METADATA ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: gradio
3
+ Version: 5.1.0
4
+ Summary: Python library for easily interacting with trained machine learning models
5
+ Project-URL: Homepage, https://github.com/gradio-app/gradio
6
+ Author-email: Abubakar Abid <gradio-team@huggingface.co>, Ali Abid <gradio-team@huggingface.co>, Ali Abdalla <gradio-team@huggingface.co>, Dawood Khan <gradio-team@huggingface.co>, Ahsen Khaliq <gradio-team@huggingface.co>, Pete Allen <gradio-team@huggingface.co>, Ömer Faruk Özdemir <gradio-team@huggingface.co>, Freddy A Boulton <gradio-team@huggingface.co>, Hannah Blair <gradio-team@huggingface.co>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: machine learning,reproducibility,visualization
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Scientific/Engineering :: Visualization
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: aiofiles<24.0,>=22.0
24
+ Requires-Dist: anyio<5.0,>=3.0
25
+ Requires-Dist: fastapi<1.0
26
+ Requires-Dist: ffmpy
27
+ Requires-Dist: gradio-client==1.4.0
28
+ Requires-Dist: httpx>=0.24.1
29
+ Requires-Dist: huggingface-hub>=0.25.1
30
+ Requires-Dist: jinja2<4.0
31
+ Requires-Dist: markupsafe~=2.0
32
+ Requires-Dist: numpy<3.0,>=1.0
33
+ Requires-Dist: orjson~=3.0
34
+ Requires-Dist: packaging
35
+ Requires-Dist: pandas<3.0,>=1.0
36
+ Requires-Dist: pillow<11.0,>=8.0
37
+ Requires-Dist: pydantic>=2.0
38
+ Requires-Dist: pydub
39
+ Requires-Dist: python-multipart>=0.0.9
40
+ Requires-Dist: pyyaml<7.0,>=5.0
41
+ Requires-Dist: ruff>=0.2.2; sys_platform != 'emscripten'
42
+ Requires-Dist: semantic-version~=2.0
43
+ Requires-Dist: tomlkit==0.12.0
44
+ Requires-Dist: typer<1.0,>=0.12; sys_platform != 'emscripten'
45
+ Requires-Dist: typing-extensions~=4.0
46
+ Requires-Dist: urllib3~=2.0; sys_platform == 'emscripten'
47
+ Requires-Dist: uvicorn>=0.14.0; sys_platform != 'emscripten'
48
+ Provides-Extra: oauth
49
+ Requires-Dist: authlib; extra == 'oauth'
50
+ Requires-Dist: itsdangerous; extra == 'oauth'
51
+ Description-Content-Type: text/markdown
52
+
53
+ <!-- DO NOT EDIT THIS FILE DIRECTLY. INSTEAD EDIT THE `readme_template.md` OR `guides/1)getting_started/1)quickstart.md` TEMPLATES AND THEN RUN `render_readme.py` SCRIPT. -->
54
+
55
+ <div align="center">
56
+
57
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/gradio.svg" alt="gradio" width=400>](https://gradio.app)<br>
58
+
59
+ [![gradio-backend](https://github.com/gradio-app/gradio/actions/workflows/test-python.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/test-python.yml)
60
+ [![gradio-ui](https://github.com/gradio-app/gradio/actions/workflows/tests-js.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/tests-js.yml)
61
+ [![PyPI](https://img.shields.io/pypi/v/gradio)](https://pypi.org/project/gradio/)
62
+ [![PyPI downloads](https://img.shields.io/pypi/dm/gradio)](https://pypi.org/project/gradio/)
63
+ ![Python version](https://img.shields.io/badge/python-3.10+-important)
64
+ [![Twitter follow](https://img.shields.io/twitter/follow/gradio?style=social&label=follow)](https://twitter.com/gradio)
65
+
66
+ [Website](https://gradio.app)
67
+ | [Documentation](https://gradio.app/docs/)
68
+ | [Guides](https://gradio.app/guides/)
69
+ | [Getting Started](https://gradio.app/getting_started/)
70
+ | [Examples](demo/)
71
+
72
+ </div>
73
+
74
+ <div align="center">
75
+
76
+ English | [中文](https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/zh-cn#readme)
77
+
78
+ </div>
79
+
80
+ # Gradio: Build Machine Learning Web Apps — in Python
81
+
82
+
83
+
84
+ Gradio is an open-source Python package that allows you to quickly **build** a demo or web application for your machine learning model, API, or any arbitrary Python function. You can then **share** a link to your demo or web application in just a few seconds using Gradio's built-in sharing features. *No JavaScript, CSS, or web hosting experience needed!*
85
+
86
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/gif-version.gif" style="padding-bottom: 10px">
87
+
88
+ It just takes a few lines of Python to create your own demo, so let's get started 💫
89
+
90
+ ### Installation
91
+
92
+ **Prerequisite**: Gradio 5 requires [Python 3.10 or higher](https://www.python.org/downloads/)
93
+
94
+
95
+ We recommend installing Gradio using `pip`, which is included by default in Python. Run this in your terminal or command prompt:
96
+
97
+ ```
98
+ pip install --upgrade gradio
99
+ ```
100
+
101
+
102
+ > [!TIP]
103
+ > It is best to install Gradio in a virtual environment. Detailed installation instructions for all common operating systems <a href="https://www.gradio.app/main/guides/installing-gradio-in-a-virtual-environment">are provided here</a>.
104
+
105
+ ### Building Your First Demo
106
+
107
+ You can run Gradio in your favorite code editor, Jupyter notebook, Google Colab, or anywhere else you write Python. Let's write your first Gradio app:
108
+
109
+
110
+ ```python
111
+ import gradio as gr
112
+
113
+ def greet(name, intensity):
114
+ return "Hello " * intensity + name + "!"
115
+
116
+ demo = gr.Interface(
117
+ fn=greet,
118
+ inputs=["text", "slider"],
119
+ outputs=["text"],
120
+ )
121
+
122
+ demo.launch()
123
+ ```
124
+
125
+
126
+
127
+ > [!TIP]
128
+ > We shorten the imported name from <code>gradio</code> to <code>gr</code> for better readability of code. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.
129
+
130
+ Now, run your code. If you've written the Python code in a file named, for example, `app.py`, then you would run `python app.py` from the terminal.
131
+
132
+ The demo below will open in a browser on [http://localhost:7860](http://localhost:7860) if running from a file. If you are running within a notebook, the demo will appear embedded within the notebook.
133
+
134
+ ![`hello_world_4` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/hello_world_4/screenshot.gif)
135
+
136
+ Type your name in the textbox on the left, drag the slider, and then press the Submit button. You should see a friendly greeting on the right.
137
+
138
+ > [!TIP]
139
+ > When developing locally, you can run your Gradio app in <strong>hot reload mode</strong>, which automatically reloads the Gradio app whenever you make changes to the file. To do this, simply type in <code>gradio</code> before the name of the file instead of <code>python</code>. In the example above, you would type: `gradio app.py` in your terminal. Learn more about hot reloading in the <a href="https://www.gradio.app/guides/developing-faster-with-reload-mode">Hot Reloading Guide</a>.
140
+
141
+
142
+ **Understanding the `Interface` Class**
143
+
144
+ You'll notice that in order to make your first demo, you created an instance of the `gr.Interface` class. The `Interface` class is designed to create demos for machine learning models which accept one or more inputs, and return one or more outputs.
145
+
146
+ The `Interface` class has three core arguments:
147
+
148
+ - `fn`: the function to wrap a user interface (UI) around
149
+ - `inputs`: the Gradio component(s) to use for the input. The number of components should match the number of arguments in your function.
150
+ - `outputs`: the Gradio component(s) to use for the output. The number of components should match the number of return values from your function.
151
+
152
+ The `fn` argument is very flexible -- you can pass *any* Python function that you want to wrap with a UI. In the example above, we saw a relatively simple function, but the function could be anything from a music generator to a tax calculator to the prediction function of a pretrained machine learning model.
153
+
154
+ The `input` and `output` arguments take one or more Gradio components. As we'll see, Gradio includes more than [30 built-in components](https://www.gradio.app/docs/gradio/introduction) (such as the `gr.Textbox()`, `gr.Image()`, and `gr.HTML()` components) that are designed for machine learning applications.
155
+
156
+ > [!TIP]
157
+ > For the `inputs` and `outputs` arguments, you can pass in the name of these components as a string (`"textbox"`) or an instance of the class (`gr.Textbox()`).
158
+
159
+ If your function accepts more than one argument, as is the case above, pass a list of input components to `inputs`, with each input component corresponding to one of the arguments of the function, in order. The same holds true if your function returns more than one value: simply pass in a list of components to `outputs`. This flexibility makes the `Interface` class a very powerful way to create demos.
160
+
161
+ We'll dive deeper into the `gr.Interface` on our series on [building Interfaces](https://www.gradio.app/main/guides/the-interface-class).
162
+
163
+ ### Sharing Your Demo
164
+
165
+ What good is a beautiful demo if you can't share it? Gradio lets you easily share a machine learning demo without having to worry about the hassle of hosting on a web server. Simply set `share=True` in `launch()`, and a publicly accessible URL will be created for your demo. Let's revisit our example demo, but change the last line as follows:
166
+
167
+ ```python
168
+ import gradio as gr
169
+
170
+ def greet(name):
171
+ return "Hello " + name + "!"
172
+
173
+ demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
174
+
175
+ demo.launch(share=True) # Share your demo with just 1 extra parameter 🚀
176
+ ```
177
+
178
+ When you run this code, a public URL will be generated for your demo in a matter of seconds, something like:
179
+
180
+ 👉 &nbsp; `https://a23dsf231adb.gradio.live`
181
+
182
+ Now, anyone around the world can try your Gradio demo from their browser, while the machine learning model and all computation continues to run locally on your computer.
183
+
184
+ To learn more about sharing your demo, read our dedicated guide on [sharing your Gradio application](https://www.gradio.app/guides/sharing-your-app).
185
+
186
+
187
+ ### An Overview of Gradio
188
+
189
+ So far, we've been discussing the `Interface` class, which is a high-level class that lets to build demos quickly with Gradio. But what else does Gradio do?
190
+
191
+ #### Chatbots with `gr.ChatInterface`
192
+
193
+ Gradio includes another high-level class, `gr.ChatInterface`, which is specifically designed to create Chatbot UIs. Similar to `Interface`, you supply a function and Gradio creates a fully working Chatbot UI. If you're interested in creating a chatbot, you can jump straight [our dedicated guide on `gr.ChatInterface`](https://www.gradio.app/guides/creating-a-chatbot-fast).
194
+
195
+ #### Custom Demos with `gr.Blocks`
196
+
197
+ Gradio also offers a low-level approach for designing web apps with more flexible layouts and data flows with the `gr.Blocks` class. Blocks allows you to do things like control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update properties/visibility of components based on user interaction — still all in Python.
198
+
199
+ You can build very custom and complex applications using `gr.Blocks()`. For example, the popular image generation [Automatic1111 Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is built using Gradio Blocks. We dive deeper into the `gr.Blocks` on our series on [building with Blocks](https://www.gradio.app/guides/blocks-and-event-listeners).
200
+
201
+
202
+ #### The Gradio Python & JavaScript Ecosystem
203
+
204
+ That's the gist of the core `gradio` Python library, but Gradio is actually so much more! It's an entire ecosystem of Python and JavaScript libraries that let you build machine learning applications, or query them programmatically, in Python or JavaScript. Here are other related parts of the Gradio ecosystem:
205
+
206
+ * [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) (`gradio_client`): query any Gradio app programmatically in Python.
207
+ * [Gradio JavaScript Client](https://www.gradio.app/guides/getting-started-with-the-js-client) (`@gradio/client`): query any Gradio app programmatically in JavaScript.
208
+ * [Gradio-Lite](https://www.gradio.app/guides/gradio-lite) (`@gradio/lite`): write Gradio apps in Python that run entirely in the browser (no server needed!), thanks to Pyodide.
209
+ * [Hugging Face Spaces](https://huggingface.co/spaces): the most popular place to host Gradio applications — for free!
210
+
211
+ ### What's Next?
212
+
213
+ Keep learning about Gradio sequentially using the Gradio Guides, which include explanations as well as example code and embedded interactive demos. Next up: [key features about Gradio demos](https://www.gradio.app/guides/key-features).
214
+
215
+ Or, if you already know the basics and are looking for something specific, you can search the more [technical API documentation](https://www.gradio.app/docs/).
216
+
217
+
218
+
219
+
220
+ ## Questions?
221
+
222
+ If you'd like to report a bug or have a feature request, please create an [issue on GitHub](https://github.com/gradio-app/gradio/issues/new/choose). For general questions about usage, we are available on [our Discord server](https://discord.com/invite/feTf9x3ZSB) and happy to help.
223
+
224
+ If you like Gradio, please leave us a ⭐ on GitHub!
225
+
226
+ ## Open Source Stack
227
+
228
+ Gradio is built on top of many wonderful open-source libraries!
229
+
230
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/huggingface_mini.svg" alt="huggingface" height=40>](https://huggingface.co)
231
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/python.svg" alt="python" height=40>](https://www.python.org)
232
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/fastapi.svg" alt="fastapi" height=40>](https://fastapi.tiangolo.com)
233
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/encode.svg" alt="encode" height=40>](https://www.encode.io)
234
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/svelte.svg" alt="svelte" height=40>](https://svelte.dev)
235
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/vite.svg" alt="vite" height=40>](https://vitejs.dev)
236
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/pnpm.svg" alt="pnpm" height=40>](https://pnpm.io)
237
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/tailwind.svg" alt="tailwind" height=40>](https://tailwindcss.com)
238
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/storybook.svg" alt="storybook" height=40>](https://storybook.js.org/)
239
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/chromatic.svg" alt="chromatic" height=40>](https://www.chromatic.com/)
240
+
241
+ ## License
242
+
243
+ Gradio is licensed under the Apache License 2.0 found in the [LICENSE](LICENSE) file in the root directory of this repository.
244
+
245
+ ## Citation
246
+
247
+ Also check out the paper _[Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild](https://arxiv.org/abs/1906.02569), ICML HILL 2019_, and please cite it if you use Gradio in your work.
248
+
249
+ ```
250
+ @article{abid2019gradio,
251
+ title = {Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild},
252
+ author = {Abid, Abubakar and Abdalla, Ali and Abid, Ali and Khan, Dawood and Alfozan, Abdulrahman and Zou, James},
253
+ journal = {arXiv preprint arXiv:1906.02569},
254
+ year = {2019},
255
+ }
256
+ ```
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/REQUESTED ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ gradio = gradio.cli:cli
3
+ upload_theme = gradio.themes.upload_theme:main
evalkit_tf446/lib/python3.10/site-packages/gradio-5.1.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2021 Peter Odding
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/METADATA ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: humanfriendly
3
+ Version: 10.0
4
+ Summary: Human friendly output for text interfaces using Python
5
+ Home-page: https://humanfriendly.readthedocs.io
6
+ Author: Peter Odding
7
+ Author-email: peter@peterodding.com
8
+ License: MIT
9
+ Platform: UNKNOWN
10
+ Classifier: Development Status :: 6 - Mature
11
+ Classifier: Environment :: Console
12
+ Classifier: Framework :: Sphinx :: Extension
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Natural Language :: English
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 2
19
+ Classifier: Programming Language :: Python :: 2.7
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.5
22
+ Classifier: Programming Language :: Python :: 3.6
23
+ Classifier: Programming Language :: Python :: 3.7
24
+ Classifier: Programming Language :: Python :: 3.8
25
+ Classifier: Programming Language :: Python :: 3.9
26
+ Classifier: Programming Language :: Python :: Implementation :: CPython
27
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
28
+ Classifier: Topic :: Communications
29
+ Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces
30
+ Classifier: Topic :: Software Development
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Classifier: Topic :: Software Development :: User Interfaces
33
+ Classifier: Topic :: System :: Shells
34
+ Classifier: Topic :: System :: System Shells
35
+ Classifier: Topic :: System :: Systems Administration
36
+ Classifier: Topic :: Terminals
37
+ Classifier: Topic :: Text Processing :: General
38
+ Classifier: Topic :: Text Processing :: Linguistic
39
+ Classifier: Topic :: Utilities
40
+ Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*
41
+ Requires-Dist: monotonic ; python_version == "2.7"
42
+ Requires-Dist: pyreadline ; sys_platform == "win32" and python_version<"3.8"
43
+ Requires-Dist: pyreadline3 ; sys_platform == "win32" and python_version>="3.8"
44
+
45
+ humanfriendly: Human friendly input/output in Python
46
+ ====================================================
47
+
48
+ .. image:: https://github.com/xolox/python-humanfriendly/actions/workflows/test.yml/badge.svg?branch=master
49
+ :target: https://github.com/xolox/python-humanfriendly/actions
50
+
51
+ .. image:: https://codecov.io/gh/xolox/python-humanfriendly/branch/master/graph/badge.svg?token=jYaj4T74TU
52
+ :target: https://codecov.io/gh/xolox/python-humanfriendly
53
+
54
+ The functions and classes in the `humanfriendly` package can be used to make
55
+ text interfaces more user friendly. Some example features:
56
+
57
+ - Parsing and formatting numbers, file sizes, pathnames and timespans in
58
+ simple, human friendly formats.
59
+
60
+ - Easy to use timers for long running operations, with human friendly
61
+ formatting of the resulting timespans.
62
+
63
+ - Prompting the user to select a choice from a list of options by typing the
64
+ option's number or a unique substring of the option.
65
+
66
+ - Terminal interaction including text styling (`ANSI escape sequences`_), user
67
+ friendly rendering of usage messages and querying the terminal for its
68
+ size.
69
+
70
+ The `humanfriendly` package is currently tested on Python 2.7, 3.5+ and PyPy
71
+ (2.7) on Linux and macOS. While the intention is to support Windows as well,
72
+ you may encounter some rough edges.
73
+
74
+ .. contents::
75
+ :local:
76
+
77
+ Getting started
78
+ ---------------
79
+
80
+ It's very simple to start using the `humanfriendly` package::
81
+
82
+ >>> from humanfriendly import format_size, parse_size
83
+ >>> from humanfriendly.prompts import prompt_for_input
84
+ >>> user_input = prompt_for_input("Enter a readable file size: ")
85
+
86
+ Enter a readable file size: 16G
87
+
88
+ >>> num_bytes = parse_size(user_input)
89
+ >>> print(num_bytes)
90
+ 16000000000
91
+ >>> print("You entered:", format_size(num_bytes))
92
+ You entered: 16 GB
93
+ >>> print("You entered:", format_size(num_bytes, binary=True))
94
+ You entered: 14.9 GiB
95
+
96
+ To get a demonstration of supported terminal text styles (based on
97
+ `ANSI escape sequences`_) you can run the following command::
98
+
99
+ $ humanfriendly --demo
100
+
101
+ Command line
102
+ ------------
103
+
104
+ .. A DRY solution to avoid duplication of the `humanfriendly --help' text:
105
+ ..
106
+ .. [[[cog
107
+ .. from humanfriendly.usage import inject_usage
108
+ .. inject_usage('humanfriendly.cli')
109
+ .. ]]]
110
+
111
+ **Usage:** `humanfriendly [OPTIONS]`
112
+
113
+ Human friendly input/output (text formatting) on the command
114
+ line based on the Python package with the same name.
115
+
116
+ **Supported options:**
117
+
118
+ .. csv-table::
119
+ :header: Option, Description
120
+ :widths: 30, 70
121
+
122
+
123
+ "``-c``, ``--run-command``","Execute an external command (given as the positional arguments) and render
124
+ a spinner and timer while the command is running. The exit status of the
125
+ command is propagated."
126
+ ``--format-table``,"Read tabular data from standard input (each line is a row and each
127
+ whitespace separated field is a column), format the data as a table and
128
+ print the resulting table to standard output. See also the ``--delimiter``
129
+ option."
130
+ "``-d``, ``--delimiter=VALUE``","Change the delimiter used by ``--format-table`` to ``VALUE`` (a string). By default
131
+ all whitespace is treated as a delimiter."
132
+ "``-l``, ``--format-length=LENGTH``","Convert a length count (given as the integer or float ``LENGTH``) into a human
133
+ readable string and print that string to standard output."
134
+ "``-n``, ``--format-number=VALUE``","Format a number (given as the integer or floating point number ``VALUE``) with
135
+ thousands separators and two decimal places (if needed) and print the
136
+ formatted number to standard output."
137
+ "``-s``, ``--format-size=BYTES``","Convert a byte count (given as the integer ``BYTES``) into a human readable
138
+ string and print that string to standard output."
139
+ "``-b``, ``--binary``","Change the output of ``-s``, ``--format-size`` to use binary multiples of bytes
140
+ (base-2) instead of the default decimal multiples of bytes (base-10)."
141
+ "``-t``, ``--format-timespan=SECONDS``","Convert a number of seconds (given as the floating point number ``SECONDS``)
142
+ into a human readable timespan and print that string to standard output."
143
+ ``--parse-length=VALUE``,"Parse a human readable length (given as the string ``VALUE``) and print the
144
+ number of metres to standard output."
145
+ ``--parse-size=VALUE``,"Parse a human readable data size (given as the string ``VALUE``) and print the
146
+ number of bytes to standard output."
147
+ ``--demo``,"Demonstrate changing the style and color of the terminal font using ANSI
148
+ escape sequences."
149
+ "``-h``, ``--help``",Show this message and exit.
150
+
151
+ .. [[[end]]]
152
+
153
+ A note about size units
154
+ -----------------------
155
+
156
+ When I originally published the `humanfriendly` package I went with binary
157
+ multiples of bytes (powers of two). It was pointed out several times that this
158
+ was a poor choice (see issue `#4`_ and pull requests `#8`_ and `#9`_) and thus
159
+ the new default became decimal multiples of bytes (powers of ten):
160
+
161
+ +------+---------------+---------------+
162
+ | Unit | Binary value | Decimal value |
163
+ +------+---------------+---------------+
164
+ | KB | 1024 | 1000 +
165
+ +------+---------------+---------------+
166
+ | MB | 1048576 | 1000000 |
167
+ +------+---------------+---------------+
168
+ | GB | 1073741824 | 1000000000 |
169
+ +------+---------------+---------------+
170
+ | TB | 1099511627776 | 1000000000000 |
171
+ +------+---------------+---------------+
172
+ | etc | | |
173
+ +------+---------------+---------------+
174
+
175
+ The option to use binary multiples of bytes remains by passing the keyword
176
+ argument `binary=True` to the `format_size()`_ and `parse_size()`_ functions.
177
+
178
+ Windows support
179
+ ---------------
180
+
181
+ Windows 10 gained native support for ANSI escape sequences which means commands
182
+ like ``humanfriendly --demo`` should work out of the box (if your system is
183
+ up-to-date enough). If this doesn't work then you can install the colorama_
184
+ package, it will be used automatically once installed.
185
+
186
+ Contact
187
+ -------
188
+
189
+ The latest version of `humanfriendly` is available on PyPI_ and GitHub_. The
190
+ documentation is hosted on `Read the Docs`_ and includes a changelog_. For bug
191
+ reports please create an issue on GitHub_. If you have questions, suggestions,
192
+ etc. feel free to send me an e-mail at `peter@peterodding.com`_.
193
+
194
+ License
195
+ -------
196
+
197
+ This software is licensed under the `MIT license`_.
198
+
199
+ © 2021 Peter Odding.
200
+
201
+ .. External references:
202
+ .. _#4: https://github.com/xolox/python-humanfriendly/issues/4
203
+ .. _#8: https://github.com/xolox/python-humanfriendly/pull/8
204
+ .. _#9: https://github.com/xolox/python-humanfriendly/pull/9
205
+ .. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code
206
+ .. _changelog: https://humanfriendly.readthedocs.io/en/latest/changelog.html
207
+ .. _colorama: https://pypi.org/project/colorama
208
+ .. _format_size(): https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_size
209
+ .. _GitHub: https://github.com/xolox/python-humanfriendly
210
+ .. _MIT license: https://en.wikipedia.org/wiki/MIT_License
211
+ .. _parse_size(): https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.parse_size
212
+ .. _peter@peterodding.com: peter@peterodding.com
213
+ .. _PyPI: https://pypi.org/project/humanfriendly
214
+ .. _Read the Docs: https://humanfriendly.readthedocs.io
215
+
216
+
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/RECORD ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/humanfriendly,sha256=L4sFudVXsiJ6ccfUnOU4WBxyxC-9lBPyGXRe1-5_lBY,235
2
+ humanfriendly-10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
3
+ humanfriendly-10.0.dist-info/LICENSE.txt,sha256=SsSPQReAnyc0BmFQRQ8SCzuxEKwdOzIXB5XgVg27wfU,1056
4
+ humanfriendly-10.0.dist-info/METADATA,sha256=aLs0k4jN_spgKsw0Vbg6ey_jy-hAJeJ0k7y-dvOrbII,9201
5
+ humanfriendly-10.0.dist-info/RECORD,,
6
+ humanfriendly-10.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ humanfriendly-10.0.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
8
+ humanfriendly-10.0.dist-info/entry_points.txt,sha256=hU-ADsGls3mgf3plBt9B-oYLCtBDQiUJZ00khuAoqXc,58
9
+ humanfriendly-10.0.dist-info/top_level.txt,sha256=7eKAKhckmlD4ZoWJkWmhnTs1pnP_bzF-56VTq0D7WIo,14
10
+ humanfriendly/__init__.py,sha256=sPCMQv16m3p8xYwd3N3kUs1rewVJB3ZGDBkF0_8v6vo,31725
11
+ humanfriendly/__pycache__/__init__.cpython-310.pyc,,
12
+ humanfriendly/__pycache__/case.cpython-310.pyc,,
13
+ humanfriendly/__pycache__/cli.cpython-310.pyc,,
14
+ humanfriendly/__pycache__/compat.cpython-310.pyc,,
15
+ humanfriendly/__pycache__/decorators.cpython-310.pyc,,
16
+ humanfriendly/__pycache__/deprecation.cpython-310.pyc,,
17
+ humanfriendly/__pycache__/prompts.cpython-310.pyc,,
18
+ humanfriendly/__pycache__/sphinx.cpython-310.pyc,,
19
+ humanfriendly/__pycache__/tables.cpython-310.pyc,,
20
+ humanfriendly/__pycache__/testing.cpython-310.pyc,,
21
+ humanfriendly/__pycache__/tests.cpython-310.pyc,,
22
+ humanfriendly/__pycache__/text.cpython-310.pyc,,
23
+ humanfriendly/__pycache__/usage.cpython-310.pyc,,
24
+ humanfriendly/case.py,sha256=fkIinj4V1S8Xl3OCSYSgqKoGzCCbVJOjI5ZznViCT1Q,6008
25
+ humanfriendly/cli.py,sha256=ZpGqTHLwfLjFACsQacYkN9DiBZkGecPzIHysliWN1i8,9822
26
+ humanfriendly/compat.py,sha256=7qoFGMNFizGhs5BIyiMKTDUq29DxzuXGX4MRoZLo4ms,3984
27
+ humanfriendly/decorators.py,sha256=ivxB-U9dfXUjCl4GZ8g_gKFC4a3uyxDVi-3rlxPjvJo,1501
28
+ humanfriendly/deprecation.py,sha256=bdx1_T8L1gF635E41E6bYTqie9P3o7rY6n4wohjkLLk,9499
29
+ humanfriendly/prompts.py,sha256=8PSJ1Hpr3ld6YkCaXQsTHAep9BtTKYlKmQi1RiaHIEc,16335
30
+ humanfriendly/sphinx.py,sha256=BrFxK-rX3LN4iMqgNFuOTweYfppYp--O3HqWBlu05M0,11452
31
+ humanfriendly/tables.py,sha256=lCDnEKyyZRmrIHrDlUzzVpg9z6lKOO8ldP4fh1gzMBI,13968
32
+ humanfriendly/terminal/__init__.py,sha256=5BzxVHKriznclRjrWwYEk2l1ct0q0WdupJIrkuI9glc,30759
33
+ humanfriendly/terminal/__pycache__/__init__.cpython-310.pyc,,
34
+ humanfriendly/terminal/__pycache__/html.cpython-310.pyc,,
35
+ humanfriendly/terminal/__pycache__/spinners.cpython-310.pyc,,
36
+ humanfriendly/terminal/html.py,sha256=_csUZ4hID0ATwTvPXU8KrAe6ZzD_gUS7_tN3FmCHA4Q,16747
37
+ humanfriendly/terminal/spinners.py,sha256=o7nkn8rBdTqr-XHIT972sIgIuxiDymQ5kPVkBzR7utE,11323
38
+ humanfriendly/testing.py,sha256=hErsmBN5Crej5k1P_I0dhQK8IAwFr1IOZ9kQPIrZUys,24359
39
+ humanfriendly/tests.py,sha256=3bkasrRgw0cAdZFHgmTo4DUHgXEnlHtRoq_t2MEafbc,68919
40
+ humanfriendly/text.py,sha256=_WBG4SZ4bT5SH94zLUdfmB6NXbvc4gBYECEmQYXJ1sE,16212
41
+ humanfriendly/usage.py,sha256=AhPo6DcvaBRIFGWNctU22McMzN3Ryc6ZCC83kt2Zbk4,13768
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/REQUESTED ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.34.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ humanfriendly = humanfriendly.cli:main
3
+
evalkit_tf446/lib/python3.10/site-packages/humanfriendly-10.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ humanfriendly
evalkit_tf446/lib/python3.10/site-packages/imageio/__init__.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2014-2020, imageio contributors
3
+ # imageio is distributed under the terms of the (new) BSD License.
4
+
5
+ # This docstring is used at the index of the documentation pages, and
6
+ # gets inserted into a slightly larger description (in setup.py) for
7
+ # the page on Pypi:
8
+ """
9
+ Imageio is a Python library that provides an easy interface to read and
10
+ write a wide range of image data, including animated images, volumetric
11
+ data, and scientific formats. It is cross-platform, runs on Python 3.5+,
12
+ and is easy to install.
13
+
14
+ Main website: https://imageio.readthedocs.io/
15
+ """
16
+
17
+ # flake8: noqa
18
+
19
+ __version__ = "2.36.0"
20
+
21
+ import warnings
22
+
23
+ # Load some bits from core
24
+ from .core import FormatManager, RETURN_BYTES
25
+
26
+ # Instantiate the old format manager
27
+ formats = FormatManager()
28
+ show_formats = formats.show
29
+
30
+ from . import v2
31
+ from . import v3
32
+ from . import plugins
33
+
34
+ # import config after core to avoid circular import
35
+ from . import config
36
+
37
+ # import all APIs into the top level (meta API)
38
+ from .v2 import (
39
+ imread as imread_v2,
40
+ mimread,
41
+ volread,
42
+ mvolread,
43
+ imwrite,
44
+ mimwrite,
45
+ volwrite,
46
+ mvolwrite,
47
+ # aliases
48
+ get_reader as read,
49
+ get_writer as save,
50
+ imwrite as imsave,
51
+ mimwrite as mimsave,
52
+ volwrite as volsave,
53
+ mvolwrite as mvolsave,
54
+ # misc
55
+ help,
56
+ get_reader,
57
+ get_writer,
58
+ )
59
+ from .v3 import (
60
+ imopen,
61
+ # imread, # Will take over once v3 is released
62
+ # imwrite, # Will take over once v3 is released
63
+ imiter,
64
+ )
65
+
66
+
67
+ def imread(uri, format=None, **kwargs):
68
+ """imread(uri, format=None, **kwargs)
69
+
70
+ Reads an image from the specified file. Returns a numpy array, which
71
+ comes with a dict of meta data at its 'meta' attribute.
72
+
73
+ Note that the image data is returned as-is, and may not always have
74
+ a dtype of uint8 (and thus may differ from what e.g. PIL returns).
75
+
76
+ Parameters
77
+ ----------
78
+ uri : {str, pathlib.Path, bytes, file}
79
+ The resource to load the image from, e.g. a filename, pathlib.Path,
80
+ http address or file object, see the docs for more info.
81
+ format : str
82
+ The format to use to read the file. By default imageio selects
83
+ the appropriate for you based on the filename and its contents.
84
+ kwargs : ...
85
+ Further keyword arguments are passed to the reader. See :func:`.help`
86
+ to see what arguments are available for a particular format.
87
+ """
88
+
89
+ warnings.warn(
90
+ "Starting with ImageIO v3 the behavior of this function will switch to that of"
91
+ " iio.v3.imread. To keep the current behavior (and make this warning disappear)"
92
+ " use `import imageio.v2 as imageio` or call `imageio.v2.imread` directly.",
93
+ DeprecationWarning,
94
+ stacklevel=2,
95
+ )
96
+
97
+ return imread_v2(uri, format=format, **kwargs)
98
+
99
+
100
+ __all__ = [
101
+ "v2",
102
+ "v3",
103
+ "config",
104
+ "plugins",
105
+ # v3 API
106
+ "imopen",
107
+ "imread",
108
+ "imwrite",
109
+ "imiter",
110
+ # v2 API
111
+ "mimread",
112
+ "volread",
113
+ "mvolread",
114
+ "imwrite",
115
+ "mimwrite",
116
+ "volwrite",
117
+ "mvolwrite",
118
+ # v2 aliases
119
+ "read",
120
+ "save",
121
+ "imsave",
122
+ "mimsave",
123
+ "volsave",
124
+ "mvolsave",
125
+ # functions to deprecate
126
+ "help",
127
+ "get_reader",
128
+ "get_writer",
129
+ "formats",
130
+ "show_formats",
131
+ ]
evalkit_tf446/lib/python3.10/site-packages/imageio/__main__.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Console scripts and associated helper methods for imageio.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+ from os import path as op
8
+ import shutil
9
+ import sys
10
+
11
+
12
+ from . import plugins
13
+ from .core import util
14
+
15
+ # A list of plugins that require binaries from the imageio-binaries
16
+ # repository. These plugins must implement the `download` method.
17
+ PLUGINS_WITH_BINARIES = ["freeimage"]
18
+
19
+
20
+ def download_bin(plugin_names=["all"], package_dir=False):
21
+ """Download binary dependencies of plugins
22
+
23
+ This is a convenience method for downloading the binaries
24
+ (e.g. for freeimage) from the imageio-binaries
25
+ repository.
26
+
27
+ Parameters
28
+ ----------
29
+ plugin_names: list
30
+ A list of imageio plugin names. If it contains "all", all
31
+ binary dependencies are downloaded.
32
+ package_dir: bool
33
+ If set to `True`, the binaries will be downloaded to the
34
+ `resources` directory of the imageio package instead of
35
+ to the users application data directory. Note that this
36
+ might require administrative rights if imageio is installed
37
+ in a system directory.
38
+ """
39
+ if plugin_names.count("all"):
40
+ # Use all plugins
41
+ plugin_names = PLUGINS_WITH_BINARIES
42
+
43
+ plugin_names.sort()
44
+ print("Ascertaining binaries for: {}.".format(", ".join(plugin_names)))
45
+
46
+ if package_dir:
47
+ # Download the binaries to the `resources` directory
48
+ # of imageio. If imageio comes as an .egg, then a cache
49
+ # directory will be created by pkg_resources (requires setuptools).
50
+ # see `imageio.core.util.resource_dirs`
51
+ # and `imageio.core.utilresource_package_dir`
52
+ directory = util.resource_package_dir()
53
+ else:
54
+ directory = None
55
+
56
+ for plg in plugin_names:
57
+ if plg not in PLUGINS_WITH_BINARIES:
58
+ msg = "Plugin {} not registered for binary download!".format(plg)
59
+ raise Exception(msg)
60
+ mod = getattr(plugins, plg)
61
+ mod.download(directory=directory)
62
+
63
+
64
+ def download_bin_main():
65
+ """Argument-parsing wrapper for `download_bin`"""
66
+ description = "Download plugin binary dependencies"
67
+ phelp = (
68
+ "Plugin name for which to download the binary. "
69
+ + "If no argument is given, all binaries are downloaded."
70
+ )
71
+ dhelp = (
72
+ "Download the binaries to the package directory "
73
+ + "(default is the users application data directory). "
74
+ + "This might require administrative rights."
75
+ )
76
+ example_text = (
77
+ "examples:\n"
78
+ + " imageio_download_bin all\n"
79
+ + " imageio_download_bin freeimage\n"
80
+ )
81
+ parser = argparse.ArgumentParser(
82
+ description=description,
83
+ epilog=example_text,
84
+ formatter_class=argparse.RawDescriptionHelpFormatter,
85
+ )
86
+ parser.add_argument("plugin", type=str, nargs="*", default="all", help=phelp)
87
+ parser.add_argument(
88
+ "--package-dir",
89
+ dest="package_dir",
90
+ action="store_true",
91
+ default=False,
92
+ help=dhelp,
93
+ )
94
+ args = parser.parse_args()
95
+ download_bin(plugin_names=args.plugin, package_dir=args.package_dir)
96
+
97
+
98
+ def remove_bin(plugin_names=["all"]):
99
+ """Remove binary dependencies of plugins
100
+
101
+ This is a convenience method that removes all binaries
102
+ dependencies for plugins downloaded by imageio.
103
+
104
+ Notes
105
+ -----
106
+ It only makes sense to use this method if the binaries
107
+ are corrupt.
108
+ """
109
+ if plugin_names.count("all"):
110
+ # Use all plugins
111
+ plugin_names = PLUGINS_WITH_BINARIES
112
+
113
+ print("Removing binaries for: {}.".format(", ".join(plugin_names)))
114
+
115
+ rdirs = util.resource_dirs()
116
+
117
+ for plg in plugin_names:
118
+ if plg not in PLUGINS_WITH_BINARIES:
119
+ msg = "Plugin {} not registered for binary download!".format(plg)
120
+ raise Exception(msg)
121
+
122
+ not_removed = []
123
+ for rd in rdirs:
124
+ # plugin name is in subdirectories
125
+ for rsub in os.listdir(rd):
126
+ if rsub in plugin_names:
127
+ plgdir = op.join(rd, rsub)
128
+ try:
129
+ shutil.rmtree(plgdir)
130
+ except Exception:
131
+ not_removed.append(plgdir)
132
+ if not_removed:
133
+ nrs = ",".join(not_removed)
134
+ msg2 = (
135
+ "These plugins files could not be removed: {}\n".format(nrs)
136
+ + "Make sure they are not used by any program and try again."
137
+ )
138
+ raise Exception(msg2)
139
+
140
+
141
+ def remove_bin_main():
142
+ """Argument-parsing wrapper for `remove_bin`"""
143
+ description = "Remove plugin binary dependencies"
144
+ phelp = (
145
+ "Plugin name for which to remove the binary. "
146
+ + "If no argument is given, all binaries are removed."
147
+ )
148
+ example_text = (
149
+ "examples:\n"
150
+ + " imageio_remove_bin all\n"
151
+ + " imageio_remove_bin freeimage\n"
152
+ )
153
+ parser = argparse.ArgumentParser(
154
+ description=description,
155
+ epilog=example_text,
156
+ formatter_class=argparse.RawDescriptionHelpFormatter,
157
+ )
158
+ parser.add_argument("plugin", type=str, nargs="*", default="all", help=phelp)
159
+ args = parser.parse_args()
160
+ remove_bin(plugin_names=args.plugin)
161
+
162
+
163
+ if __name__ == "__main__":
164
+ if len(sys.argv) > 1 and sys.argv[1] == "download_bin":
165
+ download_bin_main()
166
+ elif len(sys.argv) > 1 and sys.argv[1] == "remove_bin":
167
+ remove_bin_main()
168
+ else:
169
+ raise RuntimeError("Invalid use of the imageio CLI")
evalkit_tf446/lib/python3.10/site-packages/imageio/config/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .extensions import (
2
+ extension_list,
3
+ known_extensions,
4
+ FileExtension,
5
+ video_extensions,
6
+ )
7
+ from .plugins import known_plugins, PluginConfig
8
+
9
+ __all__ = [
10
+ "known_plugins",
11
+ "PluginConfig",
12
+ "extension_list",
13
+ "known_extensions",
14
+ "FileExtension",
15
+ "video_extensions",
16
+ ]
evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (419 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc ADDED
Binary file (32.5 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/imageio/config/extensions.py ADDED
@@ -0,0 +1,2002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of objects representing each file extension recognized by ImageIO. If an
3
+ extension is not listed here it is still supported, as long as there exists a
4
+ supporting backend.
5
+
6
+ """
7
+
8
+
9
+ class FileExtension:
10
+ """File Extension Metadata
11
+
12
+ This class holds information about a image file format associated with a
13
+ given extension. This information is used to track plugins that are known to
14
+ be able to handle a particular format. It also contains additional
15
+ information about a format, which is used when creating the supported format
16
+ docs.
17
+
18
+ Plugins known to be able to handle this format are ordered by a ``priority``
19
+ list. This list is used to determine the ideal plugin to use when choosing a
20
+ plugin based on file extension.
21
+
22
+ Parameters
23
+ ----------
24
+ extension : str
25
+ The name of the extension including the initial dot, e.g. ".png".
26
+ priority : List
27
+ A list of plugin names (entries in config.known_plugins) that can handle
28
+ this format. The position of a plugin expresses a preference, e.g.
29
+ ["plugin1", "plugin2"] indicates that, if available, plugin1 should be
30
+ preferred over plugin2 when handling a request related to this format.
31
+ name : str
32
+ The full name of the format.
33
+ description : str
34
+ A description of the format.
35
+ external_link : str
36
+ A link to further information about the format. Typically, the format's
37
+ specification.
38
+ volume_support : str
39
+ If True, the format/extension supports volumetric image data.
40
+
41
+ Examples
42
+ --------
43
+ >>> FileExtension(
44
+ name="Bitmap",
45
+ extension=".bmp",
46
+ priority=["pillow", "BMP-PIL", "BMP-FI", "ITK"],
47
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
48
+ )
49
+
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ extension,
56
+ priority,
57
+ name=None,
58
+ description=None,
59
+ external_link=None,
60
+ volume_support=False
61
+ ):
62
+ self.extension = extension
63
+ self.priority = priority
64
+ self.name = name
65
+ self.description = description
66
+ self.external_link = external_link
67
+ self.default_priority = priority.copy()
68
+ self.volume_support = volume_support
69
+
70
+ def reset(self):
71
+ self.priority = self.default_priority.copy()
72
+
73
+
74
+ extension_list = [
75
+ FileExtension(
76
+ name="Hasselblad raw",
77
+ extension=".3fr",
78
+ priority=["RAW-FI"],
79
+ ),
80
+ FileExtension(
81
+ name="Sony alpha",
82
+ extension=".arw",
83
+ priority=["RAW-FI"],
84
+ ),
85
+ FileExtension(
86
+ name="Animated Portable Network Graphics",
87
+ external_link="https://en.wikipedia.org/wiki/APNG",
88
+ extension=".apng",
89
+ priority=["pillow", "pyav"],
90
+ ),
91
+ FileExtension(
92
+ name="Audio Video Interleave",
93
+ extension=".avi",
94
+ priority=["FFMPEG"],
95
+ ),
96
+ FileExtension(
97
+ name="Casio raw format",
98
+ extension=".bay",
99
+ priority=["RAW-FI"],
100
+ ),
101
+ FileExtension(
102
+ extension=".blp",
103
+ priority=["pillow"],
104
+ ),
105
+ FileExtension(
106
+ name="Bitmap",
107
+ extension=".bmp",
108
+ priority=["pillow", "BMP-PIL", "BMP-FI", "ITK", "pyav", "opencv"],
109
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
110
+ ),
111
+ FileExtension(
112
+ name="Device-Independent Bitmap",
113
+ extension=".dip",
114
+ priority=["opencv"],
115
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
116
+ ),
117
+ FileExtension(
118
+ name="Re-Volt mipmap",
119
+ extension=".bmq",
120
+ priority=["RAW-FI"],
121
+ ),
122
+ FileExtension(
123
+ name="Binary Structured Data Format",
124
+ extension=".bsdf",
125
+ priority=["BSDF"],
126
+ external_link="http://bsdf.io/",
127
+ ),
128
+ FileExtension(
129
+ name="Binary Universal Form for the Representation of meteorological data",
130
+ extension=".bufr",
131
+ priority=["pillow", "BUFR-PIL"],
132
+ ),
133
+ FileExtension(
134
+ name="Silicon Graphics Image",
135
+ extension=".bw",
136
+ priority=["pillow", "SGI-PIL", "SGI-FI"],
137
+ ),
138
+ FileExtension(
139
+ name="Scirra Construct",
140
+ extension=".cap",
141
+ priority=["RAW-FI"],
142
+ ),
143
+ FileExtension(
144
+ name="AMETEK High Speed Camera Format",
145
+ extension=".cine",
146
+ priority=["RAW-FI"],
147
+ external_link="https://phantomhighspeed-knowledge.secure.force.com/servlet/fileField?id=0BE1N000000kD2i#:~:text=Cine%20is%20a%20video%20file,camera%20model%20and%20image%20resolution",
148
+ ),
149
+ FileExtension(extension=".cr2", priority=["RAW-FI"]),
150
+ FileExtension(
151
+ extension=".crw",
152
+ priority=["RAW-FI"],
153
+ ),
154
+ FileExtension(
155
+ extension=".cs1",
156
+ priority=["RAW-FI"],
157
+ ),
158
+ FileExtension(
159
+ name="Computerized Tomography",
160
+ extension=".ct",
161
+ priority=["DICOM"],
162
+ ),
163
+ FileExtension(
164
+ name="Windows Cursor Icons",
165
+ extension=".cur",
166
+ priority=["pillow", "CUR-PIL"],
167
+ ),
168
+ FileExtension(
169
+ name="Dr. Halo",
170
+ extension=".cut",
171
+ priority=["CUT-FI"],
172
+ ),
173
+ FileExtension(
174
+ extension=".dc2",
175
+ priority=["RAW-FI"],
176
+ ),
177
+ FileExtension(
178
+ name="DICOM file format",
179
+ extension=".dcm",
180
+ priority=["DICOM", "ITK"],
181
+ ),
182
+ FileExtension(
183
+ extension=".dcr",
184
+ priority=["RAW-FI"],
185
+ ),
186
+ FileExtension(
187
+ name="Intel DCX",
188
+ extension=".dcx",
189
+ priority=["pillow", "DCX-PIL"],
190
+ ),
191
+ FileExtension(
192
+ name="DirectX Texture Container",
193
+ extension=".dds",
194
+ priority=["pillow", "DDS-FI", "DDS-PIL"],
195
+ ),
196
+ FileExtension(
197
+ name="Windows Bitmap",
198
+ extension=".dib",
199
+ priority=["pillow", "DIB-PIL"],
200
+ ),
201
+ FileExtension(
202
+ name="DICOM file format",
203
+ extension=".dicom",
204
+ priority=["ITK"],
205
+ ),
206
+ FileExtension(
207
+ extension=".dng",
208
+ priority=["RAW-FI"],
209
+ ),
210
+ FileExtension(
211
+ extension=".drf",
212
+ priority=["RAW-FI"],
213
+ ),
214
+ FileExtension(
215
+ extension=".dsc",
216
+ priority=["RAW-FI"],
217
+ ),
218
+ FileExtension(
219
+ name="Enhanced Compression Wavelet",
220
+ extension=".ecw",
221
+ priority=["GDAL"],
222
+ ),
223
+ FileExtension(
224
+ name="Windows Metafile",
225
+ extension=".emf",
226
+ priority=["pillow", "WMF-PIL"],
227
+ ),
228
+ FileExtension(
229
+ name="Encapsulated Postscript",
230
+ extension=".eps",
231
+ priority=["pillow", "EPS-PIL"],
232
+ ),
233
+ FileExtension(
234
+ extension=".erf",
235
+ priority=["RAW-FI"],
236
+ ),
237
+ FileExtension(
238
+ name="OpenEXR",
239
+ extension=".exr",
240
+ external_link="https://openexr.readthedocs.io/en/latest/",
241
+ priority=["EXR-FI", "pyav", "opencv"],
242
+ ),
243
+ FileExtension(
244
+ extension=".fff",
245
+ priority=["RAW-FI"],
246
+ ),
247
+ FileExtension(
248
+ name="Flexible Image Transport System File",
249
+ extension=".fit",
250
+ priority=["pillow", "FITS-PIL", "FITS"],
251
+ ),
252
+ FileExtension(
253
+ name="Flexible Image Transport System File",
254
+ extension=".fits",
255
+ priority=["pillow", "FITS-PIL", "FITS", "pyav"],
256
+ ),
257
+ FileExtension(
258
+ name="Autodesk FLC Animation",
259
+ extension=".flc",
260
+ priority=["pillow", "FLI-PIL"],
261
+ ),
262
+ FileExtension(
263
+ name="Autodesk FLI Animation",
264
+ extension=".fli",
265
+ priority=["pillow", "FLI-PIL"],
266
+ ),
267
+ FileExtension(
268
+ name="Kodak FlashPix",
269
+ extension=".fpx",
270
+ priority=["pillow", "FPX-PIL"],
271
+ ),
272
+ FileExtension(
273
+ name="Independence War 2: Edge Of Chaos Texture Format",
274
+ extension=".ftc",
275
+ priority=["pillow", "FTEX-PIL"],
276
+ ),
277
+ FileExtension(
278
+ name="Flexible Image Transport System File",
279
+ extension=".fts",
280
+ priority=["FITS"],
281
+ ),
282
+ FileExtension(
283
+ name="Independence War 2: Edge Of Chaos Texture Format",
284
+ extension=".ftu",
285
+ priority=["pillow", "FTEX-PIL"],
286
+ ),
287
+ FileExtension(
288
+ name="Flexible Image Transport System File",
289
+ extension=".fz",
290
+ priority=["FITS"],
291
+ ),
292
+ FileExtension(
293
+ name="Raw fax format CCITT G.3",
294
+ extension=".g3",
295
+ priority=["G3-FI"],
296
+ ),
297
+ FileExtension(
298
+ name="GIMP brush file",
299
+ extension=".gbr",
300
+ priority=["pillow", "GBR-PIL"],
301
+ ),
302
+ FileExtension(
303
+ name="Grassroots DICOM",
304
+ extension=".gdcm",
305
+ priority=["ITK"],
306
+ ),
307
+ FileExtension(
308
+ name="Graphics Interchange Format",
309
+ extension=".gif",
310
+ priority=["pillow", "GIF-PIL", "pyav"],
311
+ ),
312
+ FileExtension(
313
+ name="UMDS GIPL",
314
+ extension=".gipl",
315
+ priority=["ITK"],
316
+ ),
317
+ FileExtension(
318
+ name="gridded meteorological data",
319
+ extension=".grib",
320
+ priority=["pillow", "GRIB-PIL"],
321
+ ),
322
+ FileExtension(
323
+ name="Hierarchical Data Format 5",
324
+ extension=".h5",
325
+ priority=["pillow", "HDF5-PIL"],
326
+ ),
327
+ FileExtension(
328
+ name="Hierarchical Data Format 5",
329
+ extension=".hdf",
330
+ priority=["pillow", "HDF5-PIL"],
331
+ ),
332
+ FileExtension(
333
+ name="Hierarchical Data Format 5",
334
+ extension=".hdf5",
335
+ priority=["ITK"],
336
+ ),
337
+ FileExtension(
338
+ name="JPEG Extended Range",
339
+ extension=".hdp",
340
+ priority=["JPEG-XR-FI"],
341
+ ),
342
+ FileExtension(
343
+ name="High Dynamic Range Image",
344
+ extension=".hdr",
345
+ priority=["HDR-FI", "ITK", "opencv"],
346
+ ),
347
+ FileExtension(
348
+ extension=".ia",
349
+ priority=["RAW-FI"],
350
+ ),
351
+ FileExtension(
352
+ extension=".icb",
353
+ priority=["pillow"],
354
+ ),
355
+ FileExtension(
356
+ name="Mac OS Icon File",
357
+ extension=".icns",
358
+ priority=["pillow", "ICNS-PIL"],
359
+ ),
360
+ FileExtension(
361
+ name="Windows Icon File",
362
+ extension=".ico",
363
+ priority=["pillow", "ICO-FI", "ICO-PIL", "pyav"],
364
+ ),
365
+ FileExtension(
366
+ name="ILBM Interleaved Bitmap",
367
+ extension=".iff",
368
+ priority=["IFF-FI"],
369
+ ),
370
+ FileExtension(
371
+ name="IPTC/NAA",
372
+ extension=".iim",
373
+ priority=["pillow", "IPTC-PIL"],
374
+ ),
375
+ FileExtension(
376
+ extension=".iiq",
377
+ priority=["RAW-FI"],
378
+ ),
379
+ FileExtension(
380
+ name="IFUNC Image Memory",
381
+ extension=".im",
382
+ priority=["pillow", "IM-PIL"],
383
+ ),
384
+ FileExtension(
385
+ extension=".img",
386
+ priority=["ITK", "GDAL"],
387
+ ),
388
+ FileExtension(
389
+ extension=".img.gz",
390
+ priority=["ITK"],
391
+ ),
392
+ FileExtension(
393
+ name="IM Tools",
394
+ extension=".IMT",
395
+ priority=["pillow", "IMT-PIL"],
396
+ ),
397
+ FileExtension(
398
+ name="Image Processing Lab",
399
+ extension=".ipl",
400
+ priority=["ITK"],
401
+ ),
402
+ FileExtension(
403
+ name="JPEG 2000",
404
+ extension=".j2c",
405
+ priority=["pillow", "J2K-FI", "JPEG2000-PIL", "pyav"],
406
+ ),
407
+ FileExtension(
408
+ name="JPEG 2000",
409
+ extension=".j2k",
410
+ priority=["pillow", "J2K-FI", "JPEG2000-PIL", "pyav"],
411
+ ),
412
+ FileExtension(
413
+ name="JPEG",
414
+ extension=".jfif",
415
+ priority=["pillow", "JPEG-PIL"],
416
+ ),
417
+ FileExtension(
418
+ name="JPEG",
419
+ extension=".jif",
420
+ priority=["JPEG-FI"],
421
+ ),
422
+ FileExtension(
423
+ name="JPEG Network Graphics",
424
+ extension=".jng",
425
+ priority=["JNG-FI"],
426
+ ),
427
+ FileExtension(
428
+ name="JPEG 2000",
429
+ extension=".jp2",
430
+ priority=["pillow", "JP2-FI", "JPEG2000-PIL", "pyav", "opencv"],
431
+ ),
432
+ FileExtension(
433
+ name="JPEG 2000",
434
+ extension=".jpc",
435
+ priority=["pillow", "JPEG2000-PIL"],
436
+ ),
437
+ FileExtension(
438
+ name="JPEG",
439
+ extension=".jpe",
440
+ priority=["pillow", "JPEG-FI", "JPEG-PIL", "opencv"],
441
+ ),
442
+ FileExtension(
443
+ name="Joint Photographic Experts Group",
444
+ extension=".jpeg",
445
+ priority=["pillow", "JPEG-PIL", "JPEG-FI", "ITK", "GDAL", "pyav", "opencv"],
446
+ ),
447
+ FileExtension(
448
+ name="JPEG 2000",
449
+ extension=".jpf",
450
+ priority=["pillow", "JPEG2000-PIL"],
451
+ ),
452
+ FileExtension(
453
+ name="Joint Photographic Experts Group",
454
+ extension=".jpg",
455
+ priority=["pillow", "JPEG-PIL", "JPEG-FI", "ITK", "GDAL", "pyav", "opencv"],
456
+ ),
457
+ FileExtension(
458
+ name="JPEG 2000",
459
+ extension=".jpx",
460
+ priority=["pillow", "JPEG2000-PIL"],
461
+ ),
462
+ FileExtension(
463
+ name="JPEG Extended Range",
464
+ extension=".jxr",
465
+ priority=["JPEG-XR-FI"],
466
+ ),
467
+ FileExtension(
468
+ extension=".k25",
469
+ priority=["RAW-FI"],
470
+ ),
471
+ FileExtension(
472
+ extension=".kc2",
473
+ priority=["RAW-FI"],
474
+ ),
475
+ FileExtension(
476
+ extension=".kdc",
477
+ priority=["RAW-FI"],
478
+ ),
479
+ FileExtension(
480
+ name="C64 Koala Graphics",
481
+ extension=".koa",
482
+ priority=["KOALA-FI"],
483
+ ),
484
+ FileExtension(
485
+ name="ILBM Interleaved Bitmap",
486
+ extension=".lbm",
487
+ priority=["IFF-FI"],
488
+ ),
489
+ FileExtension(
490
+ name="Lytro F01",
491
+ extension=".lfp",
492
+ priority=["LYTRO-LFP"],
493
+ ),
494
+ FileExtension(
495
+ name="Lytro Illum",
496
+ extension=".lfr",
497
+ priority=["LYTRO-LFR"],
498
+ ),
499
+ FileExtension(
500
+ name="ZEISS LSM",
501
+ extension=".lsm",
502
+ priority=["tifffile", "ITK", "TIFF"],
503
+ ),
504
+ FileExtension(
505
+ name="McIdas area file",
506
+ extension=".MCIDAS",
507
+ priority=["pillow", "MCIDAS-PIL"],
508
+ external_link="https://www.ssec.wisc.edu/mcidas/doc/prog_man/2003print/progman2003-formats.html",
509
+ ),
510
+ FileExtension(
511
+ extension=".mdc",
512
+ priority=["RAW-FI"],
513
+ ),
514
+ FileExtension(
515
+ extension=".mef",
516
+ priority=["RAW-FI"],
517
+ ),
518
+ FileExtension(
519
+ name="FreeSurfer File Format",
520
+ extension=".mgh",
521
+ priority=["ITK"],
522
+ ),
523
+ FileExtension(
524
+ name="ITK MetaImage",
525
+ extension=".mha",
526
+ priority=["ITK"],
527
+ ),
528
+ FileExtension(
529
+ name="ITK MetaImage Header",
530
+ extension=".mhd",
531
+ priority=["ITK"],
532
+ ),
533
+ FileExtension(
534
+ name="Microsoft Image Composer",
535
+ extension=".mic",
536
+ priority=["pillow", "MIC-PIL"],
537
+ ),
538
+ FileExtension(
539
+ name="Matroska Multimedia Container",
540
+ extension=".mkv",
541
+ priority=["FFMPEG", "pyav"],
542
+ ),
543
+ FileExtension(
544
+ name="Medical Imaging NetCDF",
545
+ extension=".mnc",
546
+ priority=["ITK"],
547
+ ),
548
+ FileExtension(
549
+ name="Medical Imaging NetCDF 2",
550
+ extension=".mnc2",
551
+ priority=["ITK"],
552
+ ),
553
+ FileExtension(
554
+ name="Leaf Raw Image Format",
555
+ extension=".mos",
556
+ priority=["RAW-FI"],
557
+ ),
558
+ FileExtension(
559
+ name="QuickTime File Format",
560
+ extension=".mov",
561
+ priority=["FFMPEG", "pyav"],
562
+ ),
563
+ FileExtension(
564
+ name="MPEG-4 Part 14",
565
+ extension=".mp4",
566
+ priority=["FFMPEG", "pyav"],
567
+ ),
568
+ FileExtension(
569
+ name="MPEG-1 Moving Picture Experts Group",
570
+ extension=".mpeg",
571
+ priority=["FFMPEG", "pyav"],
572
+ ),
573
+ FileExtension(
574
+ name="Moving Picture Experts Group",
575
+ extension=".mpg",
576
+ priority=["pillow", "FFMPEG", "pyav"],
577
+ ),
578
+ FileExtension(
579
+ name="JPEG Multi-Picture Format",
580
+ extension=".mpo",
581
+ priority=["pillow", "MPO-PIL"],
582
+ ),
583
+ FileExtension(
584
+ name="Magnetic resonance imaging",
585
+ extension=".mri",
586
+ priority=["DICOM"],
587
+ ),
588
+ FileExtension(
589
+ extension=".mrw",
590
+ priority=["RAW-FI"],
591
+ ),
592
+ FileExtension(
593
+ name="Windows Paint",
594
+ extension=".msp",
595
+ priority=["pillow", "MSP-PIL"],
596
+ ),
597
+ FileExtension(
598
+ extension=".nef",
599
+ priority=["RAW-FI", "rawpy"],
600
+ ),
601
+ FileExtension(
602
+ extension=".nhdr",
603
+ priority=["ITK"],
604
+ ),
605
+ FileExtension(
606
+ extension=".nia",
607
+ priority=["ITK"],
608
+ ),
609
+ FileExtension(
610
+ extension=".nii",
611
+ priority=["ITK"],
612
+ ),
613
+ FileExtension(
614
+ name="nii.gz",
615
+ extension=".nii.gz",
616
+ priority=["ITK"],
617
+ ),
618
+ FileExtension(
619
+ name="Numpy Array",
620
+ extension=".npz",
621
+ priority=["NPZ"],
622
+ volume_support=True,
623
+ ),
624
+ FileExtension(
625
+ extension=".nrrd",
626
+ priority=["ITK"],
627
+ ),
628
+ FileExtension(
629
+ extension=".nrw",
630
+ priority=["RAW-FI"],
631
+ ),
632
+ FileExtension(
633
+ extension=".orf",
634
+ priority=["RAW-FI"],
635
+ ),
636
+ FileExtension(
637
+ extension=".palm",
638
+ priority=["pillow"],
639
+ ),
640
+ FileExtension(
641
+ name="Portable Bitmap",
642
+ extension=".pbm",
643
+ priority=["PGM-FI", "PGMRAW-FI", "pyav", "opencv"],
644
+ ),
645
+ FileExtension(
646
+ name="Kodak PhotoCD",
647
+ extension=".pcd",
648
+ priority=["pillow", "PCD-FI", "PCD-PIL"],
649
+ ),
650
+ FileExtension(
651
+ name="Macintosh PICT",
652
+ extension=".pct",
653
+ priority=["PICT-FI"],
654
+ ),
655
+ FileExtension(
656
+ name="Zsoft Paintbrush",
657
+ extension=".PCX",
658
+ priority=["pillow", "PCX-FI", "PCX-PIL"],
659
+ ),
660
+ FileExtension(
661
+ extension=".pdf",
662
+ priority=["pillow"],
663
+ ),
664
+ FileExtension(
665
+ extension=".pef",
666
+ priority=["RAW-FI"],
667
+ ),
668
+ FileExtension(
669
+ extension=".pfm",
670
+ priority=["PFM-FI", "pyav", "opencv"],
671
+ ),
672
+ FileExtension(
673
+ name="Portable Greymap",
674
+ extension=".pgm",
675
+ priority=["pillow", "PGM-FI", "PGMRAW-FI", "pyav", "opencv"],
676
+ ),
677
+ FileExtension(
678
+ name="Macintosh PICT",
679
+ extension=".pic",
680
+ priority=["PICT-FI", "ITK", "opencv"],
681
+ ),
682
+ FileExtension(
683
+ name="Macintosh PICT",
684
+ extension=".pict",
685
+ priority=["PICT-FI"],
686
+ ),
687
+ FileExtension(
688
+ name="Portable Network Graphics",
689
+ extension=".png",
690
+ priority=["pillow", "PNG-PIL", "PNG-FI", "ITK", "pyav", "opencv"],
691
+ ),
692
+ FileExtension(
693
+ name="Portable Image Format",
694
+ extension=".pnm",
695
+ priority=["pillow", "opencv"],
696
+ ),
697
+ FileExtension(
698
+ name="Pbmplus image",
699
+ extension=".ppm",
700
+ priority=["pillow", "PPM-PIL", "pyav"],
701
+ ),
702
+ FileExtension(
703
+ name="Pbmplus image",
704
+ extension=".pbm",
705
+ priority=["pillow", "PPM-PIL", "PPM-FI"],
706
+ ),
707
+ FileExtension(
708
+ name="Portable image format",
709
+ extension=".pxm",
710
+ priority=["opencv"],
711
+ ),
712
+ FileExtension(
713
+ name="Portable Pixelmap (ASCII)",
714
+ extension=".ppm",
715
+ priority=["PPM-FI", "opencv"],
716
+ ),
717
+ FileExtension(
718
+ name="Portable Pixelmap (Raw)",
719
+ extension=".ppm",
720
+ priority=["PPMRAW-FI"],
721
+ ),
722
+ FileExtension(
723
+ name="Ghostscript",
724
+ extension=".ps",
725
+ priority=["pillow", "EPS-PIL"],
726
+ ),
727
+ FileExtension(
728
+ name="Adope Photoshop 2.5 and 3.0",
729
+ extension=".psd",
730
+ priority=["pillow", "PSD-PIL", "PSD-FI"],
731
+ ),
732
+ FileExtension(
733
+ extension=".ptx",
734
+ priority=["RAW-FI"],
735
+ ),
736
+ FileExtension(
737
+ extension=".pxn",
738
+ priority=["RAW-FI"],
739
+ ),
740
+ FileExtension(
741
+ name="PIXAR raster image",
742
+ extension=".pxr",
743
+ priority=["pillow", "PIXAR-PIL"],
744
+ ),
745
+ FileExtension(
746
+ extension=".qtk",
747
+ priority=["RAW-FI"],
748
+ ),
749
+ FileExtension(
750
+ extension=".raf",
751
+ priority=["RAW-FI"],
752
+ ),
753
+ FileExtension(
754
+ name="Sun Raster File",
755
+ extension=".ras",
756
+ priority=["pillow", "SUN-PIL", "RAS-FI", "pyav", "opencv"],
757
+ ),
758
+ FileExtension(
759
+ name="Sun Raster File",
760
+ extension=".sr",
761
+ priority=["opencv"],
762
+ ),
763
+ FileExtension(
764
+ extension=".raw",
765
+ priority=["RAW-FI", "LYTRO-ILLUM-RAW", "LYTRO-F01-RAW", "rawpy"],
766
+ ),
767
+ FileExtension(
768
+ extension=".rdc",
769
+ priority=["RAW-FI"],
770
+ ),
771
+ FileExtension(
772
+ name="Silicon Graphics Image",
773
+ extension=".rgb",
774
+ priority=["pillow", "SGI-PIL"],
775
+ ),
776
+ FileExtension(
777
+ name="Silicon Graphics Image",
778
+ extension=".rgba",
779
+ priority=["pillow", "SGI-PIL"],
780
+ ),
781
+ FileExtension(
782
+ extension=".rw2",
783
+ priority=["RAW-FI"],
784
+ ),
785
+ FileExtension(
786
+ extension=".rwl",
787
+ priority=["RAW-FI"],
788
+ ),
789
+ FileExtension(
790
+ extension=".rwz",
791
+ priority=["RAW-FI"],
792
+ ),
793
+ FileExtension(
794
+ name="Silicon Graphics Image",
795
+ extension=".sgi",
796
+ priority=["pillow", "SGI-PIL", "pyav"],
797
+ ),
798
+ FileExtension(
799
+ name="SPE File Format",
800
+ extension=".spe",
801
+ priority=["SPE"],
802
+ ),
803
+ FileExtension(
804
+ extension=".SPIDER",
805
+ priority=["pillow", "SPIDER-PIL"],
806
+ ),
807
+ FileExtension(
808
+ extension=".sr2",
809
+ priority=["RAW-FI"],
810
+ ),
811
+ FileExtension(
812
+ extension=".srf",
813
+ priority=["RAW-FI"],
814
+ ),
815
+ FileExtension(
816
+ extension=".srw",
817
+ priority=["RAW-FI"],
818
+ ),
819
+ FileExtension(
820
+ extension=".sti",
821
+ priority=["RAW-FI"],
822
+ ),
823
+ FileExtension(
824
+ extension=".stk",
825
+ priority=["tifffile", "TIFF"],
826
+ ),
827
+ FileExtension(
828
+ name="ShockWave Flash",
829
+ extension=".swf",
830
+ priority=["SWF", "pyav"],
831
+ ),
832
+ FileExtension(
833
+ name="Truevision TGA",
834
+ extension=".targa",
835
+ priority=["pillow", "TARGA-FI"],
836
+ ),
837
+ FileExtension(
838
+ name="Truevision TGA",
839
+ extension=".tga",
840
+ priority=["pillow", "TGA-PIL", "TARGA-FI", "pyav"],
841
+ ),
842
+ FileExtension(
843
+ name="Tagged Image File",
844
+ extension=".tif",
845
+ priority=[
846
+ "tifffile",
847
+ "TIFF",
848
+ "pillow",
849
+ "TIFF-PIL",
850
+ "TIFF-FI",
851
+ "FEI",
852
+ "ITK",
853
+ "GDAL",
854
+ "pyav",
855
+ "opencv",
856
+ ],
857
+ volume_support=True,
858
+ ),
859
+ FileExtension(
860
+ name="Tagged Image File Format",
861
+ extension=".tiff",
862
+ priority=[
863
+ "tifffile",
864
+ "TIFF",
865
+ "pillow",
866
+ "TIFF-PIL",
867
+ "TIFF-FI",
868
+ "FEI",
869
+ "ITK",
870
+ "GDAL",
871
+ "pyav",
872
+ "opencv",
873
+ ],
874
+ volume_support=True,
875
+ ),
876
+ FileExtension(
877
+ extension=".vda",
878
+ priority=["pillow"],
879
+ ),
880
+ FileExtension(
881
+ extension=".vst",
882
+ priority=["pillow"],
883
+ ),
884
+ FileExtension(
885
+ extension=".vtk",
886
+ priority=["ITK"],
887
+ ),
888
+ FileExtension(
889
+ name="Wireless Bitmap",
890
+ extension=".wap",
891
+ priority=["WBMP-FI"],
892
+ ),
893
+ FileExtension(
894
+ name="Wireless Bitmap",
895
+ extension=".wbm",
896
+ priority=["WBMP-FI"],
897
+ ),
898
+ FileExtension(
899
+ name="Wireless Bitmap",
900
+ extension=".wbmp",
901
+ priority=["WBMP-FI"],
902
+ ),
903
+ FileExtension(
904
+ name="JPEG Extended Range",
905
+ extension=".wdp",
906
+ priority=["JPEG-XR-FI"],
907
+ ),
908
+ FileExtension(
909
+ name="Matroska",
910
+ extension=".webm",
911
+ priority=["FFMPEG", "pyav"],
912
+ ),
913
+ FileExtension(
914
+ name="Google WebP",
915
+ extension=".webp",
916
+ priority=["pillow", "WEBP-FI", "pyav", "opencv"],
917
+ ),
918
+ FileExtension(
919
+ name="Windows Meta File",
920
+ extension=".wmf",
921
+ priority=["pillow", "WMF-PIL"],
922
+ ),
923
+ FileExtension(
924
+ name="Windows Media Video",
925
+ extension=".wmv",
926
+ priority=["FFMPEG"],
927
+ ),
928
+ FileExtension(
929
+ name="X11 Bitmap",
930
+ extension=".xbm",
931
+ priority=["pillow", "XBM-PIL", "XBM-FI", "pyav"],
932
+ ),
933
+ FileExtension(
934
+ name="X11 Pixel Map",
935
+ extension=".xpm",
936
+ priority=["pillow", "XPM-PIL", "XPM-FI"],
937
+ ),
938
+ FileExtension(
939
+ name="Thumbnail Image",
940
+ extension=".XVTHUMB",
941
+ priority=["pillow", "XVTHUMB-PIL"],
942
+ ),
943
+ FileExtension(
944
+ extension=".dpx",
945
+ priority=["pyav"],
946
+ ),
947
+ FileExtension(
948
+ extension=".im1",
949
+ priority=["pyav"],
950
+ ),
951
+ FileExtension(
952
+ extension=".im24",
953
+ priority=["pyav"],
954
+ ),
955
+ FileExtension(
956
+ extension=".im8",
957
+ priority=["pyav"],
958
+ ),
959
+ FileExtension(
960
+ extension=".jls",
961
+ priority=["pyav"],
962
+ ),
963
+ FileExtension(
964
+ extension=".ljpg",
965
+ priority=["pyav"],
966
+ ),
967
+ FileExtension(
968
+ extension=".pam",
969
+ priority=["pyav"],
970
+ ),
971
+ FileExtension(
972
+ extension=".pcx",
973
+ priority=["pyav"],
974
+ ),
975
+ FileExtension(
976
+ extension=".pgmyuv",
977
+ priority=["pyav"],
978
+ ),
979
+ FileExtension(
980
+ extension=".pix",
981
+ priority=["pyav"],
982
+ ),
983
+ FileExtension(
984
+ extension=".ppm",
985
+ priority=["pyav"],
986
+ ),
987
+ FileExtension(
988
+ extension=".rs",
989
+ priority=["pyav"],
990
+ ),
991
+ FileExtension(
992
+ extension=".sun",
993
+ priority=["pyav"],
994
+ ),
995
+ FileExtension(
996
+ extension=".sunras",
997
+ priority=["pyav"],
998
+ ),
999
+ FileExtension(
1000
+ extension=".xface",
1001
+ priority=["pyav"],
1002
+ ),
1003
+ FileExtension(
1004
+ extension=".xwd",
1005
+ priority=["pyav"],
1006
+ ),
1007
+ FileExtension(
1008
+ extension=".y",
1009
+ priority=["pyav"],
1010
+ ),
1011
+ FileExtension(
1012
+ name="3GP (3GPP file format)",
1013
+ extension=".3g2",
1014
+ priority=["pyav"],
1015
+ ),
1016
+ FileExtension(
1017
+ name="3GP (3GPP file format)",
1018
+ extension=".3gp",
1019
+ priority=["pyav"],
1020
+ ),
1021
+ FileExtension(
1022
+ name="3GP (3GPP file format)",
1023
+ extension=".f4v",
1024
+ priority=["pyav"],
1025
+ ),
1026
+ FileExtension(
1027
+ name="3GP (3GPP file format)",
1028
+ extension=".ism",
1029
+ priority=["pyav"],
1030
+ ),
1031
+ FileExtension(
1032
+ name="3GP (3GPP file format)",
1033
+ extension=".isma",
1034
+ priority=["pyav"],
1035
+ ),
1036
+ FileExtension(
1037
+ name="3GP (3GPP file format)",
1038
+ extension=".ismv",
1039
+ priority=["pyav"],
1040
+ ),
1041
+ FileExtension(
1042
+ name="3GP (3GPP file format)",
1043
+ extension=".m4a",
1044
+ priority=["pyav"],
1045
+ ),
1046
+ FileExtension(
1047
+ name="3GP (3GPP file format)",
1048
+ extension=".m4b",
1049
+ priority=["pyav"],
1050
+ ),
1051
+ FileExtension(
1052
+ name="3GP (3GPP file format)",
1053
+ extension=".mj2",
1054
+ priority=["pyav"],
1055
+ ),
1056
+ FileExtension(
1057
+ name="3GP (3GPP file format)",
1058
+ extension=".psp",
1059
+ priority=["pyav"],
1060
+ ),
1061
+ FileExtension(
1062
+ name="3GP2 (3GPP2 file format)",
1063
+ extension=".3g2",
1064
+ priority=["pyav"],
1065
+ ),
1066
+ FileExtension(
1067
+ name="3GP2 (3GPP2 file format)",
1068
+ extension=".3gp",
1069
+ priority=["pyav"],
1070
+ ),
1071
+ FileExtension(
1072
+ name="3GP2 (3GPP2 file format)",
1073
+ extension=".f4v",
1074
+ priority=["pyav"],
1075
+ ),
1076
+ FileExtension(
1077
+ name="3GP2 (3GPP2 file format)",
1078
+ extension=".ism",
1079
+ priority=["pyav"],
1080
+ ),
1081
+ FileExtension(
1082
+ name="3GP2 (3GPP2 file format)",
1083
+ extension=".isma",
1084
+ priority=["pyav"],
1085
+ ),
1086
+ FileExtension(
1087
+ name="3GP2 (3GPP2 file format)",
1088
+ extension=".ismv",
1089
+ priority=["pyav"],
1090
+ ),
1091
+ FileExtension(
1092
+ name="3GP2 (3GPP2 file format)",
1093
+ extension=".m4a",
1094
+ priority=["pyav"],
1095
+ ),
1096
+ FileExtension(
1097
+ name="3GP2 (3GPP2 file format)",
1098
+ extension=".m4b",
1099
+ priority=["pyav"],
1100
+ ),
1101
+ FileExtension(
1102
+ name="3GP2 (3GPP2 file format)",
1103
+ extension=".mj2",
1104
+ priority=["pyav"],
1105
+ ),
1106
+ FileExtension(
1107
+ name="3GP2 (3GPP2 file format)",
1108
+ extension=".psp",
1109
+ priority=["pyav"],
1110
+ ),
1111
+ FileExtension(
1112
+ name="3GPP AMR",
1113
+ extension=".amr",
1114
+ priority=["pyav"],
1115
+ ),
1116
+ FileExtension(
1117
+ name="a64 - video for Commodore 64",
1118
+ extension=".A64",
1119
+ priority=["pyav"],
1120
+ ),
1121
+ FileExtension(
1122
+ name="a64 - video for Commodore 64",
1123
+ extension=".a64",
1124
+ priority=["pyav"],
1125
+ ),
1126
+ FileExtension(
1127
+ name="Adobe Filmstrip",
1128
+ extension=".flm",
1129
+ priority=["pyav"],
1130
+ ),
1131
+ FileExtension(
1132
+ name="AMV",
1133
+ extension=".amv",
1134
+ priority=["pyav"],
1135
+ ),
1136
+ FileExtension(
1137
+ name="ASF (Advanced / Active Streaming Format)",
1138
+ extension=".asf",
1139
+ priority=["pyav"],
1140
+ ),
1141
+ FileExtension(
1142
+ name="ASF (Advanced / Active Streaming Format)",
1143
+ extension=".asf",
1144
+ priority=["pyav"],
1145
+ ),
1146
+ FileExtension(
1147
+ name="ASF (Advanced / Active Streaming Format)",
1148
+ extension=".wmv",
1149
+ priority=["pyav"],
1150
+ ),
1151
+ FileExtension(
1152
+ name="ASF (Advanced / Active Streaming Format)",
1153
+ extension=".wmv",
1154
+ priority=["pyav"],
1155
+ ),
1156
+ FileExtension(
1157
+ name="AV1 Annex B",
1158
+ extension=".obu",
1159
+ priority=["pyav"],
1160
+ ),
1161
+ FileExtension(
1162
+ name="AV1 low overhead OBU",
1163
+ extension=".obu",
1164
+ priority=["pyav"],
1165
+ ),
1166
+ FileExtension(
1167
+ name="AVI (Audio Video Interleaved)",
1168
+ extension=".avi",
1169
+ priority=["pyav"],
1170
+ ),
1171
+ FileExtension(
1172
+ name="AVR (Audio Visual Research)",
1173
+ extension=".avr",
1174
+ priority=["pyav"],
1175
+ ),
1176
+ FileExtension(
1177
+ name="Beam Software SIFF",
1178
+ extension=".vb",
1179
+ priority=["pyav"],
1180
+ ),
1181
+ FileExtension(
1182
+ name="CD Graphics",
1183
+ extension=".cdg",
1184
+ priority=["pyav"],
1185
+ ),
1186
+ FileExtension(
1187
+ name="Commodore CDXL video",
1188
+ extension=".cdxl",
1189
+ priority=["pyav"],
1190
+ ),
1191
+ FileExtension(
1192
+ name="Commodore CDXL video",
1193
+ extension=".xl",
1194
+ priority=["pyav"],
1195
+ ),
1196
+ FileExtension(
1197
+ name="DASH Muxer",
1198
+ extension=".mpd",
1199
+ priority=["pyav"],
1200
+ ),
1201
+ FileExtension(
1202
+ name="Digital Pictures SGA",
1203
+ extension=".sga",
1204
+ priority=["pyav"],
1205
+ ),
1206
+ FileExtension(
1207
+ name="Discworld II BMV",
1208
+ extension=".bmv",
1209
+ priority=["pyav"],
1210
+ ),
1211
+ FileExtension(
1212
+ name="DV (Digital Video)",
1213
+ extension=".dif",
1214
+ priority=["pyav"],
1215
+ ),
1216
+ FileExtension(
1217
+ name="DV (Digital Video)",
1218
+ extension=".dv",
1219
+ priority=["pyav"],
1220
+ ),
1221
+ FileExtension(
1222
+ name="F4V Adobe Flash Video",
1223
+ extension=".f4v",
1224
+ priority=["pyav"],
1225
+ ),
1226
+ FileExtension(
1227
+ name="FLV (Flash Video)",
1228
+ extension=".flv",
1229
+ priority=["pyav"],
1230
+ ),
1231
+ FileExtension(
1232
+ name="GXF (General eXchange Format)",
1233
+ extension=".gxf",
1234
+ priority=["pyav"],
1235
+ ),
1236
+ FileExtension(
1237
+ name="iCE Draw File",
1238
+ extension=".idf",
1239
+ priority=["pyav"],
1240
+ ),
1241
+ FileExtension(
1242
+ name="IFV CCTV DVR",
1243
+ extension=".ifv",
1244
+ priority=["pyav"],
1245
+ ),
1246
+ FileExtension(
1247
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1248
+ extension=".m4a",
1249
+ priority=["pyav"],
1250
+ ),
1251
+ FileExtension(
1252
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1253
+ extension=".m4b",
1254
+ priority=["pyav"],
1255
+ ),
1256
+ FileExtension(
1257
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1258
+ extension=".m4v",
1259
+ priority=["pyav"],
1260
+ ),
1261
+ FileExtension(
1262
+ name="IVR (Internet Video Recording)",
1263
+ extension=".ivr",
1264
+ priority=["pyav"],
1265
+ ),
1266
+ FileExtension(
1267
+ name="Konami PS2 SVAG",
1268
+ extension=".svag",
1269
+ priority=["pyav"],
1270
+ ),
1271
+ FileExtension(
1272
+ name="KUX (YouKu)",
1273
+ extension=".kux",
1274
+ priority=["pyav"],
1275
+ ),
1276
+ FileExtension(
1277
+ name="live RTMP FLV (Flash Video)",
1278
+ extension=".flv",
1279
+ priority=["pyav"],
1280
+ ),
1281
+ FileExtension(
1282
+ name="Loki SDL MJPEG",
1283
+ extension=".mjpg",
1284
+ priority=["pyav"],
1285
+ ),
1286
+ FileExtension(
1287
+ name="LVF",
1288
+ extension=".lvf",
1289
+ priority=["pyav"],
1290
+ ),
1291
+ FileExtension(
1292
+ name="Matroska / WebM",
1293
+ extension=".mk3d",
1294
+ priority=["pyav"],
1295
+ ),
1296
+ FileExtension(
1297
+ name="Matroska / WebM",
1298
+ extension=".mka",
1299
+ priority=["pyav"],
1300
+ ),
1301
+ FileExtension(
1302
+ name="Matroska / WebM",
1303
+ extension=".mks",
1304
+ priority=["pyav"],
1305
+ ),
1306
+ FileExtension(
1307
+ name="Microsoft XMV",
1308
+ extension=".xmv",
1309
+ priority=["pyav"],
1310
+ ),
1311
+ FileExtension(
1312
+ name="MIME multipart JPEG",
1313
+ extension=".mjpg",
1314
+ priority=["pyav"],
1315
+ ),
1316
+ FileExtension(
1317
+ name="MobiClip MODS",
1318
+ extension=".mods",
1319
+ priority=["pyav"],
1320
+ ),
1321
+ FileExtension(
1322
+ name="MobiClip MOFLEX",
1323
+ extension=".moflex",
1324
+ priority=["pyav"],
1325
+ ),
1326
+ FileExtension(
1327
+ name="Motion Pixels MVI",
1328
+ extension=".mvi",
1329
+ priority=["pyav"],
1330
+ ),
1331
+ FileExtension(
1332
+ name="MP4 (MPEG-4 Part 14)",
1333
+ extension=".3g2",
1334
+ priority=["pyav"],
1335
+ ),
1336
+ FileExtension(
1337
+ name="MP4 (MPEG-4 Part 14)",
1338
+ extension=".3gp",
1339
+ priority=["pyav"],
1340
+ ),
1341
+ FileExtension(
1342
+ name="MP4 (MPEG-4 Part 14)",
1343
+ extension=".f4v",
1344
+ priority=["pyav"],
1345
+ ),
1346
+ FileExtension(
1347
+ name="MP4 (MPEG-4 Part 14)",
1348
+ extension=".ism",
1349
+ priority=["pyav"],
1350
+ ),
1351
+ FileExtension(
1352
+ name="MP4 (MPEG-4 Part 14)",
1353
+ extension=".isma",
1354
+ priority=["pyav"],
1355
+ ),
1356
+ FileExtension(
1357
+ name="MP4 (MPEG-4 Part 14)",
1358
+ extension=".ismv",
1359
+ priority=["pyav"],
1360
+ ),
1361
+ FileExtension(
1362
+ name="MP4 (MPEG-4 Part 14)",
1363
+ extension=".m4a",
1364
+ priority=["pyav"],
1365
+ ),
1366
+ FileExtension(
1367
+ name="MP4 (MPEG-4 Part 14)",
1368
+ extension=".m4b",
1369
+ priority=["pyav"],
1370
+ ),
1371
+ FileExtension(
1372
+ name="MP4 (MPEG-4 Part 14)",
1373
+ extension=".mj2",
1374
+ priority=["pyav"],
1375
+ ),
1376
+ FileExtension(
1377
+ name="MP4 (MPEG-4 Part 14)",
1378
+ extension=".psp",
1379
+ priority=["pyav"],
1380
+ ),
1381
+ FileExtension(
1382
+ name="MPEG-2 PS (DVD VOB)",
1383
+ extension=".dvd",
1384
+ priority=["pyav"],
1385
+ ),
1386
+ FileExtension(
1387
+ name="MPEG-2 PS (SVCD)",
1388
+ extension=".vob",
1389
+ priority=["pyav"],
1390
+ ),
1391
+ FileExtension(
1392
+ name="MPEG-2 PS (VOB)",
1393
+ extension=".vob",
1394
+ priority=["pyav"],
1395
+ ),
1396
+ FileExtension(
1397
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1398
+ extension=".m2t",
1399
+ priority=["pyav"],
1400
+ ),
1401
+ FileExtension(
1402
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1403
+ extension=".m2ts",
1404
+ priority=["pyav"],
1405
+ ),
1406
+ FileExtension(
1407
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1408
+ extension=".mts",
1409
+ priority=["pyav"],
1410
+ ),
1411
+ FileExtension(
1412
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1413
+ extension=".ts",
1414
+ priority=["pyav"],
1415
+ ),
1416
+ FileExtension(
1417
+ name="Musepack",
1418
+ extension=".mpc",
1419
+ priority=["pyav"],
1420
+ ),
1421
+ FileExtension(
1422
+ name="MXF (Material eXchange Format) Operational Pattern Atom",
1423
+ extension=".mxf",
1424
+ priority=["pyav"],
1425
+ ),
1426
+ FileExtension(
1427
+ name="MXF (Material eXchange Format)",
1428
+ extension=".mxf",
1429
+ priority=["pyav"],
1430
+ ),
1431
+ FileExtension(
1432
+ name="MxPEG clip",
1433
+ extension=".mxg",
1434
+ priority=["pyav"],
1435
+ ),
1436
+ FileExtension(
1437
+ name="NC camera feed",
1438
+ extension=".v",
1439
+ priority=["pyav"],
1440
+ ),
1441
+ FileExtension(
1442
+ name="NUT",
1443
+ extension=".nut",
1444
+ priority=["pyav"],
1445
+ ),
1446
+ FileExtension(
1447
+ name="Ogg Video",
1448
+ extension=".ogv",
1449
+ priority=["pyav"],
1450
+ ),
1451
+ FileExtension(
1452
+ name="Ogg",
1453
+ extension=".ogg",
1454
+ priority=["pyav"],
1455
+ ),
1456
+ FileExtension(
1457
+ name="On2 IVF",
1458
+ extension=".ivf",
1459
+ priority=["pyav"],
1460
+ ),
1461
+ FileExtension(
1462
+ name="PSP MP4 (MPEG-4 Part 14)",
1463
+ extension=".psp",
1464
+ priority=["pyav"],
1465
+ ),
1466
+ FileExtension(
1467
+ name="Psygnosis YOP",
1468
+ extension=".yop",
1469
+ priority=["pyav"],
1470
+ ),
1471
+ FileExtension(
1472
+ name="QuickTime / MOV",
1473
+ extension=".3g2",
1474
+ priority=["pyav"],
1475
+ ),
1476
+ FileExtension(
1477
+ name="QuickTime / MOV",
1478
+ extension=".3gp",
1479
+ priority=["pyav"],
1480
+ ),
1481
+ FileExtension(
1482
+ name="QuickTime / MOV",
1483
+ extension=".f4v",
1484
+ priority=["pyav"],
1485
+ ),
1486
+ FileExtension(
1487
+ name="QuickTime / MOV",
1488
+ extension=".ism",
1489
+ priority=["pyav"],
1490
+ ),
1491
+ FileExtension(
1492
+ name="QuickTime / MOV",
1493
+ extension=".isma",
1494
+ priority=["pyav"],
1495
+ ),
1496
+ FileExtension(
1497
+ name="QuickTime / MOV",
1498
+ extension=".ismv",
1499
+ priority=["pyav"],
1500
+ ),
1501
+ FileExtension(
1502
+ name="QuickTime / MOV",
1503
+ extension=".m4a",
1504
+ priority=["pyav"],
1505
+ ),
1506
+ FileExtension(
1507
+ name="QuickTime / MOV",
1508
+ extension=".m4b",
1509
+ priority=["pyav"],
1510
+ ),
1511
+ FileExtension(
1512
+ name="QuickTime / MOV",
1513
+ extension=".mj2",
1514
+ priority=["pyav"],
1515
+ ),
1516
+ FileExtension(
1517
+ name="QuickTime / MOV",
1518
+ extension=".psp",
1519
+ priority=["pyav"],
1520
+ ),
1521
+ FileExtension(
1522
+ name="raw AVS2-P2/IEEE1857.4 video",
1523
+ extension=".avs",
1524
+ priority=["pyav"],
1525
+ ),
1526
+ FileExtension(
1527
+ name="raw AVS2-P2/IEEE1857.4 video",
1528
+ extension=".avs2",
1529
+ priority=["pyav"],
1530
+ ),
1531
+ FileExtension(
1532
+ name="raw AVS3-P2/IEEE1857.10",
1533
+ extension=".avs3",
1534
+ priority=["pyav"],
1535
+ ),
1536
+ FileExtension(
1537
+ name="raw Chinese AVS (Audio Video Standard) video",
1538
+ extension=".cavs",
1539
+ priority=["pyav"],
1540
+ ),
1541
+ FileExtension(
1542
+ name="raw Dirac",
1543
+ extension=".drc",
1544
+ priority=["pyav"],
1545
+ ),
1546
+ FileExtension(
1547
+ name="raw Dirac",
1548
+ extension=".vc2",
1549
+ priority=["pyav"],
1550
+ ),
1551
+ FileExtension(
1552
+ name="raw DNxHD (SMPTE VC-3)",
1553
+ extension=".dnxhd",
1554
+ priority=["pyav"],
1555
+ ),
1556
+ FileExtension(
1557
+ name="raw DNxHD (SMPTE VC-3)",
1558
+ extension=".dnxhr",
1559
+ priority=["pyav"],
1560
+ ),
1561
+ FileExtension(
1562
+ name="raw GSM",
1563
+ extension=".gsm",
1564
+ priority=["pyav"],
1565
+ ),
1566
+ FileExtension(
1567
+ name="raw H.261",
1568
+ extension=".h261",
1569
+ priority=["pyav"],
1570
+ ),
1571
+ FileExtension(
1572
+ name="raw H.263",
1573
+ extension=".h263",
1574
+ priority=["pyav"],
1575
+ ),
1576
+ FileExtension(
1577
+ name="raw H.264 video",
1578
+ extension=".264",
1579
+ priority=["pyav"],
1580
+ ),
1581
+ FileExtension(
1582
+ name="raw H.264 video",
1583
+ extension=".avc",
1584
+ priority=["pyav"],
1585
+ ),
1586
+ FileExtension(
1587
+ name="raw H.264 video",
1588
+ extension=".h264",
1589
+ priority=["pyav", "FFMPEG"],
1590
+ ),
1591
+ FileExtension(
1592
+ name="raw H.264 video",
1593
+ extension=".h26l",
1594
+ priority=["pyav"],
1595
+ ),
1596
+ FileExtension(
1597
+ name="raw HEVC video",
1598
+ extension=".265",
1599
+ priority=["pyav"],
1600
+ ),
1601
+ FileExtension(
1602
+ name="raw HEVC video",
1603
+ extension=".h265",
1604
+ priority=["pyav"],
1605
+ ),
1606
+ FileExtension(
1607
+ name="raw HEVC video",
1608
+ extension=".hevc",
1609
+ priority=["pyav"],
1610
+ ),
1611
+ FileExtension(
1612
+ name="raw id RoQ",
1613
+ extension=".roq",
1614
+ priority=["pyav"],
1615
+ ),
1616
+ FileExtension(
1617
+ name="raw Ingenient MJPEG",
1618
+ extension=".cgi",
1619
+ priority=["pyav"],
1620
+ ),
1621
+ FileExtension(
1622
+ name="raw IPU Video",
1623
+ extension=".ipu",
1624
+ priority=["pyav"],
1625
+ ),
1626
+ FileExtension(
1627
+ name="raw MJPEG 2000 video",
1628
+ extension=".j2k",
1629
+ priority=["pyav"],
1630
+ ),
1631
+ FileExtension(
1632
+ name="raw MJPEG video",
1633
+ extension=".mjpeg",
1634
+ priority=["pyav"],
1635
+ ),
1636
+ FileExtension(
1637
+ name="raw MJPEG video",
1638
+ extension=".mjpg",
1639
+ priority=["pyav"],
1640
+ ),
1641
+ FileExtension(
1642
+ name="raw MJPEG video",
1643
+ extension=".mpo",
1644
+ priority=["pyav"],
1645
+ ),
1646
+ FileExtension(
1647
+ name="raw MPEG-1 video",
1648
+ extension=".m1v",
1649
+ priority=["pyav"],
1650
+ ),
1651
+ FileExtension(
1652
+ name="raw MPEG-1 video",
1653
+ extension=".mpeg",
1654
+ priority=["pyav"],
1655
+ ),
1656
+ FileExtension(
1657
+ name="raw MPEG-1 video",
1658
+ extension=".mpg",
1659
+ priority=["pyav"],
1660
+ ),
1661
+ FileExtension(
1662
+ name="raw MPEG-2 video",
1663
+ extension=".m2v",
1664
+ priority=["pyav"],
1665
+ ),
1666
+ FileExtension(
1667
+ name="raw MPEG-4 video",
1668
+ extension=".m4v",
1669
+ priority=["pyav"],
1670
+ ),
1671
+ FileExtension(
1672
+ name="raw VC-1 video",
1673
+ extension=".vc1",
1674
+ priority=["pyav"],
1675
+ ),
1676
+ FileExtension(
1677
+ name="raw video",
1678
+ extension=".cif",
1679
+ priority=["pyav"],
1680
+ ),
1681
+ FileExtension(
1682
+ name="raw video",
1683
+ extension=".qcif",
1684
+ priority=["pyav"],
1685
+ ),
1686
+ FileExtension(
1687
+ name="raw video",
1688
+ extension=".rgb",
1689
+ priority=["pyav"],
1690
+ ),
1691
+ FileExtension(
1692
+ name="raw video",
1693
+ extension=".yuv",
1694
+ priority=["pyav"],
1695
+ ),
1696
+ FileExtension(
1697
+ name="RealMedia",
1698
+ extension=".rm",
1699
+ priority=["pyav"],
1700
+ ),
1701
+ FileExtension(
1702
+ name="SDR2",
1703
+ extension=".sdr2",
1704
+ priority=["pyav"],
1705
+ ),
1706
+ FileExtension(
1707
+ name="Sega FILM / CPK",
1708
+ extension=".cpk",
1709
+ priority=["pyav"],
1710
+ ),
1711
+ FileExtension(
1712
+ name="SER (Simple uncompressed video format for astronomical capturing)",
1713
+ extension=".ser",
1714
+ priority=["pyav"],
1715
+ ),
1716
+ FileExtension(
1717
+ name="Simbiosis Interactive IMX",
1718
+ extension=".imx",
1719
+ priority=["pyav"],
1720
+ ),
1721
+ FileExtension(
1722
+ name="Square SVS",
1723
+ extension=".svs",
1724
+ priority=["tifffile", "pyav"],
1725
+ ),
1726
+ FileExtension(
1727
+ name="TiVo TY Stream",
1728
+ extension=".ty",
1729
+ priority=["pyav"],
1730
+ ),
1731
+ FileExtension(
1732
+ name="TiVo TY Stream",
1733
+ extension=".ty+",
1734
+ priority=["pyav"],
1735
+ ),
1736
+ FileExtension(
1737
+ name="Uncompressed 4:2:2 10-bit",
1738
+ extension=".v210",
1739
+ priority=["pyav"],
1740
+ ),
1741
+ FileExtension(
1742
+ name="Uncompressed 4:2:2 10-bit",
1743
+ extension=".yuv10",
1744
+ priority=["pyav"],
1745
+ ),
1746
+ FileExtension(
1747
+ name="VC-1 test bitstream",
1748
+ extension=".rcv",
1749
+ priority=["pyav"],
1750
+ ),
1751
+ FileExtension(
1752
+ name="Video CCTV DAT",
1753
+ extension=".dat",
1754
+ priority=["pyav"],
1755
+ ),
1756
+ FileExtension(
1757
+ name="Video DAV",
1758
+ extension=".dav",
1759
+ priority=["pyav"],
1760
+ ),
1761
+ FileExtension(
1762
+ name="Vivo",
1763
+ extension=".viv",
1764
+ priority=["pyav"],
1765
+ ),
1766
+ FileExtension(
1767
+ name="WebM Chunk Muxer",
1768
+ extension=".chk",
1769
+ priority=["pyav"],
1770
+ ),
1771
+ FileExtension(
1772
+ name="WebM",
1773
+ extension=".mk3d",
1774
+ priority=["pyav"],
1775
+ ),
1776
+ FileExtension(
1777
+ name="WebM",
1778
+ extension=".mka",
1779
+ priority=["pyav"],
1780
+ ),
1781
+ FileExtension(
1782
+ name="WebM",
1783
+ extension=".mks",
1784
+ priority=["pyav"],
1785
+ ),
1786
+ FileExtension(
1787
+ name="Windows Television (WTV)",
1788
+ extension=".wtv",
1789
+ priority=["pyav"],
1790
+ ),
1791
+ FileExtension(
1792
+ name="Xilam DERF",
1793
+ extension=".adp",
1794
+ priority=["pyav"],
1795
+ ),
1796
+ FileExtension(
1797
+ name="YUV4MPEG pipe",
1798
+ extension=".y4m",
1799
+ priority=["pyav"],
1800
+ ),
1801
+ FileExtension(
1802
+ extension=".qpi",
1803
+ priority=["tifffile"],
1804
+ ),
1805
+ FileExtension(
1806
+ name="PCO Camera",
1807
+ extension=".pcoraw",
1808
+ priority=["tifffile"],
1809
+ ),
1810
+ FileExtension(
1811
+ name="PCO Camera",
1812
+ extension=".rec",
1813
+ priority=["tifffile"],
1814
+ ),
1815
+ FileExtension(
1816
+ name="Perkin Elmer Vectra",
1817
+ extension=".qptiff",
1818
+ priority=["tifffile"],
1819
+ ),
1820
+ FileExtension(
1821
+ name="Pyramid Encoded TIFF",
1822
+ extension=".ptiff",
1823
+ priority=["tifffile"],
1824
+ ),
1825
+ FileExtension(
1826
+ name="Pyramid Encoded TIFF",
1827
+ extension=".ptif",
1828
+ priority=["tifffile"],
1829
+ ),
1830
+ FileExtension(
1831
+ name="Opticks Gel",
1832
+ extension=".gel",
1833
+ priority=["tifffile"],
1834
+ ),
1835
+ FileExtension(
1836
+ name="Zoomify Image Format",
1837
+ extension=".zif",
1838
+ priority=["tifffile"],
1839
+ ),
1840
+ FileExtension(
1841
+ name="Hamamatsu Slide Scanner",
1842
+ extension=".ndpi",
1843
+ priority=["tifffile"],
1844
+ ),
1845
+ FileExtension(
1846
+ name="Roche Digital Pathology",
1847
+ extension=".bif",
1848
+ priority=["tifffile"],
1849
+ ),
1850
+ FileExtension(
1851
+ extension=".tf8",
1852
+ priority=["tifffile"],
1853
+ ),
1854
+ FileExtension(
1855
+ extension=".btf",
1856
+ priority=["tifffile"],
1857
+ ),
1858
+ FileExtension(
1859
+ name="High Efficiency Image File Format",
1860
+ extension=".heic",
1861
+ priority=["pillow"],
1862
+ ),
1863
+ FileExtension(
1864
+ name="AV1 Image File Format",
1865
+ extension=".avif",
1866
+ priority=["pillow"],
1867
+ ),
1868
+ ]
1869
+ extension_list.sort(key=lambda x: x.extension)
1870
+
1871
+
1872
+ known_extensions = dict()
1873
+ for ext in extension_list:
1874
+ if ext.extension not in known_extensions:
1875
+ known_extensions[ext.extension] = list()
1876
+ known_extensions[ext.extension].append(ext)
1877
+
1878
+ extension_list = [ext for ext_list in known_extensions.values() for ext in ext_list]
1879
+
1880
+ _video_extension_strings = [
1881
+ ".264",
1882
+ ".265",
1883
+ ".3g2",
1884
+ ".3gp",
1885
+ ".a64",
1886
+ ".A64",
1887
+ ".adp",
1888
+ ".amr",
1889
+ ".amv",
1890
+ ".asf",
1891
+ ".avc",
1892
+ ".avi",
1893
+ ".avr",
1894
+ ".avs",
1895
+ ".avs2",
1896
+ ".avs3",
1897
+ ".bmv",
1898
+ ".cavs",
1899
+ ".cdg",
1900
+ ".cdxl",
1901
+ ".cgi",
1902
+ ".chk",
1903
+ ".cif",
1904
+ ".cpk",
1905
+ ".dat",
1906
+ ".dav",
1907
+ ".dif",
1908
+ ".dnxhd",
1909
+ ".dnxhr",
1910
+ ".drc",
1911
+ ".dv",
1912
+ ".dvd",
1913
+ ".f4v",
1914
+ ".flm",
1915
+ ".flv",
1916
+ ".gsm",
1917
+ ".gxf",
1918
+ ".h261",
1919
+ ".h263",
1920
+ ".h264",
1921
+ ".h265",
1922
+ ".h26l",
1923
+ ".hevc",
1924
+ ".idf",
1925
+ ".ifv",
1926
+ ".imx",
1927
+ ".ipu",
1928
+ ".ism",
1929
+ ".isma",
1930
+ ".ismv",
1931
+ ".ivf",
1932
+ ".ivr",
1933
+ ".j2k",
1934
+ ".kux",
1935
+ ".lvf",
1936
+ ".m1v",
1937
+ ".m2t",
1938
+ ".m2ts",
1939
+ ".m2v",
1940
+ ".m4a",
1941
+ ".m4b",
1942
+ ".m4v",
1943
+ ".mj2",
1944
+ ".mjpeg",
1945
+ ".mjpg",
1946
+ ".mk3d",
1947
+ ".mka",
1948
+ ".mks",
1949
+ ".mkv",
1950
+ ".mods",
1951
+ ".moflex",
1952
+ ".mov",
1953
+ ".mp4",
1954
+ ".mpc",
1955
+ ".mpd",
1956
+ ".mpeg",
1957
+ ".mpg",
1958
+ ".mpo",
1959
+ ".mts",
1960
+ ".mvi",
1961
+ ".mxf",
1962
+ ".mxg",
1963
+ ".nut",
1964
+ ".obu",
1965
+ ".ogg",
1966
+ ".ogv",
1967
+ ".psp",
1968
+ ".qcif",
1969
+ ".rcv",
1970
+ ".rgb",
1971
+ ".rm",
1972
+ ".roq",
1973
+ ".sdr2",
1974
+ ".ser",
1975
+ ".sga",
1976
+ ".svag",
1977
+ ".svs",
1978
+ ".ts",
1979
+ ".ty",
1980
+ ".ty+",
1981
+ ".v",
1982
+ ".v210",
1983
+ ".vb",
1984
+ ".vc1",
1985
+ ".vc2",
1986
+ ".viv",
1987
+ ".vob",
1988
+ ".webm",
1989
+ ".wmv",
1990
+ ".wtv",
1991
+ ".xl",
1992
+ ".xmv",
1993
+ ".y4m",
1994
+ ".yop",
1995
+ ".yuv",
1996
+ ".yuv10",
1997
+ ]
1998
+ video_extensions = list()
1999
+ for ext_string in _video_extension_strings:
2000
+ formats = known_extensions[ext_string]
2001
+ video_extensions.append(formats[0])
2002
+ video_extensions.sort(key=lambda x: x.extension)
evalkit_tf446/lib/python3.10/site-packages/imageio/config/extensions.pyi ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Optional
2
+
3
+ class FileExtension:
4
+ extension: str
5
+ priority: List[str]
6
+ name: Optional[str] = None
7
+ description: Optional[str] = None
8
+ external_link: Optional[str] = None
9
+ volume_support: bool
10
+
11
+ def __init__(
12
+ self,
13
+ *,
14
+ extension: str,
15
+ priority: List[str],
16
+ name: str = None,
17
+ description: str = None,
18
+ external_link: str = None
19
+ ) -> None: ...
20
+ def reset(self) -> None: ...
21
+
22
+ extension_list: List[FileExtension]
23
+ known_extensions: Dict[str, List[FileExtension]]
24
+ video_extensions: List[FileExtension]
evalkit_tf446/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_tf446/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_tf446/lib/python3.10/site-packages/imageio/freeze.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functions for freezing imageio.
3
+ """
4
+
5
+
6
+ def get_includes():
7
+ return ["email", "urllib.request", "numpy", "zipfile", "io"]
8
+
9
+
10
+ def get_excludes():
11
+ return []
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ # flake8: noqa
5
+
6
+ """
7
+ Here you can find documentation on how to write your own plugin to allow
8
+ ImageIO to access a new backend. Plugins are quite object oriented, and
9
+ the relevant classes and their interaction are documented here:
10
+
11
+ .. currentmodule:: imageio
12
+
13
+ .. autosummary::
14
+ :toctree: ../_autosummary
15
+ :template: better_class.rst
16
+
17
+ imageio.core.Format
18
+ imageio.core.Request
19
+
20
+ .. note::
21
+ You can always check existing plugins if you want to see examples.
22
+
23
+ What methods to implement
24
+ -------------------------
25
+
26
+ To implement a new plugin, create a new class that inherits from
27
+ :class:`imageio.core.Format`. and implement the following functions:
28
+
29
+ .. autosummary::
30
+ :toctree: ../_autosummary
31
+
32
+ imageio.core.Format.__init__
33
+ imageio.core.Format._can_read
34
+ imageio.core.Format._can_write
35
+
36
+ Further, each format contains up to two nested classes; one for reading and
37
+ one for writing. To support reading and/or writing, the respective classes
38
+ need to be defined.
39
+
40
+ For reading, create a nested class that inherits from
41
+ ``imageio.core.Format.Reader`` and that implements the following functions:
42
+
43
+ * Implement ``_open(**kwargs)`` to initialize the reader. Deal with the
44
+ user-provided keyword arguments here.
45
+ * Implement ``_close()`` to clean up.
46
+ * Implement ``_get_length()`` to provide a suitable length based on what
47
+ the user expects. Can be ``inf`` for streaming data.
48
+ * Implement ``_get_data(index)`` to return an array and a meta-data dict.
49
+ * Implement ``_get_meta_data(index)`` to return a meta-data dict. If index
50
+ is None, it should return the 'global' meta-data.
51
+
52
+ For writing, create a nested class that inherits from
53
+ ``imageio.core.Format.Writer`` and implement the following functions:
54
+
55
+ * Implement ``_open(**kwargs)`` to initialize the writer. Deal with the
56
+ user-provided keyword arguments here.
57
+ * Implement ``_close()`` to clean up.
58
+ * Implement ``_append_data(im, meta)`` to add data (and meta-data).
59
+ * Implement ``_set_meta_data(meta)`` to set the global meta-data.
60
+
61
+ """
62
+
63
+ import importlib
64
+ import os
65
+ import warnings
66
+
67
+
68
+ # v2 imports remove in v3
69
+ from .. import formats
70
+
71
+ # v2 allows formatting plugins by environment variable
72
+ # this is done here.
73
+ env_plugin_order = os.getenv("IMAGEIO_FORMAT_ORDER", None)
74
+ if env_plugin_order is not None: # pragma: no cover
75
+ warnings.warn(
76
+ "Setting plugin priority through an environment variable is"
77
+ " deprecated and will be removed in ImageIO v3. There is no"
78
+ " replacement planned for this feature. If you have an"
79
+ " active use-case for it, please reach out to us on GitHub.",
80
+ DeprecationWarning,
81
+ )
82
+
83
+ formats.sort(*os.getenv("IMAGEIO_FORMAT_ORDER", "").split(","))
84
+
85
+
86
+ # this class replaces plugin module. For details
87
+ # see https://stackoverflow.com/questions/2447353/getattr-on-a-module
88
+ def __getattr__(name):
89
+ """Lazy-Import Plugins
90
+
91
+ This function dynamically loads plugins into the imageio.plugin
92
+ namespace upon first access. For example, the following snippet will
93
+ delay importing freeimage until the second line:
94
+
95
+ >>> import imageio
96
+ >>> imageio.plugins.freeimage.download()
97
+
98
+ """
99
+
100
+ try:
101
+ return importlib.import_module(f"imageio.plugins.{name}")
102
+ except ImportError:
103
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'") from None
evalkit_tf446/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_tf446/lib/python3.10/site-packages/imageio/plugins/_freeimage.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ # styletest: ignore E261
5
+
6
+ """ Module imageio/freeimage.py
7
+
8
+ This module contains the wrapper code for the freeimage library.
9
+ The functions defined in this module are relatively thin; just thin
10
+ enough so that arguments and results are native Python/numpy data
11
+ types.
12
+
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import ctypes
18
+ import threading
19
+ import logging
20
+ import numpy
21
+
22
+ from ..core import (
23
+ get_remote_file,
24
+ load_lib,
25
+ Dict,
26
+ resource_dirs,
27
+ IS_PYPY,
28
+ get_platform,
29
+ InternetNotAllowedError,
30
+ NeedDownloadError,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ TEST_NUMPY_NO_STRIDES = False # To test pypy fallback
36
+
37
+ FNAME_PER_PLATFORM = {
38
+ "osx32": "libfreeimage-3.16.0-osx10.6.dylib", # universal library
39
+ "osx64": "libfreeimage-3.16.0-osx10.6.dylib",
40
+ "win32": "FreeImage-3.18.0-win32.dll",
41
+ "win64": "FreeImage-3.18.0-win64.dll",
42
+ "linux32": "libfreeimage-3.16.0-linux32.so",
43
+ "linux64": "libfreeimage-3.16.0-linux64.so",
44
+ }
45
+
46
+
47
+ def download(directory=None, force_download=False):
48
+ """Download the FreeImage library to your computer.
49
+
50
+ Parameters
51
+ ----------
52
+ directory : str | None
53
+ The directory where the file will be cached if a download was
54
+ required to obtain the file. By default, the appdata directory
55
+ is used. This is also the first directory that is checked for
56
+ a local version of the file.
57
+ force_download : bool | str
58
+ If True, the file will be downloaded even if a local copy exists
59
+ (and this copy will be overwritten). Can also be a YYYY-MM-DD date
60
+ to ensure a file is up-to-date (modified date of a file on disk,
61
+ if present, is checked).
62
+ """
63
+ plat = get_platform()
64
+ if plat and plat in FNAME_PER_PLATFORM:
65
+ fname = "freeimage/" + FNAME_PER_PLATFORM[plat]
66
+ get_remote_file(fname=fname, directory=directory, force_download=force_download)
67
+ fi._lib = None # allow trying again (needed to make tests work)
68
+
69
+
70
+ def get_freeimage_lib():
71
+ """Ensure we have our version of the binary freeimage lib."""
72
+
73
+ lib = os.getenv("IMAGEIO_FREEIMAGE_LIB", None)
74
+ if lib: # pragma: no cover
75
+ return lib
76
+
77
+ # Get filename to load
78
+ # If we do not provide a binary, the system may still do ...
79
+ plat = get_platform()
80
+ if plat and plat in FNAME_PER_PLATFORM:
81
+ try:
82
+ return get_remote_file("freeimage/" + FNAME_PER_PLATFORM[plat], auto=False)
83
+ except InternetNotAllowedError:
84
+ pass
85
+ except NeedDownloadError:
86
+ raise NeedDownloadError(
87
+ "Need FreeImage library. "
88
+ "You can obtain it with either:\n"
89
+ " - download using the command: "
90
+ "imageio_download_bin freeimage\n"
91
+ " - download by calling (in Python): "
92
+ "imageio.plugins.freeimage.download()\n"
93
+ )
94
+ except RuntimeError as e: # pragma: no cover
95
+ logger.warning(str(e))
96
+
97
+
98
+ # Define function to encode a filename to bytes (for the current system)
99
+ def efn(x):
100
+ return x.encode(sys.getfilesystemencoding())
101
+
102
+
103
+ # 4-byte quads of 0,v,v,v from 0,0,0,0 to 0,255,255,255
104
+ GREY_PALETTE = numpy.arange(0, 0x01000000, 0x00010101, dtype=numpy.uint32)
105
+
106
+
107
+ class FI_TYPES(object):
108
+ FIT_UNKNOWN = 0
109
+ FIT_BITMAP = 1
110
+ FIT_UINT16 = 2
111
+ FIT_INT16 = 3
112
+ FIT_UINT32 = 4
113
+ FIT_INT32 = 5
114
+ FIT_FLOAT = 6
115
+ FIT_DOUBLE = 7
116
+ FIT_COMPLEX = 8
117
+ FIT_RGB16 = 9
118
+ FIT_RGBA16 = 10
119
+ FIT_RGBF = 11
120
+ FIT_RGBAF = 12
121
+
122
+ dtypes = {
123
+ FIT_BITMAP: numpy.uint8,
124
+ FIT_UINT16: numpy.uint16,
125
+ FIT_INT16: numpy.int16,
126
+ FIT_UINT32: numpy.uint32,
127
+ FIT_INT32: numpy.int32,
128
+ FIT_FLOAT: numpy.float32,
129
+ FIT_DOUBLE: numpy.float64,
130
+ FIT_COMPLEX: numpy.complex128,
131
+ FIT_RGB16: numpy.uint16,
132
+ FIT_RGBA16: numpy.uint16,
133
+ FIT_RGBF: numpy.float32,
134
+ FIT_RGBAF: numpy.float32,
135
+ }
136
+
137
+ fi_types = {
138
+ (numpy.uint8, 1): FIT_BITMAP,
139
+ (numpy.uint8, 3): FIT_BITMAP,
140
+ (numpy.uint8, 4): FIT_BITMAP,
141
+ (numpy.uint16, 1): FIT_UINT16,
142
+ (numpy.int16, 1): FIT_INT16,
143
+ (numpy.uint32, 1): FIT_UINT32,
144
+ (numpy.int32, 1): FIT_INT32,
145
+ (numpy.float32, 1): FIT_FLOAT,
146
+ (numpy.float64, 1): FIT_DOUBLE,
147
+ (numpy.complex128, 1): FIT_COMPLEX,
148
+ (numpy.uint16, 3): FIT_RGB16,
149
+ (numpy.uint16, 4): FIT_RGBA16,
150
+ (numpy.float32, 3): FIT_RGBF,
151
+ (numpy.float32, 4): FIT_RGBAF,
152
+ }
153
+
154
+ extra_dims = {
155
+ FIT_UINT16: [],
156
+ FIT_INT16: [],
157
+ FIT_UINT32: [],
158
+ FIT_INT32: [],
159
+ FIT_FLOAT: [],
160
+ FIT_DOUBLE: [],
161
+ FIT_COMPLEX: [],
162
+ FIT_RGB16: [3],
163
+ FIT_RGBA16: [4],
164
+ FIT_RGBF: [3],
165
+ FIT_RGBAF: [4],
166
+ }
167
+
168
+
169
+ class IO_FLAGS(object):
170
+ FIF_LOAD_NOPIXELS = 0x8000 # loading: load the image header only
171
+ # # (not supported by all plugins)
172
+ BMP_DEFAULT = 0
173
+ BMP_SAVE_RLE = 1
174
+ CUT_DEFAULT = 0
175
+ DDS_DEFAULT = 0
176
+ EXR_DEFAULT = 0 # save data as half with piz-based wavelet compression
177
+ EXR_FLOAT = 0x0001 # save data as float instead of half (not recommended)
178
+ EXR_NONE = 0x0002 # save with no compression
179
+ EXR_ZIP = 0x0004 # save with zlib compression, in blocks of 16 scan lines
180
+ EXR_PIZ = 0x0008 # save with piz-based wavelet compression
181
+ EXR_PXR24 = 0x0010 # save with lossy 24-bit float compression
182
+ EXR_B44 = 0x0020 # save with lossy 44% float compression
183
+ # # - goes to 22% when combined with EXR_LC
184
+ EXR_LC = 0x0040 # save images with one luminance and two chroma channels,
185
+ # # rather than as RGB (lossy compression)
186
+ FAXG3_DEFAULT = 0
187
+ GIF_DEFAULT = 0
188
+ GIF_LOAD256 = 1 # Load the image as a 256 color image with ununsed
189
+ # # palette entries, if it's 16 or 2 color
190
+ GIF_PLAYBACK = 2 # 'Play' the GIF to generate each frame (as 32bpp)
191
+ # # instead of returning raw frame data when loading
192
+ HDR_DEFAULT = 0
193
+ ICO_DEFAULT = 0
194
+ ICO_MAKEALPHA = 1 # convert to 32bpp and create an alpha channel from the
195
+ # # AND-mask when loading
196
+ IFF_DEFAULT = 0
197
+ J2K_DEFAULT = 0 # save with a 16:1 rate
198
+ JP2_DEFAULT = 0 # save with a 16:1 rate
199
+ JPEG_DEFAULT = 0 # loading (see JPEG_FAST);
200
+ # # saving (see JPEG_QUALITYGOOD|JPEG_SUBSAMPLING_420)
201
+ JPEG_FAST = 0x0001 # load the file as fast as possible,
202
+ # # sacrificing some quality
203
+ JPEG_ACCURATE = 0x0002 # load the file with the best quality,
204
+ # # sacrificing some speed
205
+ JPEG_CMYK = 0x0004 # load separated CMYK "as is"
206
+ # # (use | to combine with other load flags)
207
+ JPEG_EXIFROTATE = 0x0008 # load and rotate according to
208
+ # # Exif 'Orientation' tag if available
209
+ JPEG_QUALITYSUPERB = 0x80 # save with superb quality (100:1)
210
+ JPEG_QUALITYGOOD = 0x0100 # save with good quality (75:1)
211
+ JPEG_QUALITYNORMAL = 0x0200 # save with normal quality (50:1)
212
+ JPEG_QUALITYAVERAGE = 0x0400 # save with average quality (25:1)
213
+ JPEG_QUALITYBAD = 0x0800 # save with bad quality (10:1)
214
+ JPEG_PROGRESSIVE = 0x2000 # save as a progressive-JPEG
215
+ # # (use | to combine with other save flags)
216
+ JPEG_SUBSAMPLING_411 = 0x1000 # save with high 4x1 chroma
217
+ # # subsampling (4:1:1)
218
+ JPEG_SUBSAMPLING_420 = 0x4000 # save with medium 2x2 medium chroma
219
+ # # subsampling (4:2:0) - default value
220
+ JPEG_SUBSAMPLING_422 = 0x8000 # save /w low 2x1 chroma subsampling (4:2:2)
221
+ JPEG_SUBSAMPLING_444 = 0x10000 # save with no chroma subsampling (4:4:4)
222
+ JPEG_OPTIMIZE = 0x20000 # on saving, compute optimal Huffman coding tables
223
+ # # (can reduce a few percent of file size)
224
+ JPEG_BASELINE = 0x40000 # save basic JPEG, without metadata or any markers
225
+ KOALA_DEFAULT = 0
226
+ LBM_DEFAULT = 0
227
+ MNG_DEFAULT = 0
228
+ PCD_DEFAULT = 0
229
+ PCD_BASE = 1 # load the bitmap sized 768 x 512
230
+ PCD_BASEDIV4 = 2 # load the bitmap sized 384 x 256
231
+ PCD_BASEDIV16 = 3 # load the bitmap sized 192 x 128
232
+ PCX_DEFAULT = 0
233
+ PFM_DEFAULT = 0
234
+ PICT_DEFAULT = 0
235
+ PNG_DEFAULT = 0
236
+ PNG_IGNOREGAMMA = 1 # loading: avoid gamma correction
237
+ PNG_Z_BEST_SPEED = 0x0001 # save using ZLib level 1 compression flag
238
+ # # (default value is 6)
239
+ PNG_Z_DEFAULT_COMPRESSION = 0x0006 # save using ZLib level 6 compression
240
+ # # flag (default recommended value)
241
+ PNG_Z_BEST_COMPRESSION = 0x0009 # save using ZLib level 9 compression flag
242
+ # # (default value is 6)
243
+ PNG_Z_NO_COMPRESSION = 0x0100 # save without ZLib compression
244
+ PNG_INTERLACED = 0x0200 # save using Adam7 interlacing (use | to combine
245
+ # # with other save flags)
246
+ PNM_DEFAULT = 0
247
+ PNM_SAVE_RAW = 0 # Writer saves in RAW format (i.e. P4, P5 or P6)
248
+ PNM_SAVE_ASCII = 1 # Writer saves in ASCII format (i.e. P1, P2 or P3)
249
+ PSD_DEFAULT = 0
250
+ PSD_CMYK = 1 # reads tags for separated CMYK (default is conversion to RGB)
251
+ PSD_LAB = 2 # reads tags for CIELab (default is conversion to RGB)
252
+ RAS_DEFAULT = 0
253
+ RAW_DEFAULT = 0 # load the file as linear RGB 48-bit
254
+ RAW_PREVIEW = 1 # try to load the embedded JPEG preview with included
255
+ # # Exif Data or default to RGB 24-bit
256
+ RAW_DISPLAY = 2 # load the file as RGB 24-bit
257
+ SGI_DEFAULT = 0
258
+ TARGA_DEFAULT = 0
259
+ TARGA_LOAD_RGB888 = 1 # Convert RGB555 and ARGB8888 -> RGB888.
260
+ TARGA_SAVE_RLE = 2 # Save with RLE compression
261
+ TIFF_DEFAULT = 0
262
+ TIFF_CMYK = 0x0001 # reads/stores tags for separated CMYK
263
+ # # (use | to combine with compression flags)
264
+ TIFF_PACKBITS = 0x0100 # save using PACKBITS compression
265
+ TIFF_DEFLATE = 0x0200 # save using DEFLATE (a.k.a. ZLIB) compression
266
+ TIFF_ADOBE_DEFLATE = 0x0400 # save using ADOBE DEFLATE compression
267
+ TIFF_NONE = 0x0800 # save without any compression
268
+ TIFF_CCITTFAX3 = 0x1000 # save using CCITT Group 3 fax encoding
269
+ TIFF_CCITTFAX4 = 0x2000 # save using CCITT Group 4 fax encoding
270
+ TIFF_LZW = 0x4000 # save using LZW compression
271
+ TIFF_JPEG = 0x8000 # save using JPEG compression
272
+ TIFF_LOGLUV = 0x10000 # save using LogLuv compression
273
+ WBMP_DEFAULT = 0
274
+ XBM_DEFAULT = 0
275
+ XPM_DEFAULT = 0
276
+
277
+
278
+ class METADATA_MODELS(object):
279
+ FIMD_COMMENTS = 0
280
+ FIMD_EXIF_MAIN = 1
281
+ FIMD_EXIF_EXIF = 2
282
+ FIMD_EXIF_GPS = 3
283
+ FIMD_EXIF_MAKERNOTE = 4
284
+ FIMD_EXIF_INTEROP = 5
285
+ FIMD_IPTC = 6
286
+ FIMD_XMP = 7
287
+ FIMD_GEOTIFF = 8
288
+ FIMD_ANIMATION = 9
289
+
290
+
291
+ class METADATA_DATATYPE(object):
292
+ FIDT_BYTE = 1 # 8-bit unsigned integer
293
+ FIDT_ASCII = 2 # 8-bit bytes w/ last byte null
294
+ FIDT_SHORT = 3 # 16-bit unsigned integer
295
+ FIDT_LONG = 4 # 32-bit unsigned integer
296
+ FIDT_RATIONAL = 5 # 64-bit unsigned fraction
297
+ FIDT_SBYTE = 6 # 8-bit signed integer
298
+ FIDT_UNDEFINED = 7 # 8-bit untyped data
299
+ FIDT_SSHORT = 8 # 16-bit signed integer
300
+ FIDT_SLONG = 9 # 32-bit signed integer
301
+ FIDT_SRATIONAL = 10 # 64-bit signed fraction
302
+ FIDT_FLOAT = 11 # 32-bit IEEE floating point
303
+ FIDT_DOUBLE = 12 # 64-bit IEEE floating point
304
+ FIDT_IFD = 13 # 32-bit unsigned integer (offset)
305
+ FIDT_PALETTE = 14 # 32-bit RGBQUAD
306
+ FIDT_LONG8 = 16 # 64-bit unsigned integer
307
+ FIDT_SLONG8 = 17 # 64-bit signed integer
308
+ FIDT_IFD8 = 18 # 64-bit unsigned integer (offset)
309
+
310
+ dtypes = {
311
+ FIDT_BYTE: numpy.uint8,
312
+ FIDT_SHORT: numpy.uint16,
313
+ FIDT_LONG: numpy.uint32,
314
+ FIDT_RATIONAL: [("numerator", numpy.uint32), ("denominator", numpy.uint32)],
315
+ FIDT_LONG8: numpy.uint64,
316
+ FIDT_SLONG8: numpy.int64,
317
+ FIDT_IFD8: numpy.uint64,
318
+ FIDT_SBYTE: numpy.int8,
319
+ FIDT_UNDEFINED: numpy.uint8,
320
+ FIDT_SSHORT: numpy.int16,
321
+ FIDT_SLONG: numpy.int32,
322
+ FIDT_SRATIONAL: [("numerator", numpy.int32), ("denominator", numpy.int32)],
323
+ FIDT_FLOAT: numpy.float32,
324
+ FIDT_DOUBLE: numpy.float64,
325
+ FIDT_IFD: numpy.uint32,
326
+ FIDT_PALETTE: [
327
+ ("R", numpy.uint8),
328
+ ("G", numpy.uint8),
329
+ ("B", numpy.uint8),
330
+ ("A", numpy.uint8),
331
+ ],
332
+ }
333
+
334
+
335
+ class Freeimage(object):
336
+ """Class to represent an interface to the FreeImage library.
337
+ This class is relatively thin. It provides a Pythonic API that converts
338
+ Freeimage objects to Python objects, but that's about it.
339
+ The actual implementation should be provided by the plugins.
340
+
341
+ The recommended way to call into the Freeimage library (so that
342
+ errors and warnings show up in the right moment) is to use this
343
+ object as a context manager:
344
+ with imageio.fi as lib:
345
+ lib.FreeImage_GetPalette()
346
+
347
+ """
348
+
349
+ _API = {
350
+ # All we're doing here is telling ctypes that some of the
351
+ # FreeImage functions return pointers instead of integers. (On
352
+ # 64-bit systems, without this information the pointers get
353
+ # truncated and crashes result). There's no need to list
354
+ # functions that return ints, or the types of the parameters
355
+ # to these or other functions -- that's fine to do implicitly.
356
+ # Note that the ctypes immediately converts the returned void_p
357
+ # back to a python int again! This is really not helpful,
358
+ # because then passing it back to another library call will
359
+ # cause truncation-to-32-bits on 64-bit systems. Thanks, ctypes!
360
+ # So after these calls one must immediately re-wrap the int as
361
+ # a c_void_p if it is to be passed back into FreeImage.
362
+ "FreeImage_AllocateT": (ctypes.c_void_p, None),
363
+ "FreeImage_FindFirstMetadata": (ctypes.c_void_p, None),
364
+ "FreeImage_GetBits": (ctypes.c_void_p, None),
365
+ "FreeImage_GetPalette": (ctypes.c_void_p, None),
366
+ "FreeImage_GetTagKey": (ctypes.c_char_p, None),
367
+ "FreeImage_GetTagValue": (ctypes.c_void_p, None),
368
+ "FreeImage_CreateTag": (ctypes.c_void_p, None),
369
+ "FreeImage_Save": (ctypes.c_void_p, None),
370
+ "FreeImage_Load": (ctypes.c_void_p, None),
371
+ "FreeImage_LoadFromMemory": (ctypes.c_void_p, None),
372
+ "FreeImage_OpenMultiBitmap": (ctypes.c_void_p, None),
373
+ "FreeImage_LoadMultiBitmapFromMemory": (ctypes.c_void_p, None),
374
+ "FreeImage_LockPage": (ctypes.c_void_p, None),
375
+ "FreeImage_OpenMemory": (ctypes.c_void_p, None),
376
+ # 'FreeImage_ReadMemory': (ctypes.c_void_p, None),
377
+ # 'FreeImage_CloseMemory': (ctypes.c_void_p, None),
378
+ "FreeImage_GetVersion": (ctypes.c_char_p, None),
379
+ "FreeImage_GetFIFExtensionList": (ctypes.c_char_p, None),
380
+ "FreeImage_GetFormatFromFIF": (ctypes.c_char_p, None),
381
+ "FreeImage_GetFIFDescription": (ctypes.c_char_p, None),
382
+ "FreeImage_ColorQuantizeEx": (ctypes.c_void_p, None),
383
+ # Pypy wants some extra definitions, so here we go ...
384
+ "FreeImage_IsLittleEndian": (ctypes.c_int, None),
385
+ "FreeImage_SetOutputMessage": (ctypes.c_void_p, None),
386
+ "FreeImage_GetFIFCount": (ctypes.c_int, None),
387
+ "FreeImage_IsPluginEnabled": (ctypes.c_int, None),
388
+ "FreeImage_GetFileType": (ctypes.c_int, None),
389
+ #
390
+ "FreeImage_GetTagType": (ctypes.c_int, None),
391
+ "FreeImage_GetTagLength": (ctypes.c_int, None),
392
+ "FreeImage_FindNextMetadata": (ctypes.c_int, None),
393
+ "FreeImage_FindCloseMetadata": (ctypes.c_void_p, None),
394
+ #
395
+ "FreeImage_GetFIFFromFilename": (ctypes.c_int, None),
396
+ "FreeImage_FIFSupportsReading": (ctypes.c_int, None),
397
+ "FreeImage_FIFSupportsWriting": (ctypes.c_int, None),
398
+ "FreeImage_FIFSupportsExportType": (ctypes.c_int, None),
399
+ "FreeImage_FIFSupportsExportBPP": (ctypes.c_int, None),
400
+ "FreeImage_GetHeight": (ctypes.c_int, None),
401
+ "FreeImage_GetWidth": (ctypes.c_int, None),
402
+ "FreeImage_GetImageType": (ctypes.c_int, None),
403
+ "FreeImage_GetBPP": (ctypes.c_int, None),
404
+ "FreeImage_GetColorsUsed": (ctypes.c_int, None),
405
+ "FreeImage_ConvertTo32Bits": (ctypes.c_void_p, None),
406
+ "FreeImage_GetPitch": (ctypes.c_int, None),
407
+ "FreeImage_Unload": (ctypes.c_void_p, None),
408
+ }
409
+
410
+ def __init__(self):
411
+ # Initialize freeimage lib as None
412
+ self._lib = None
413
+
414
+ # A lock to create thread-safety
415
+ self._lock = threading.RLock()
416
+
417
+ # Init log messages lists
418
+ self._messages = []
419
+
420
+ # Select functype for error handler
421
+ if sys.platform.startswith("win"):
422
+ functype = ctypes.WINFUNCTYPE
423
+ else:
424
+ functype = ctypes.CFUNCTYPE
425
+
426
+ # Create output message handler
427
+ @functype(None, ctypes.c_int, ctypes.c_char_p)
428
+ def error_handler(fif, message):
429
+ message = message.decode("utf-8")
430
+ self._messages.append(message)
431
+ while (len(self._messages)) > 256:
432
+ self._messages.pop(0)
433
+
434
+ # Make sure to keep a ref to function
435
+ self._error_handler = error_handler
436
+
437
+ @property
438
+ def lib(self):
439
+ if self._lib is None:
440
+ try:
441
+ self.load_freeimage()
442
+ except OSError as err:
443
+ self._lib = "The freeimage library could not be loaded: "
444
+ self._lib += str(err)
445
+ if isinstance(self._lib, str):
446
+ raise RuntimeError(self._lib)
447
+ return self._lib
448
+
449
+ def has_lib(self):
450
+ try:
451
+ self.lib
452
+ except Exception:
453
+ return False
454
+ return True
455
+
456
+ def load_freeimage(self):
457
+ """Try to load the freeimage lib from the system. If not successful,
458
+ try to download the imageio version and try again.
459
+ """
460
+ # Load library and register API
461
+ success = False
462
+ try:
463
+ # Try without forcing a download, but giving preference
464
+ # to the imageio-provided lib (if previously downloaded)
465
+ self._load_freeimage()
466
+ self._register_api()
467
+ if self.lib.FreeImage_GetVersion().decode("utf-8") >= "3.15":
468
+ success = True
469
+ except OSError:
470
+ pass
471
+
472
+ if not success:
473
+ # Ensure we have our own lib, try again
474
+ get_freeimage_lib()
475
+ self._load_freeimage()
476
+ self._register_api()
477
+
478
+ # Wrap up
479
+ self.lib.FreeImage_SetOutputMessage(self._error_handler)
480
+ self.lib_version = self.lib.FreeImage_GetVersion().decode("utf-8")
481
+
482
+ def _load_freeimage(self):
483
+ # Define names
484
+ lib_names = ["freeimage", "libfreeimage"]
485
+ exact_lib_names = [
486
+ "FreeImage",
487
+ "libfreeimage.dylib",
488
+ "libfreeimage.so",
489
+ "libfreeimage.so.3",
490
+ ]
491
+ # Add names of libraries that we provide (that file may not exist)
492
+ res_dirs = resource_dirs()
493
+ plat = get_platform()
494
+ if plat: # Can be None on e.g. FreeBSD
495
+ fname = FNAME_PER_PLATFORM[plat]
496
+ for dir in res_dirs:
497
+ exact_lib_names.insert(0, os.path.join(dir, "freeimage", fname))
498
+
499
+ # Add the path specified with IMAGEIO_FREEIMAGE_LIB:
500
+ lib = os.getenv("IMAGEIO_FREEIMAGE_LIB", None)
501
+ if lib is not None:
502
+ exact_lib_names.insert(0, lib)
503
+
504
+ # Load
505
+ try:
506
+ lib, fname = load_lib(exact_lib_names, lib_names, res_dirs)
507
+ except OSError as err: # pragma: no cover
508
+ err_msg = str(err) + "\nPlease install the FreeImage library."
509
+ raise OSError(err_msg)
510
+
511
+ # Store
512
+ self._lib = lib
513
+ self.lib_fname = fname
514
+
515
+ def _register_api(self):
516
+ # Albert's ctypes pattern
517
+ for f, (restype, argtypes) in self._API.items():
518
+ func = getattr(self.lib, f)
519
+ func.restype = restype
520
+ func.argtypes = argtypes
521
+
522
+ # Handling of output messages
523
+
524
+ def __enter__(self):
525
+ self._lock.acquire()
526
+ return self.lib
527
+
528
+ def __exit__(self, *args):
529
+ self._show_any_warnings()
530
+ self._lock.release()
531
+
532
+ def _reset_log(self):
533
+ """Reset the list of output messages. Call this before
534
+ loading or saving an image with the FreeImage API.
535
+ """
536
+ self._messages = []
537
+
538
+ def _get_error_message(self):
539
+ """Get the output messages produced since the last reset as
540
+ one string. Returns 'No known reason.' if there are no messages.
541
+ Also resets the log.
542
+ """
543
+ if self._messages:
544
+ res = " ".join(self._messages)
545
+ self._reset_log()
546
+ return res
547
+ else:
548
+ return "No known reason."
549
+
550
+ def _show_any_warnings(self):
551
+ """If there were any messages since the last reset, show them
552
+ as a warning. Otherwise do nothing. Also resets the messages.
553
+ """
554
+ if self._messages:
555
+ logger.warning("imageio.freeimage warning: " + self._get_error_message())
556
+ self._reset_log()
557
+
558
+ def get_output_log(self):
559
+ """Return a list of the last 256 output messages
560
+ (warnings and errors) produced by the FreeImage library.
561
+ """
562
+ # This message log is not cleared/reset, but kept to 256 elements.
563
+ return [m for m in self._messages]
564
+
565
+ def getFIF(self, filename, mode, bb=None):
566
+ """Get the freeimage Format (FIF) from a given filename.
567
+ If mode is 'r', will try to determine the format by reading
568
+ the file, otherwise only the filename is used.
569
+
570
+ This function also tests whether the format supports reading/writing.
571
+ """
572
+ with self as lib:
573
+ # Init
574
+ ftype = -1
575
+ if mode not in "rw":
576
+ raise ValueError('Invalid mode (must be "r" or "w").')
577
+
578
+ # Try getting format from the content. Note that some files
579
+ # do not have a header that allows reading the format from
580
+ # the file.
581
+ if mode == "r":
582
+ if bb is not None:
583
+ fimemory = lib.FreeImage_OpenMemory(ctypes.c_char_p(bb), len(bb))
584
+ ftype = lib.FreeImage_GetFileTypeFromMemory(
585
+ ctypes.c_void_p(fimemory), len(bb)
586
+ )
587
+ lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
588
+ if (ftype == -1) and os.path.isfile(filename):
589
+ ftype = lib.FreeImage_GetFileType(efn(filename), 0)
590
+ # Try getting the format from the extension
591
+ if ftype == -1:
592
+ ftype = lib.FreeImage_GetFIFFromFilename(efn(filename))
593
+
594
+ # Test if ok
595
+ if ftype == -1:
596
+ raise ValueError('Cannot determine format of file "%s"' % filename)
597
+ elif mode == "w" and not lib.FreeImage_FIFSupportsWriting(ftype):
598
+ raise ValueError('Cannot write the format of file "%s"' % filename)
599
+ elif mode == "r" and not lib.FreeImage_FIFSupportsReading(ftype):
600
+ raise ValueError('Cannot read the format of file "%s"' % filename)
601
+ return ftype
602
+
603
+ def create_bitmap(self, filename, ftype, flags=0):
604
+ """create_bitmap(filename, ftype, flags=0)
605
+ Create a wrapped bitmap object.
606
+ """
607
+ return FIBitmap(self, filename, ftype, flags)
608
+
609
+ def create_multipage_bitmap(self, filename, ftype, flags=0):
610
+ """create_multipage_bitmap(filename, ftype, flags=0)
611
+ Create a wrapped multipage bitmap object.
612
+ """
613
+ return FIMultipageBitmap(self, filename, ftype, flags)
614
+
615
+
616
+ class FIBaseBitmap(object):
617
+ def __init__(self, fi, filename, ftype, flags):
618
+ self._fi = fi
619
+ self._filename = filename
620
+ self._ftype = ftype
621
+ self._flags = flags
622
+ self._bitmap = None
623
+ self._close_funcs = []
624
+
625
+ def __del__(self):
626
+ self.close()
627
+
628
+ def close(self):
629
+ if (self._bitmap is not None) and self._close_funcs:
630
+ for close_func in self._close_funcs:
631
+ try:
632
+ with self._fi:
633
+ fun = close_func[0]
634
+ fun(*close_func[1:])
635
+ except Exception: # pragma: no cover
636
+ pass
637
+ self._close_funcs = []
638
+ self._bitmap = None
639
+
640
+ def _set_bitmap(self, bitmap, close_func=None):
641
+ """Function to set the bitmap and specify the function to unload it."""
642
+ if self._bitmap is not None:
643
+ pass # bitmap is converted
644
+ if close_func is None:
645
+ close_func = self._fi.lib.FreeImage_Unload, bitmap
646
+
647
+ self._bitmap = bitmap
648
+ if close_func:
649
+ self._close_funcs.append(close_func)
650
+
651
+ def get_meta_data(self):
652
+ # todo: there is also FreeImage_TagToString, is that useful?
653
+ # and would that work well when reading and then saving?
654
+
655
+ # Create a list of (model_name, number) tuples
656
+ models = [
657
+ (name[5:], number)
658
+ for name, number in METADATA_MODELS.__dict__.items()
659
+ if name.startswith("FIMD_")
660
+ ]
661
+
662
+ # Prepare
663
+ metadata = Dict()
664
+ tag = ctypes.c_void_p()
665
+
666
+ with self._fi as lib:
667
+ # Iterate over all FreeImage meta models
668
+ for model_name, number in models:
669
+ # Find beginning, get search handle
670
+ mdhandle = lib.FreeImage_FindFirstMetadata(
671
+ number, self._bitmap, ctypes.byref(tag)
672
+ )
673
+ mdhandle = ctypes.c_void_p(mdhandle)
674
+ if mdhandle:
675
+ # Iterate over all tags in this model
676
+ more = True
677
+ while more:
678
+ # Get info about tag
679
+ tag_name = lib.FreeImage_GetTagKey(tag).decode("utf-8")
680
+ tag_type = lib.FreeImage_GetTagType(tag)
681
+ byte_size = lib.FreeImage_GetTagLength(tag)
682
+ char_ptr = ctypes.c_char * byte_size
683
+ data = char_ptr.from_address(lib.FreeImage_GetTagValue(tag))
684
+ # Convert in a way compatible with Pypy
685
+ tag_bytes = bytes(bytearray(data))
686
+ # The default value is the raw bytes
687
+ tag_val = tag_bytes
688
+ # Convert to a Python value in the metadata dict
689
+ if tag_type == METADATA_DATATYPE.FIDT_ASCII:
690
+ tag_val = tag_bytes.decode("utf-8", "replace")
691
+ elif tag_type in METADATA_DATATYPE.dtypes:
692
+ dtype = METADATA_DATATYPE.dtypes[tag_type]
693
+ if IS_PYPY and isinstance(dtype, (list, tuple)):
694
+ pass # pragma: no cover - or we get a segfault
695
+ else:
696
+ try:
697
+ tag_val = numpy.frombuffer(
698
+ tag_bytes, dtype=dtype
699
+ ).copy()
700
+ if len(tag_val) == 1:
701
+ tag_val = tag_val[0]
702
+ except Exception: # pragma: no cover
703
+ pass
704
+ # Store data in dict
705
+ subdict = metadata.setdefault(model_name, Dict())
706
+ subdict[tag_name] = tag_val
707
+ # Next
708
+ more = lib.FreeImage_FindNextMetadata(
709
+ mdhandle, ctypes.byref(tag)
710
+ )
711
+
712
+ # Close search handle for current meta model
713
+ lib.FreeImage_FindCloseMetadata(mdhandle)
714
+
715
+ # Done
716
+ return metadata
717
+
718
+ def set_meta_data(self, metadata):
719
+ # Create a dict mapping model_name to number
720
+ models = {}
721
+ for name, number in METADATA_MODELS.__dict__.items():
722
+ if name.startswith("FIMD_"):
723
+ models[name[5:]] = number
724
+
725
+ # Create a mapping from numpy.dtype to METADATA_DATATYPE
726
+ def get_tag_type_number(dtype):
727
+ for number, numpy_dtype in METADATA_DATATYPE.dtypes.items():
728
+ if dtype == numpy_dtype:
729
+ return number
730
+ else:
731
+ return None
732
+
733
+ with self._fi as lib:
734
+ for model_name, subdict in metadata.items():
735
+ # Get model number
736
+ number = models.get(model_name, None)
737
+ if number is None:
738
+ continue # Unknown model, silent ignore
739
+
740
+ for tag_name, tag_val in subdict.items():
741
+ # Create new tag
742
+ tag = lib.FreeImage_CreateTag()
743
+ tag = ctypes.c_void_p(tag)
744
+
745
+ try:
746
+ # Convert Python value to FI type, val
747
+ is_ascii = False
748
+ if isinstance(tag_val, str):
749
+ try:
750
+ tag_bytes = tag_val.encode("ascii")
751
+ is_ascii = True
752
+ except UnicodeError:
753
+ pass
754
+ if is_ascii:
755
+ tag_type = METADATA_DATATYPE.FIDT_ASCII
756
+ tag_count = len(tag_bytes)
757
+ else:
758
+ if not hasattr(tag_val, "dtype"):
759
+ tag_val = numpy.array([tag_val])
760
+ tag_type = get_tag_type_number(tag_val.dtype)
761
+ if tag_type is None:
762
+ logger.warning(
763
+ "imageio.freeimage warning: Could not "
764
+ "determine tag type of %r." % tag_name
765
+ )
766
+ continue
767
+ tag_bytes = tag_val.tobytes()
768
+ tag_count = tag_val.size
769
+ # Set properties
770
+ lib.FreeImage_SetTagKey(tag, tag_name.encode("utf-8"))
771
+ lib.FreeImage_SetTagType(tag, tag_type)
772
+ lib.FreeImage_SetTagCount(tag, tag_count)
773
+ lib.FreeImage_SetTagLength(tag, len(tag_bytes))
774
+ lib.FreeImage_SetTagValue(tag, tag_bytes)
775
+ # Store tag
776
+ tag_key = lib.FreeImage_GetTagKey(tag)
777
+ lib.FreeImage_SetMetadata(number, self._bitmap, tag_key, tag)
778
+
779
+ except Exception as err: # pragma: no cover
780
+ logger.warning(
781
+ "imagio.freeimage warning: Could not set tag "
782
+ "%r: %s, %s"
783
+ % (tag_name, self._fi._get_error_message(), str(err))
784
+ )
785
+ finally:
786
+ lib.FreeImage_DeleteTag(tag)
787
+
788
+
789
+ class FIBitmap(FIBaseBitmap):
790
+ """Wrapper for the FI bitmap object."""
791
+
792
+ def allocate(self, array):
793
+ # Prepare array
794
+ assert isinstance(array, numpy.ndarray)
795
+ shape = array.shape
796
+ dtype = array.dtype
797
+
798
+ # Get shape and channel info
799
+ r, c = shape[:2]
800
+ if len(shape) == 2:
801
+ n_channels = 1
802
+ elif len(shape) == 3:
803
+ n_channels = shape[2]
804
+ else:
805
+ n_channels = shape[0]
806
+
807
+ # Get fi_type
808
+ try:
809
+ fi_type = FI_TYPES.fi_types[(dtype.type, n_channels)]
810
+ self._fi_type = fi_type
811
+ except KeyError:
812
+ raise ValueError("Cannot write arrays of given type and shape.")
813
+
814
+ # Allocate bitmap
815
+ with self._fi as lib:
816
+ bpp = 8 * dtype.itemsize * n_channels
817
+ bitmap = lib.FreeImage_AllocateT(fi_type, c, r, bpp, 0, 0, 0)
818
+ bitmap = ctypes.c_void_p(bitmap)
819
+
820
+ # Check and store
821
+ if not bitmap: # pragma: no cover
822
+ raise RuntimeError(
823
+ "Could not allocate bitmap for storage: %s"
824
+ % self._fi._get_error_message()
825
+ )
826
+ self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
827
+
828
+ def load_from_filename(self, filename=None):
829
+ if filename is None:
830
+ filename = self._filename
831
+
832
+ with self._fi as lib:
833
+ # Create bitmap
834
+ bitmap = lib.FreeImage_Load(self._ftype, efn(filename), self._flags)
835
+ bitmap = ctypes.c_void_p(bitmap)
836
+
837
+ # Check and store
838
+ if not bitmap: # pragma: no cover
839
+ raise ValueError(
840
+ 'Could not load bitmap "%s": %s'
841
+ % (self._filename, self._fi._get_error_message())
842
+ )
843
+ self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
844
+
845
+ # def load_from_bytes(self, bb):
846
+ # with self._fi as lib:
847
+ # # Create bitmap
848
+ # fimemory = lib.FreeImage_OpenMemory(
849
+ # ctypes.c_char_p(bb), len(bb))
850
+ # bitmap = lib.FreeImage_LoadFromMemory(
851
+ # self._ftype, ctypes.c_void_p(fimemory), self._flags)
852
+ # bitmap = ctypes.c_void_p(bitmap)
853
+ # lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
854
+ #
855
+ # # Check
856
+ # if not bitmap:
857
+ # raise ValueError('Could not load bitmap "%s": %s'
858
+ # % (self._filename, self._fi._get_error_message()))
859
+ # else:
860
+ # self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
861
+
862
+ def save_to_filename(self, filename=None):
863
+ if filename is None:
864
+ filename = self._filename
865
+
866
+ ftype = self._ftype
867
+ bitmap = self._bitmap
868
+ fi_type = self._fi_type # element type
869
+
870
+ with self._fi as lib:
871
+ # Check if can write
872
+ if fi_type == FI_TYPES.FIT_BITMAP:
873
+ can_write = lib.FreeImage_FIFSupportsExportBPP(
874
+ ftype, lib.FreeImage_GetBPP(bitmap)
875
+ )
876
+ else:
877
+ can_write = lib.FreeImage_FIFSupportsExportType(ftype, fi_type)
878
+ if not can_write:
879
+ raise TypeError("Cannot save image of this format to this file type")
880
+
881
+ # Save to file
882
+ res = lib.FreeImage_Save(ftype, bitmap, efn(filename), self._flags)
883
+ # Check
884
+ if res is None: # pragma: no cover, we do so many checks, this is rare
885
+ raise RuntimeError(
886
+ f"Could not save file `{self._filename}`: {self._fi._get_error_message()}"
887
+ )
888
+
889
+ # def save_to_bytes(self):
890
+ # ftype = self._ftype
891
+ # bitmap = self._bitmap
892
+ # fi_type = self._fi_type # element type
893
+ #
894
+ # with self._fi as lib:
895
+ # # Check if can write
896
+ # if fi_type == FI_TYPES.FIT_BITMAP:
897
+ # can_write = lib.FreeImage_FIFSupportsExportBPP(ftype,
898
+ # lib.FreeImage_GetBPP(bitmap))
899
+ # else:
900
+ # can_write = lib.FreeImage_FIFSupportsExportType(ftype, fi_type)
901
+ # if not can_write:
902
+ # raise TypeError('Cannot save image of this format '
903
+ # 'to this file type')
904
+ #
905
+ # # Extract the bytes
906
+ # fimemory = lib.FreeImage_OpenMemory(0, 0)
907
+ # res = lib.FreeImage_SaveToMemory(ftype, bitmap,
908
+ # ctypes.c_void_p(fimemory),
909
+ # self._flags)
910
+ # if res:
911
+ # N = lib.FreeImage_TellMemory(ctypes.c_void_p(fimemory))
912
+ # result = ctypes.create_string_buffer(N)
913
+ # lib.FreeImage_SeekMemory(ctypes.c_void_p(fimemory), 0)
914
+ # lib.FreeImage_ReadMemory(result, 1, N, ctypes.c_void_p(fimemory))
915
+ # result = result.raw
916
+ # lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
917
+ #
918
+ # # Check
919
+ # if not res:
920
+ # raise RuntimeError('Could not save file "%s": %s'
921
+ # % (self._filename, self._fi._get_error_message()))
922
+ #
923
+ # # Done
924
+ # return result
925
+
926
+ def get_image_data(self):
927
+ dtype, shape, bpp = self._get_type_and_shape()
928
+ array = self._wrap_bitmap_bits_in_array(shape, dtype, False)
929
+ with self._fi as lib:
930
+ isle = lib.FreeImage_IsLittleEndian()
931
+
932
+ # swizzle the color components and flip the scanlines to go from
933
+ # FreeImage's BGR[A] and upside-down internal memory format to
934
+ # something more normal
935
+ def n(arr):
936
+ # return arr[..., ::-1].T # Does not work on numpypy yet
937
+ if arr.ndim == 1: # pragma: no cover
938
+ return arr[::-1].T
939
+ elif arr.ndim == 2: # Always the case here ...
940
+ return arr[:, ::-1].T
941
+ elif arr.ndim == 3: # pragma: no cover
942
+ return arr[:, :, ::-1].T
943
+ elif arr.ndim == 4: # pragma: no cover
944
+ return arr[:, :, :, ::-1].T
945
+
946
+ if len(shape) == 3 and isle and dtype.type == numpy.uint8:
947
+ b = n(array[0])
948
+ g = n(array[1])
949
+ r = n(array[2])
950
+ if shape[0] == 3:
951
+ return numpy.dstack((r, g, b))
952
+ elif shape[0] == 4:
953
+ a = n(array[3])
954
+ return numpy.dstack((r, g, b, a))
955
+ else: # pragma: no cover - we check this earlier
956
+ raise ValueError("Cannot handle images of shape %s" % shape)
957
+
958
+ # We need to copy because array does *not* own its memory
959
+ # after bitmap is freed.
960
+ a = n(array).copy()
961
+ return a
962
+
963
+ def set_image_data(self, array):
964
+ # Prepare array
965
+ assert isinstance(array, numpy.ndarray)
966
+ shape = array.shape
967
+ dtype = array.dtype
968
+ with self._fi as lib:
969
+ isle = lib.FreeImage_IsLittleEndian()
970
+
971
+ # Calculate shape and channels
972
+ r, c = shape[:2]
973
+ if len(shape) == 2:
974
+ n_channels = 1
975
+ w_shape = (c, r)
976
+ elif len(shape) == 3:
977
+ n_channels = shape[2]
978
+ w_shape = (n_channels, c, r)
979
+ else:
980
+ n_channels = shape[0]
981
+
982
+ def n(arr): # normalise to freeimage's in-memory format
983
+ return arr[::-1].T
984
+
985
+ wrapped_array = self._wrap_bitmap_bits_in_array(w_shape, dtype, True)
986
+ # swizzle the color components and flip the scanlines to go to
987
+ # FreeImage's BGR[A] and upside-down internal memory format
988
+ # The BGR[A] order is only used for 8bits per channel images
989
+ # on little endian machines. For everything else RGB[A] is
990
+ # used.
991
+ if len(shape) == 3 and isle and dtype.type == numpy.uint8:
992
+ R = array[:, :, 0]
993
+ G = array[:, :, 1]
994
+ B = array[:, :, 2]
995
+ wrapped_array[0] = n(B)
996
+ wrapped_array[1] = n(G)
997
+ wrapped_array[2] = n(R)
998
+ if shape[2] == 4:
999
+ A = array[:, :, 3]
1000
+ wrapped_array[3] = n(A)
1001
+ else:
1002
+ wrapped_array[:] = n(array)
1003
+ if self._need_finish:
1004
+ self._finish_wrapped_array(wrapped_array)
1005
+
1006
+ if len(shape) == 2 and dtype.type == numpy.uint8:
1007
+ with self._fi as lib:
1008
+ palette = lib.FreeImage_GetPalette(self._bitmap)
1009
+ palette = ctypes.c_void_p(palette)
1010
+ if not palette:
1011
+ raise RuntimeError("Could not get image palette")
1012
+ try:
1013
+ palette_data = GREY_PALETTE.ctypes.data
1014
+ except Exception: # pragma: no cover - IS_PYPY
1015
+ palette_data = GREY_PALETTE.__array_interface__["data"][0]
1016
+ ctypes.memmove(palette, palette_data, 1024)
1017
+
1018
+ def _wrap_bitmap_bits_in_array(self, shape, dtype, save):
1019
+ """Return an ndarray view on the data in a FreeImage bitmap. Only
1020
+ valid for as long as the bitmap is loaded (if single page) / locked
1021
+ in memory (if multipage). This is used in loading data, but
1022
+ also during saving, to prepare a strided numpy array buffer.
1023
+
1024
+ """
1025
+ # Get bitmap info
1026
+ with self._fi as lib:
1027
+ pitch = lib.FreeImage_GetPitch(self._bitmap)
1028
+ bits = lib.FreeImage_GetBits(self._bitmap)
1029
+
1030
+ # Get more info
1031
+ height = shape[-1]
1032
+ byte_size = height * pitch
1033
+ itemsize = dtype.itemsize
1034
+
1035
+ # Get strides
1036
+ if len(shape) == 3:
1037
+ strides = (itemsize, shape[0] * itemsize, pitch)
1038
+ else:
1039
+ strides = (itemsize, pitch)
1040
+
1041
+ # Create numpy array and return
1042
+ data = (ctypes.c_char * byte_size).from_address(bits)
1043
+ try:
1044
+ self._need_finish = False
1045
+ if TEST_NUMPY_NO_STRIDES:
1046
+ raise NotImplementedError()
1047
+ return numpy.ndarray(shape, dtype=dtype, buffer=data, strides=strides)
1048
+ except NotImplementedError:
1049
+ # IS_PYPY - not very efficient. We create a C-contiguous
1050
+ # numpy array (because pypy does not support Fortran-order)
1051
+ # and shape it such that the rest of the code can remain.
1052
+ if save:
1053
+ self._need_finish = True # Flag to use _finish_wrapped_array
1054
+ return numpy.zeros(shape, dtype=dtype)
1055
+ else:
1056
+ bb = bytes(bytearray(data))
1057
+ array = numpy.frombuffer(bb, dtype=dtype).copy()
1058
+ # Deal with strides
1059
+ if len(shape) == 3:
1060
+ array.shape = shape[2], strides[-1] // shape[0], shape[0]
1061
+ array2 = array[: shape[2], : shape[1], : shape[0]]
1062
+ array = numpy.zeros(shape, dtype=array.dtype)
1063
+ for i in range(shape[0]):
1064
+ array[i] = array2[:, :, i].T
1065
+ else:
1066
+ array.shape = shape[1], strides[-1]
1067
+ array = array[: shape[1], : shape[0]].T
1068
+ return array
1069
+
1070
+ def _finish_wrapped_array(self, array): # IS_PYPY
1071
+ """Hardcore way to inject numpy array in bitmap."""
1072
+ # Get bitmap info
1073
+ with self._fi as lib:
1074
+ pitch = lib.FreeImage_GetPitch(self._bitmap)
1075
+ bits = lib.FreeImage_GetBits(self._bitmap)
1076
+ bpp = lib.FreeImage_GetBPP(self._bitmap)
1077
+ # Get channels and realwidth
1078
+ nchannels = bpp // 8 // array.itemsize
1079
+ realwidth = pitch // nchannels
1080
+ # Apply padding for pitch if necessary
1081
+ extra = realwidth - array.shape[-2]
1082
+ assert 0 <= extra < 10
1083
+ # Make sort of Fortran, also take padding (i.e. pitch) into account
1084
+ newshape = array.shape[-1], realwidth, nchannels
1085
+ array2 = numpy.zeros(newshape, array.dtype)
1086
+ if nchannels == 1:
1087
+ array2[:, : array.shape[-2], 0] = array.T
1088
+ else:
1089
+ for i in range(nchannels):
1090
+ array2[:, : array.shape[-2], i] = array[i, :, :].T
1091
+ # copy data
1092
+ data_ptr = array2.__array_interface__["data"][0]
1093
+ ctypes.memmove(bits, data_ptr, array2.nbytes)
1094
+ del array2
1095
+
1096
+ def _get_type_and_shape(self):
1097
+ bitmap = self._bitmap
1098
+
1099
+ # Get info on bitmap
1100
+ with self._fi as lib:
1101
+ w = lib.FreeImage_GetWidth(bitmap)
1102
+ h = lib.FreeImage_GetHeight(bitmap)
1103
+ self._fi_type = fi_type = lib.FreeImage_GetImageType(bitmap)
1104
+ if not fi_type:
1105
+ raise ValueError("Unknown image pixel type")
1106
+
1107
+ # Determine required props for numpy array
1108
+ bpp = None
1109
+ dtype = FI_TYPES.dtypes[fi_type]
1110
+
1111
+ if fi_type == FI_TYPES.FIT_BITMAP:
1112
+ with self._fi as lib:
1113
+ bpp = lib.FreeImage_GetBPP(bitmap)
1114
+ has_pallette = lib.FreeImage_GetColorsUsed(bitmap)
1115
+ if has_pallette:
1116
+ # Examine the palette. If it is grayscale, we return as such
1117
+ if has_pallette == 256:
1118
+ palette = lib.FreeImage_GetPalette(bitmap)
1119
+ palette = ctypes.c_void_p(palette)
1120
+ p = (ctypes.c_uint8 * (256 * 4)).from_address(palette.value)
1121
+ p = numpy.frombuffer(p, numpy.uint32).copy()
1122
+ if (GREY_PALETTE == p).all():
1123
+ extra_dims = []
1124
+ return numpy.dtype(dtype), extra_dims + [w, h], bpp
1125
+ # Convert bitmap and call this method again
1126
+ newbitmap = lib.FreeImage_ConvertTo32Bits(bitmap)
1127
+ newbitmap = ctypes.c_void_p(newbitmap)
1128
+ self._set_bitmap(newbitmap)
1129
+ return self._get_type_and_shape()
1130
+ elif bpp == 8:
1131
+ extra_dims = []
1132
+ elif bpp == 24:
1133
+ extra_dims = [3]
1134
+ elif bpp == 32:
1135
+ extra_dims = [4]
1136
+ else: # pragma: no cover
1137
+ # raise ValueError('Cannot convert %d BPP bitmap' % bpp)
1138
+ # Convert bitmap and call this method again
1139
+ newbitmap = lib.FreeImage_ConvertTo32Bits(bitmap)
1140
+ newbitmap = ctypes.c_void_p(newbitmap)
1141
+ self._set_bitmap(newbitmap)
1142
+ return self._get_type_and_shape()
1143
+ else:
1144
+ extra_dims = FI_TYPES.extra_dims[fi_type]
1145
+
1146
+ # Return dtype and shape
1147
+ return numpy.dtype(dtype), extra_dims + [w, h], bpp
1148
+
1149
+ def quantize(self, quantizer=0, palettesize=256):
1150
+ """Quantize the bitmap to make it 8-bit (paletted). Returns a new
1151
+ FIBitmap object.
1152
+ Only for 24 bit images.
1153
+ """
1154
+ with self._fi as lib:
1155
+ # New bitmap
1156
+ bitmap = lib.FreeImage_ColorQuantizeEx(
1157
+ self._bitmap, quantizer, palettesize, 0, None
1158
+ )
1159
+ bitmap = ctypes.c_void_p(bitmap)
1160
+
1161
+ # Check and return
1162
+ if not bitmap:
1163
+ raise ValueError(
1164
+ 'Could not quantize bitmap "%s": %s'
1165
+ % (self._filename, self._fi._get_error_message())
1166
+ )
1167
+
1168
+ new = FIBitmap(self._fi, self._filename, self._ftype, self._flags)
1169
+ new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
1170
+ new._fi_type = self._fi_type
1171
+ return new
1172
+
1173
+
1174
+ # def convert_to_32bit(self):
1175
+ # """ Convert to 32bit image.
1176
+ # """
1177
+ # with self._fi as lib:
1178
+ # # New bitmap
1179
+ # bitmap = lib.FreeImage_ConvertTo32Bits(self._bitmap)
1180
+ # bitmap = ctypes.c_void_p(bitmap)
1181
+ #
1182
+ # # Check and return
1183
+ # if not bitmap:
1184
+ # raise ValueError('Could not convert bitmap to 32bit "%s": %s' %
1185
+ # (self._filename,
1186
+ # self._fi._get_error_message()))
1187
+ # else:
1188
+ # new = FIBitmap(self._fi, self._filename, self._ftype,
1189
+ # self._flags)
1190
+ # new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
1191
+ # new._fi_type = self._fi_type
1192
+ # return new
1193
+
1194
+
1195
+ class FIMultipageBitmap(FIBaseBitmap):
1196
+ """Wrapper for the multipage FI bitmap object."""
1197
+
1198
+ def load_from_filename(self, filename=None):
1199
+ if filename is None: # pragma: no cover
1200
+ filename = self._filename
1201
+
1202
+ # Prepare
1203
+ create_new = False
1204
+ read_only = True
1205
+ keep_cache_in_memory = False
1206
+
1207
+ # Try opening
1208
+ with self._fi as lib:
1209
+ # Create bitmap
1210
+ multibitmap = lib.FreeImage_OpenMultiBitmap(
1211
+ self._ftype,
1212
+ efn(filename),
1213
+ create_new,
1214
+ read_only,
1215
+ keep_cache_in_memory,
1216
+ self._flags,
1217
+ )
1218
+ multibitmap = ctypes.c_void_p(multibitmap)
1219
+
1220
+ # Check
1221
+ if not multibitmap: # pragma: no cover
1222
+ err = self._fi._get_error_message()
1223
+ raise ValueError(
1224
+ 'Could not open file "%s" as multi-image: %s'
1225
+ % (self._filename, err)
1226
+ )
1227
+ self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap))
1228
+
1229
+ # def load_from_bytes(self, bb):
1230
+ # with self._fi as lib:
1231
+ # # Create bitmap
1232
+ # fimemory = lib.FreeImage_OpenMemory(
1233
+ # ctypes.c_char_p(bb), len(bb))
1234
+ # multibitmap = lib.FreeImage_LoadMultiBitmapFromMemory(
1235
+ # self._ftype, ctypes.c_void_p(fimemory), self._flags)
1236
+ # multibitmap = ctypes.c_void_p(multibitmap)
1237
+ # #lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
1238
+ # self._mem = fimemory
1239
+ # self._bytes = bb
1240
+ # # Check
1241
+ # if not multibitmap:
1242
+ # raise ValueError('Could not load multibitmap "%s": %s'
1243
+ # % (self._filename, self._fi._get_error_message()))
1244
+ # else:
1245
+ # self._set_bitmap(multibitmap,
1246
+ # (lib.FreeImage_CloseMultiBitmap, multibitmap))
1247
+
1248
+ def save_to_filename(self, filename=None):
1249
+ if filename is None: # pragma: no cover
1250
+ filename = self._filename
1251
+
1252
+ # Prepare
1253
+ create_new = True
1254
+ read_only = False
1255
+ keep_cache_in_memory = False
1256
+
1257
+ # Open the file
1258
+ # todo: Set flags at close func
1259
+ with self._fi as lib:
1260
+ multibitmap = lib.FreeImage_OpenMultiBitmap(
1261
+ self._ftype,
1262
+ efn(filename),
1263
+ create_new,
1264
+ read_only,
1265
+ keep_cache_in_memory,
1266
+ 0,
1267
+ )
1268
+ multibitmap = ctypes.c_void_p(multibitmap)
1269
+
1270
+ # Check
1271
+ if not multibitmap: # pragma: no cover
1272
+ msg = 'Could not open file "%s" for writing multi-image: %s' % (
1273
+ self._filename,
1274
+ self._fi._get_error_message(),
1275
+ )
1276
+ raise ValueError(msg)
1277
+ self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap))
1278
+
1279
+ def __len__(self):
1280
+ with self._fi as lib:
1281
+ return lib.FreeImage_GetPageCount(self._bitmap)
1282
+
1283
+ def get_page(self, index):
1284
+ """Return the sub-bitmap for the given page index.
1285
+ Please close the returned bitmap when done.
1286
+ """
1287
+ with self._fi as lib:
1288
+ # Create low-level bitmap in freeimage
1289
+ bitmap = lib.FreeImage_LockPage(self._bitmap, index)
1290
+ bitmap = ctypes.c_void_p(bitmap)
1291
+ if not bitmap: # pragma: no cover
1292
+ raise ValueError(
1293
+ "Could not open sub-image %i in %r: %s"
1294
+ % (index, self._filename, self._fi._get_error_message())
1295
+ )
1296
+
1297
+ # Get bitmap object to wrap this bitmap
1298
+ bm = FIBitmap(self._fi, self._filename, self._ftype, self._flags)
1299
+ bm._set_bitmap(
1300
+ bitmap, (lib.FreeImage_UnlockPage, self._bitmap, bitmap, False)
1301
+ )
1302
+ return bm
1303
+
1304
+ def append_bitmap(self, bitmap):
1305
+ """Add a sub-bitmap to the multi-page bitmap."""
1306
+ with self._fi as lib:
1307
+ # no return value
1308
+ lib.FreeImage_AppendPage(self._bitmap, bitmap._bitmap)
1309
+
1310
+
1311
+ # Create instance
1312
+ fi = Freeimage()
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/bsdf.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write BSDF files.
5
+
6
+ Backend Library: internal
7
+
8
+ The BSDF format enables reading and writing of image data in the
9
+ BSDF serialization format. This format allows storage of images, volumes,
10
+ and series thereof. Data can be of any numeric data type, and can
11
+ optionally be compressed. Each image/volume can have associated
12
+ meta data, which can consist of any data type supported by BSDF.
13
+
14
+ By default, image data is lazily loaded; the actual image data is
15
+ not read until it is requested. This allows storing multiple images
16
+ in a single file and still have fast access to individual images.
17
+ Alternatively, a series of images can be read in streaming mode, reading
18
+ images as they are read (e.g. from http).
19
+
20
+ BSDF is a simple generic binary format. It is easy to extend and there
21
+ are standard extension definitions for 2D and 3D image data.
22
+ Read more at http://bsdf.io.
23
+
24
+
25
+ Parameters
26
+ ----------
27
+ random_access : bool
28
+ Whether individual images in the file can be read in random order.
29
+ Defaults to True for normal files, and to False when reading from HTTP.
30
+ If False, the file is read in "streaming mode", allowing reading
31
+ files as they are read, but without support for "rewinding".
32
+ Note that setting this to True when reading from HTTP, the whole file
33
+ is read upon opening it (since lazy loading is not possible over HTTP).
34
+
35
+ compression : int
36
+ Use ``0`` or "no" for no compression, ``1`` or "zlib" for Zlib
37
+ compression (same as zip files and PNG), and ``2`` or "bz2" for Bz2
38
+ compression (more compact but slower). Default 1 (zlib).
39
+ Note that some BSDF implementations may not support compression
40
+ (e.g. JavaScript).
41
+
42
+ """
43
+
44
+ import numpy as np
45
+
46
+ from ..core import Format
47
+
48
+
49
+ def get_bsdf_serializer(options):
50
+ from . import _bsdf as bsdf
51
+
52
+ class NDArrayExtension(bsdf.Extension):
53
+ """Copy of BSDF's NDArrayExtension but deal with lazy blobs."""
54
+
55
+ name = "ndarray"
56
+ cls = np.ndarray
57
+
58
+ def encode(self, s, v):
59
+ return dict(shape=v.shape, dtype=str(v.dtype), data=v.tobytes())
60
+
61
+ def decode(self, s, v):
62
+ return v # return as dict, because of lazy blobs, decode in Image
63
+
64
+ class ImageExtension(bsdf.Extension):
65
+ """We implement two extensions that trigger on the Image classes."""
66
+
67
+ def encode(self, s, v):
68
+ return dict(array=v.array, meta=v.meta)
69
+
70
+ def decode(self, s, v):
71
+ return Image(v["array"], v["meta"])
72
+
73
+ class Image2DExtension(ImageExtension):
74
+ name = "image2d"
75
+ cls = Image2D
76
+
77
+ class Image3DExtension(ImageExtension):
78
+ name = "image3d"
79
+ cls = Image3D
80
+
81
+ exts = [NDArrayExtension, Image2DExtension, Image3DExtension]
82
+ serializer = bsdf.BsdfSerializer(exts, **options)
83
+
84
+ return bsdf, serializer
85
+
86
+
87
+ class Image:
88
+ """Class in which we wrap the array and meta data. By using an extension
89
+ we can make BSDF trigger on these classes and thus encode the images.
90
+ as actual images.
91
+ """
92
+
93
+ def __init__(self, array, meta):
94
+ self.array = array
95
+ self.meta = meta
96
+
97
+ def get_array(self):
98
+ if not isinstance(self.array, np.ndarray):
99
+ v = self.array
100
+ blob = v["data"]
101
+ if not isinstance(blob, bytes): # then it's a lazy bsdf.Blob
102
+ blob = blob.get_bytes()
103
+ self.array = np.frombuffer(blob, dtype=v["dtype"])
104
+ self.array.shape = v["shape"]
105
+ return self.array
106
+
107
+ def get_meta(self):
108
+ return self.meta
109
+
110
+
111
+ class Image2D(Image):
112
+ pass
113
+
114
+
115
+ class Image3D(Image):
116
+ pass
117
+
118
+
119
+ class BsdfFormat(Format):
120
+ """The BSDF format enables reading and writing of image data in the
121
+ BSDF serialization format. This format allows storage of images, volumes,
122
+ and series thereof. Data can be of any numeric data type, and can
123
+ optionally be compressed. Each image/volume can have associated
124
+ meta data, which can consist of any data type supported by BSDF.
125
+
126
+ By default, image data is lazily loaded; the actual image data is
127
+ not read until it is requested. This allows storing multiple images
128
+ in a single file and still have fast access to individual images.
129
+ Alternatively, a series of images can be read in streaming mode, reading
130
+ images as they are read (e.g. from http).
131
+
132
+ BSDF is a simple generic binary format. It is easy to extend and there
133
+ are standard extension definitions for 2D and 3D image data.
134
+ Read more at http://bsdf.io.
135
+
136
+ Parameters for reading
137
+ ----------------------
138
+ random_access : bool
139
+ Whether individual images in the file can be read in random order.
140
+ Defaults to True for normal files, and to False when reading from HTTP.
141
+ If False, the file is read in "streaming mode", allowing reading
142
+ files as they are read, but without support for "rewinding".
143
+ Note that setting this to True when reading from HTTP, the whole file
144
+ is read upon opening it (since lazy loading is not possible over HTTP).
145
+
146
+ Parameters for saving
147
+ ---------------------
148
+ compression : {0, 1, 2}
149
+ Use ``0`` or "no" for no compression, ``1`` or "zlib" for Zlib
150
+ compression (same as zip files and PNG), and ``2`` or "bz2" for Bz2
151
+ compression (more compact but slower). Default 1 (zlib).
152
+ Note that some BSDF implementations may not support compression
153
+ (e.g. JavaScript).
154
+
155
+ """
156
+
157
+ def _can_read(self, request):
158
+ if request.mode[1] in (self.modes + "?"):
159
+ # if request.extension in self.extensions:
160
+ # return True
161
+ if request.firstbytes.startswith(b"BSDF"):
162
+ return True
163
+
164
+ def _can_write(self, request):
165
+ if request.mode[1] in (self.modes + "?"):
166
+ if request.extension in self.extensions:
167
+ return True
168
+
169
+ # -- reader
170
+
171
+ class Reader(Format.Reader):
172
+ def _open(self, random_access=None):
173
+ # Validate - we need a BSDF file consisting of a list of images
174
+ # The list is typically a stream, but does not have to be.
175
+ assert self.request.firstbytes[:4] == b"BSDF", "Not a BSDF file"
176
+ # self.request.firstbytes[5:6] == major and minor version
177
+ if not (
178
+ self.request.firstbytes[6:15] == b"M\x07image2D"
179
+ or self.request.firstbytes[6:15] == b"M\x07image3D"
180
+ or self.request.firstbytes[6:7] == b"l"
181
+ ):
182
+ pass # Actually, follow a more duck-type approach ...
183
+ # raise RuntimeError('BSDF file does not look like an '
184
+ # 'image container.')
185
+ # Set options. If we think that seeking is allowed, we lazily load
186
+ # blobs, and set streaming to False (i.e. the whole file is read,
187
+ # but we skip over binary blobs), so that we subsequently allow
188
+ # random access to the images.
189
+ # If seeking is not allowed (e.g. with a http request), we cannot
190
+ # lazily load blobs, but we can still load streaming from the web.
191
+ options = {}
192
+ if self.request.filename.startswith(("http://", "https://")):
193
+ ra = False if random_access is None else bool(random_access)
194
+ options["lazy_blob"] = False # Because we cannot seek now
195
+ options["load_streaming"] = not ra # Load as a stream?
196
+ else:
197
+ ra = True if random_access is None else bool(random_access)
198
+ options["lazy_blob"] = ra # Don't read data until needed
199
+ options["load_streaming"] = not ra
200
+
201
+ file = self.request.get_file()
202
+ bsdf, self._serializer = get_bsdf_serializer(options)
203
+ self._stream = self._serializer.load(file)
204
+ # Another validation
205
+ if (
206
+ isinstance(self._stream, dict)
207
+ and "meta" in self._stream
208
+ and "array" in self._stream
209
+ ):
210
+ self._stream = Image(self._stream["array"], self._stream["meta"])
211
+ if not isinstance(self._stream, (Image, list, bsdf.ListStream)):
212
+ raise RuntimeError(
213
+ "BSDF file does not look seem to have an " "image container."
214
+ )
215
+
216
+ def _close(self):
217
+ pass
218
+
219
+ def _get_length(self):
220
+ if isinstance(self._stream, Image):
221
+ return 1
222
+ elif isinstance(self._stream, list):
223
+ return len(self._stream)
224
+ elif self._stream.count < 0:
225
+ return np.inf
226
+ return self._stream.count
227
+
228
+ def _get_data(self, index):
229
+ # Validate
230
+ if index < 0 or index >= self.get_length():
231
+ raise IndexError(
232
+ "Image index %i not in [0 %i]." % (index, self.get_length())
233
+ )
234
+ # Get Image object
235
+ if isinstance(self._stream, Image):
236
+ image_ob = self._stream # singleton
237
+ elif isinstance(self._stream, list):
238
+ # Easy when we have random access
239
+ image_ob = self._stream[index]
240
+ else:
241
+ # For streaming, we need to skip over frames
242
+ if index < self._stream.index:
243
+ raise IndexError(
244
+ "BSDF file is being read in streaming "
245
+ "mode, thus does not allow rewinding."
246
+ )
247
+ while index > self._stream.index:
248
+ self._stream.next()
249
+ image_ob = self._stream.next() # Can raise StopIteration
250
+ # Is this an image?
251
+ if (
252
+ isinstance(image_ob, dict)
253
+ and "meta" in image_ob
254
+ and "array" in image_ob
255
+ ):
256
+ image_ob = Image(image_ob["array"], image_ob["meta"])
257
+ if isinstance(image_ob, Image):
258
+ # Return as array (if we have lazy blobs, they are read now)
259
+ return image_ob.get_array(), image_ob.get_meta()
260
+ else:
261
+ r = repr(image_ob)
262
+ r = r if len(r) < 200 else r[:197] + "..."
263
+ raise RuntimeError("BSDF file contains non-image " + r)
264
+
265
+ def _get_meta_data(self, index): # pragma: no cover
266
+ return {} # This format does not support global meta data
267
+
268
+ # -- writer
269
+
270
+ class Writer(Format.Writer):
271
+ def _open(self, compression=1):
272
+ options = {"compression": compression}
273
+ bsdf, self._serializer = get_bsdf_serializer(options)
274
+ if self.request.mode[1] in "iv":
275
+ self._stream = None # Singleton image
276
+ self._written = False
277
+ else:
278
+ # Series (stream) of images
279
+ file = self.request.get_file()
280
+ self._stream = bsdf.ListStream()
281
+ self._serializer.save(file, self._stream)
282
+
283
+ def _close(self):
284
+ # We close the stream here, which will mark the number of written
285
+ # elements. If we would not close it, the file would be fine, it's
286
+ # just that upon reading it would not be known how many items are
287
+ # in there.
288
+ if self._stream is not None:
289
+ self._stream.close(False) # False says "keep this a stream"
290
+
291
+ def _append_data(self, im, meta):
292
+ # Determine dimension
293
+ ndim = None
294
+ if self.request.mode[1] in "iI":
295
+ ndim = 2
296
+ elif self.request.mode[1] in "vV":
297
+ ndim = 3
298
+ else:
299
+ ndim = 3 # Make an educated guess
300
+ if im.ndim == 2 or (im.ndim == 3 and im.shape[-1] <= 4):
301
+ ndim = 2
302
+ # Validate shape
303
+ assert ndim in (2, 3)
304
+ if ndim == 2:
305
+ assert im.ndim == 2 or (im.ndim == 3 and im.shape[-1] <= 4)
306
+ else:
307
+ assert im.ndim == 3 or (im.ndim == 4 and im.shape[-1] <= 4)
308
+ # Wrap data and meta data in our special class that will trigger
309
+ # the BSDF image2D or image3D extension.
310
+ if ndim == 2:
311
+ ob = Image2D(im, meta)
312
+ else:
313
+ ob = Image3D(im, meta)
314
+ # Write directly or to stream
315
+ if self._stream is None:
316
+ assert not self._written, "Cannot write singleton image twice"
317
+ self._written = True
318
+ file = self.request.get_file()
319
+ self._serializer.save(file, ob)
320
+ else:
321
+ self._stream.append(ob)
322
+
323
+ def set_meta_data(self, meta): # pragma: no cover
324
+ raise RuntimeError("The BSDF format only supports " "per-image meta data.")
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/dicom.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read DICOM files.
5
+
6
+ Backend Library: internal
7
+
8
+ A format for reading DICOM images: a common format used to store
9
+ medical image data, such as X-ray, CT and MRI.
10
+
11
+ This format borrows some code (and ideas) from the pydicom project. However,
12
+ only a predefined subset of tags are extracted from the file. This allows
13
+ for great simplifications allowing us to make a stand-alone reader, and
14
+ also results in a much faster read time.
15
+
16
+ By default, only uncompressed and deflated transfer syntaxes are supported.
17
+ If gdcm or dcmtk is installed, these will be used to automatically convert
18
+ the data. See https://github.com/malaterre/GDCM/releases for installing GDCM.
19
+
20
+ This format provides functionality to group images of the same
21
+ series together, thus extracting volumes (and multiple volumes).
22
+ Using volread will attempt to yield a volume. If multiple volumes
23
+ are present, the first one is given. Using mimread will simply yield
24
+ all images in the given directory (not taking series into account).
25
+
26
+ Parameters
27
+ ----------
28
+ progress : {True, False, BaseProgressIndicator}
29
+ Whether to show progress when reading from multiple files.
30
+ Default True. By passing an object that inherits from
31
+ BaseProgressIndicator, the way in which progress is reported
32
+ can be costumized.
33
+
34
+ """
35
+
36
+ # todo: Use pydicom:
37
+ # * Note: is not py3k ready yet
38
+ # * Allow reading the full meta info
39
+ # I think we can more or less replace the SimpleDicomReader with a
40
+ # pydicom.Dataset For series, only ned to read the full info from one
41
+ # file: speed still high
42
+ # * Perhaps allow writing?
43
+
44
+ import os
45
+ import sys
46
+ import logging
47
+ import subprocess
48
+
49
+ from ..core import Format, BaseProgressIndicator, StdoutProgressIndicator
50
+ from ..core import read_n_bytes
51
+
52
+ _dicom = None # lazily loaded in load_lib()
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ def load_lib():
58
+ global _dicom
59
+ from . import _dicom
60
+
61
+ return _dicom
62
+
63
+
64
+ # Determine endianity of system
65
+ sys_is_little_endian = sys.byteorder == "little"
66
+
67
+
68
+ def get_dcmdjpeg_exe():
69
+ fname = "dcmdjpeg" + ".exe" * sys.platform.startswith("win")
70
+ for dir in (
71
+ "c:\\dcmtk",
72
+ "c:\\Program Files",
73
+ "c:\\Program Files\\dcmtk",
74
+ "c:\\Program Files (x86)\\dcmtk",
75
+ ):
76
+ filename = os.path.join(dir, fname)
77
+ if os.path.isfile(filename):
78
+ return [filename]
79
+
80
+ try:
81
+ subprocess.check_call([fname, "--version"])
82
+ return [fname]
83
+ except Exception:
84
+ return None
85
+
86
+
87
+ def get_gdcmconv_exe():
88
+ fname = "gdcmconv" + ".exe" * sys.platform.startswith("win")
89
+ # Maybe it's on the path
90
+ try:
91
+ subprocess.check_call([fname, "--version"])
92
+ return [fname, "--raw"]
93
+ except Exception:
94
+ pass
95
+ # Select directories where it could be
96
+ candidates = []
97
+ base_dirs = [r"c:\Program Files"]
98
+ for base_dir in base_dirs:
99
+ if os.path.isdir(base_dir):
100
+ for dname in os.listdir(base_dir):
101
+ if dname.lower().startswith("gdcm"):
102
+ suffix = dname[4:].strip()
103
+ candidates.append((suffix, os.path.join(base_dir, dname)))
104
+ # Sort, so higher versions are tried earlier
105
+ candidates.sort(reverse=True)
106
+ # Select executable
107
+ filename = None
108
+ for _, dirname in candidates:
109
+ exe1 = os.path.join(dirname, "gdcmconv.exe")
110
+ exe2 = os.path.join(dirname, "bin", "gdcmconv.exe")
111
+ if os.path.isfile(exe1):
112
+ filename = exe1
113
+ break
114
+ if os.path.isfile(exe2):
115
+ filename = exe2
116
+ break
117
+ else:
118
+ return None
119
+ return [filename, "--raw"]
120
+
121
+
122
+ class DicomFormat(Format):
123
+ """See :mod:`imageio.plugins.dicom`"""
124
+
125
+ def _can_read(self, request):
126
+ # If user URI was a directory, we check whether it has a DICOM file
127
+ if os.path.isdir(request.filename):
128
+ files = os.listdir(request.filename)
129
+ for fname in sorted(files): # Sorting make it consistent
130
+ filename = os.path.join(request.filename, fname)
131
+ if os.path.isfile(filename) and "DICOMDIR" not in fname:
132
+ with open(filename, "rb") as f:
133
+ first_bytes = read_n_bytes(f, 140)
134
+ return first_bytes[128:132] == b"DICM"
135
+ else:
136
+ return False
137
+ # Check
138
+ return request.firstbytes[128:132] == b"DICM"
139
+
140
+ def _can_write(self, request):
141
+ # We cannot save yet. May be possible if we will used pydicom as
142
+ # a backend.
143
+ return False
144
+
145
+ # --
146
+
147
+ class Reader(Format.Reader):
148
+ _compressed_warning_dirs = set()
149
+
150
+ def _open(self, progress=True):
151
+ if not _dicom:
152
+ load_lib()
153
+ if os.path.isdir(self.request.filename):
154
+ # A dir can be given if the user used the format explicitly
155
+ self._info = {}
156
+ self._data = None
157
+ else:
158
+ # Read the given dataset now ...
159
+ try:
160
+ dcm = _dicom.SimpleDicomReader(self.request.get_file())
161
+ except _dicom.CompressedDicom as err:
162
+ # We cannot do this on our own. Perhaps with some help ...
163
+ cmd = get_gdcmconv_exe()
164
+ if not cmd and "JPEG" in str(err):
165
+ cmd = get_dcmdjpeg_exe()
166
+ if not cmd:
167
+ msg = err.args[0].replace("using", "installing")
168
+ msg = msg.replace("convert", "auto-convert")
169
+ err.args = (msg,)
170
+ raise
171
+ else:
172
+ fname1 = self.request.get_local_filename()
173
+ fname2 = fname1 + ".raw"
174
+ try:
175
+ subprocess.check_call(cmd + [fname1, fname2])
176
+ except Exception:
177
+ raise err
178
+ d = os.path.dirname(fname1)
179
+ if d not in self._compressed_warning_dirs:
180
+ self._compressed_warning_dirs.add(d)
181
+ logger.warning(
182
+ "DICOM file contained compressed data. "
183
+ + "Autoconverting with "
184
+ + cmd[0]
185
+ + " (this warning is shown once for each directory)"
186
+ )
187
+ dcm = _dicom.SimpleDicomReader(fname2)
188
+
189
+ self._info = dcm._info
190
+ self._data = dcm.get_numpy_array()
191
+
192
+ # Initialize series, list of DicomSeries objects
193
+ self._series = None # only created if needed
194
+
195
+ # Set progress indicator
196
+ if isinstance(progress, BaseProgressIndicator):
197
+ self._progressIndicator = progress
198
+ elif progress is True:
199
+ p = StdoutProgressIndicator("Reading DICOM")
200
+ self._progressIndicator = p
201
+ elif progress in (None, False):
202
+ self._progressIndicator = BaseProgressIndicator("Dummy")
203
+ else:
204
+ raise ValueError("Invalid value for progress.")
205
+
206
+ def _close(self):
207
+ # Clean up
208
+ self._info = None
209
+ self._data = None
210
+ self._series = None
211
+
212
+ @property
213
+ def series(self):
214
+ if self._series is None:
215
+ pi = self._progressIndicator
216
+ self._series = _dicom.process_directory(self.request, pi)
217
+ return self._series
218
+
219
+ def _get_length(self):
220
+ if self._data is None:
221
+ dcm = self.series[0][0]
222
+ self._info = dcm._info
223
+ self._data = dcm.get_numpy_array()
224
+
225
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
226
+
227
+ if self.request.mode[1] == "i":
228
+ # User expects one, but lets be honest about this file
229
+ return nslices
230
+ elif self.request.mode[1] == "I":
231
+ # User expects multiple, if this file has multiple slices, ok.
232
+ # Otherwise we have to check the series.
233
+ if nslices > 1:
234
+ return nslices
235
+ else:
236
+ return sum([len(serie) for serie in self.series])
237
+ elif self.request.mode[1] == "v":
238
+ # User expects a volume, if this file has one, ok.
239
+ # Otherwise we have to check the series
240
+ if nslices > 1:
241
+ return 1
242
+ else:
243
+ return len(self.series) # We assume one volume per series
244
+ elif self.request.mode[1] == "V":
245
+ # User expects multiple volumes. We have to check the series
246
+ return len(self.series) # We assume one volume per series
247
+ else:
248
+ raise RuntimeError("DICOM plugin should know what to expect.")
249
+
250
+ def _get_slice_data(self, index):
251
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
252
+
253
+ # Allow index >1 only if this file contains >1
254
+ if nslices > 1:
255
+ return self._data[index], self._info
256
+ elif index == 0:
257
+ return self._data, self._info
258
+ else:
259
+ raise IndexError("Dicom file contains only one slice.")
260
+
261
+ def _get_data(self, index):
262
+ if self._data is None:
263
+ dcm = self.series[0][0]
264
+ self._info = dcm._info
265
+ self._data = dcm.get_numpy_array()
266
+
267
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
268
+
269
+ if self.request.mode[1] == "i":
270
+ return self._get_slice_data(index)
271
+ elif self.request.mode[1] == "I":
272
+ # Return slice from volume, or return item from series
273
+ if index == 0 and nslices > 1:
274
+ return self._data[index], self._info
275
+ else:
276
+ L = []
277
+ for serie in self.series:
278
+ L.extend([dcm_ for dcm_ in serie])
279
+ return L[index].get_numpy_array(), L[index].info
280
+ elif self.request.mode[1] in "vV":
281
+ # Return volume or series
282
+ if index == 0 and nslices > 1:
283
+ return self._data, self._info
284
+ else:
285
+ return (
286
+ self.series[index].get_numpy_array(),
287
+ self.series[index].info,
288
+ )
289
+ # mode is `?` (typically because we are using V3). If there is a
290
+ # series (multiple files), index referrs to the element of the
291
+ # series and we read volumes. If there is no series, index
292
+ # referrs to the slice in the volume we read "flat" images.
293
+ elif len(self.series) > 1:
294
+ # mode is `?` and there are multiple series. Each series is a ndimage.
295
+ return (
296
+ self.series[index].get_numpy_array(),
297
+ self.series[index].info,
298
+ )
299
+ else:
300
+ # mode is `?` and there is only one series. Each slice is an ndimage.
301
+ return self._get_slice_data(index)
302
+
303
+ def _get_meta_data(self, index):
304
+ if self._data is None:
305
+ dcm = self.series[0][0]
306
+ self._info = dcm._info
307
+ self._data = dcm.get_numpy_array()
308
+
309
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
310
+
311
+ # Default is the meta data of the given file, or the "first" file.
312
+ if index is None:
313
+ return self._info
314
+
315
+ if self.request.mode[1] == "i":
316
+ return self._info
317
+ elif self.request.mode[1] == "I":
318
+ # Return slice from volume, or return item from series
319
+ if index == 0 and nslices > 1:
320
+ return self._info
321
+ else:
322
+ L = []
323
+ for serie in self.series:
324
+ L.extend([dcm_ for dcm_ in serie])
325
+ return L[index].info
326
+ elif self.request.mode[1] in "vV":
327
+ # Return volume or series
328
+ if index == 0 and nslices > 1:
329
+ return self._info
330
+ else:
331
+ return self.series[index].info
332
+ else: # pragma: no cover
333
+ raise ValueError("DICOM plugin should know what to expect.")
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/fits.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read FITS files.
5
+
6
+ Backend Library: `Astropy <https://www.astropy.org/>`_
7
+
8
+ .. note::
9
+ To use this plugin you have to install its backend::
10
+
11
+ pip install imageio[fits]
12
+
13
+ Flexible Image Transport System (FITS) is an open standard defining a
14
+ digital file format useful for storage, transmission and processing of
15
+ scientific and other images. FITS is the most commonly used digital
16
+ file format in astronomy.
17
+
18
+
19
+ Parameters
20
+ ----------
21
+ cache : bool
22
+ If the file name is a URL, `~astropy.utils.data.download_file` is used
23
+ to open the file. This specifies whether or not to save the file
24
+ locally in Astropy's download cache (default: `True`).
25
+ uint : bool
26
+ Interpret signed integer data where ``BZERO`` is the
27
+ central value and ``BSCALE == 1`` as unsigned integer
28
+ data. For example, ``int16`` data with ``BZERO = 32768``
29
+ and ``BSCALE = 1`` would be treated as ``uint16`` data.
30
+
31
+ Note, for backward compatibility, the kwarg **uint16** may
32
+ be used instead. The kwarg was renamed when support was
33
+ added for integers of any size.
34
+ ignore_missing_end : bool
35
+ Do not issue an exception when opening a file that is
36
+ missing an ``END`` card in the last header.
37
+ checksum : bool or str
38
+ If `True`, verifies that both ``DATASUM`` and
39
+ ``CHECKSUM`` card values (when present in the HDU header)
40
+ match the header and data of all HDU's in the file. Updates to a
41
+ file that already has a checksum will preserve and update the
42
+ existing checksums unless this argument is given a value of
43
+ 'remove', in which case the CHECKSUM and DATASUM values are not
44
+ checked, and are removed when saving changes to the file.
45
+ disable_image_compression : bool, optional
46
+ If `True`, treats compressed image HDU's like normal
47
+ binary table HDU's.
48
+ do_not_scale_image_data : bool
49
+ If `True`, image data is not scaled using BSCALE/BZERO values
50
+ when read.
51
+ ignore_blank : bool
52
+ If `True`, the BLANK keyword is ignored if present.
53
+ scale_back : bool
54
+ If `True`, when saving changes to a file that contained scaled
55
+ image data, restore the data to the original type and reapply the
56
+ original BSCALE/BZERO values. This could lead to loss of accuracy
57
+ if scaling back to integer values after performing floating point
58
+ operations on the data.
59
+
60
+ """
61
+
62
+ from ..core import Format
63
+
64
+ _fits = None # lazily loaded
65
+
66
+
67
+ def load_lib():
68
+ global _fits
69
+ try:
70
+ from astropy.io import fits as _fits
71
+ except ImportError:
72
+ raise ImportError(
73
+ "The FITS format relies on the astropy package."
74
+ "Please refer to http://www.astropy.org/ "
75
+ "for further instructions."
76
+ )
77
+ return _fits
78
+
79
+
80
+ class FitsFormat(Format):
81
+ """See :mod:`imageio.plugins.fits`"""
82
+
83
+ def _can_read(self, request):
84
+ # We return True if ext matches, because this is the only plugin
85
+ # that can. If astropy is not installed, a useful error follows.
86
+ return request.extension in self.extensions
87
+
88
+ def _can_write(self, request):
89
+ # No write support
90
+ return False
91
+
92
+ # -- reader
93
+
94
+ class Reader(Format.Reader):
95
+ def _open(self, cache=False, **kwargs):
96
+ if not _fits:
97
+ load_lib()
98
+ hdulist = _fits.open(self.request.get_file(), cache=cache, **kwargs)
99
+
100
+ self._index = []
101
+ allowed_hdu_types = (_fits.ImageHDU, _fits.PrimaryHDU, _fits.CompImageHDU)
102
+ for n, hdu in zip(range(len(hdulist)), hdulist):
103
+ if isinstance(hdu, allowed_hdu_types):
104
+ # Ignore (primary) header units with no data (use '.size'
105
+ # rather than '.data' to avoid actually loading the image):
106
+ if hdu.size > 0:
107
+ self._index.append(n)
108
+ self._hdulist = hdulist
109
+
110
+ def _close(self):
111
+ self._hdulist.close()
112
+
113
+ def _get_length(self):
114
+ return len(self._index)
115
+
116
+ def _get_data(self, index):
117
+ # Get data
118
+ if index < 0 or index >= len(self._index):
119
+ raise IndexError("Index out of range while reading from fits")
120
+ im = self._hdulist[self._index[index]].data
121
+ # Return array and empty meta data
122
+ return im, {}
123
+
124
+ def _get_meta_data(self, index):
125
+ # Get the meta data for the given index
126
+ raise RuntimeError("The fits format does not support meta data.")
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/npz.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read/Write NPZ files.
5
+
6
+ Backend: `Numpy <https://numpy.org/doc/stable/reference/generated/numpy.savez.html>`_
7
+
8
+ NPZ is a file format by numpy that provides storage of array data using gzip
9
+ compression. This imageio plugin supports data of any shape, and also supports
10
+ multiple images per file. However, the npz format does not provide streaming;
11
+ all data is read/written at once. Further, there is no support for meta data.
12
+
13
+ See the BSDF format for a similar (but more fully featured) format.
14
+
15
+ Parameters
16
+ ----------
17
+ None
18
+
19
+ Notes
20
+ -----
21
+ This format is not available on Pypy.
22
+
23
+ """
24
+
25
+ import numpy as np
26
+
27
+ from ..core import Format
28
+
29
+
30
+ class NpzFormat(Format):
31
+ """See :mod:`imageio.plugins.npz`"""
32
+
33
+ def _can_read(self, request):
34
+ # We support any kind of image data
35
+ return request.extension in self.extensions
36
+
37
+ def _can_write(self, request):
38
+ # We support any kind of image data
39
+ return request.extension in self.extensions
40
+
41
+ # -- reader
42
+
43
+ class Reader(Format.Reader):
44
+ def _open(self):
45
+ # Load npz file, which provides another file like object
46
+ self._npz = np.load(self.request.get_file())
47
+ assert isinstance(self._npz, np.lib.npyio.NpzFile)
48
+ # Get list of names, ordered by name, but smarter
49
+ self._names = sorted(self._npz.files, key=lambda x: x.split("_")[-1])
50
+
51
+ def _close(self):
52
+ self._npz.close()
53
+
54
+ def _get_length(self):
55
+ return len(self._names)
56
+
57
+ def _get_data(self, index):
58
+ # Get data
59
+ if index < 0 or index >= len(self._names):
60
+ raise IndexError("Index out of range while reading from nzp")
61
+ im = self._npz[self._names[index]]
62
+ # Return array and empty meta data
63
+ return im, {}
64
+
65
+ def _get_meta_data(self, index):
66
+ # Get the meta data for the given index
67
+ raise RuntimeError("The npz format does not support meta data.")
68
+
69
+ # -- writer
70
+
71
+ class Writer(Format.Writer):
72
+ def _open(self):
73
+ # Npz is not such a great format. We cannot stream to the file.
74
+ # So we remember all images and write them to file at the end.
75
+ self._images = []
76
+
77
+ def _close(self):
78
+ # Write everything
79
+ np.savez_compressed(self.request.get_file(), *self._images)
80
+
81
+ def _append_data(self, im, meta):
82
+ self._images.append(im) # discart meta data
83
+
84
+ def set_meta_data(self, meta):
85
+ raise RuntimeError("The npz format does not support meta data.")
evalkit_tf446/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_tf446/lib/python3.10/site-packages/imageio/plugins/pillowmulti.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PIL formats for multiple images.
3
+ """
4
+
5
+ import logging
6
+
7
+ import numpy as np
8
+
9
+ from .pillow_legacy import PillowFormat, image_as_uint, ndarray_to_pil
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ NeuQuant = None # we can implement this when we need it
14
+
15
+
16
+ class TIFFFormat(PillowFormat):
17
+ _modes = "i" # arg, why bother; people should use the tiffile version
18
+ _description = "TIFF format (Pillow)"
19
+
20
+
21
+ class GIFFormat(PillowFormat):
22
+ """See :mod:`imageio.plugins.pillow_legacy`"""
23
+
24
+ _modes = "iI"
25
+ _description = "Static and animated gif (Pillow)"
26
+
27
+ # GIF reader needs no modifications compared to base pillow reader
28
+
29
+ class Writer(PillowFormat.Writer): # pragma: no cover
30
+ def _open(
31
+ self,
32
+ loop=0,
33
+ duration=None,
34
+ fps=10,
35
+ palettesize=256,
36
+ quantizer=0,
37
+ subrectangles=False,
38
+ ):
39
+ from PIL import __version__ as pillow_version
40
+
41
+ major, minor, patch = tuple(int(x) for x in pillow_version.split("."))
42
+ if major == 10 and minor >= 1:
43
+ raise ImportError(
44
+ f"Pillow v{pillow_version} is not supported by ImageIO's legacy "
45
+ "pillow plugin when writing GIFs. Consider switching to the new "
46
+ "plugin or downgrading to `pillow<10.1.0`."
47
+ )
48
+
49
+ # Check palettesize
50
+ palettesize = int(palettesize)
51
+ if palettesize < 2 or palettesize > 256:
52
+ raise ValueError("GIF quantize param must be 2..256")
53
+ if palettesize not in [2, 4, 8, 16, 32, 64, 128, 256]:
54
+ palettesize = 2 ** int(np.log2(128) + 0.999)
55
+ logger.warning(
56
+ "Warning: palettesize (%r) modified to a factor of "
57
+ "two between 2-256." % palettesize
58
+ )
59
+ # Duratrion / fps
60
+ if duration is None:
61
+ self._duration = 1.0 / float(fps)
62
+ elif isinstance(duration, (list, tuple)):
63
+ self._duration = [float(d) for d in duration]
64
+ else:
65
+ self._duration = float(duration)
66
+ # loop
67
+ loop = float(loop)
68
+ if loop <= 0 or loop == float("inf"):
69
+ loop = 0
70
+ loop = int(loop)
71
+ # Subrectangles / dispose
72
+ subrectangles = bool(subrectangles)
73
+ self._dispose = 1 if subrectangles else 2
74
+ # The "0" (median cut) quantizer is by far the best
75
+
76
+ fp = self.request.get_file()
77
+ self._writer = GifWriter(
78
+ fp, subrectangles, loop, quantizer, int(palettesize)
79
+ )
80
+
81
+ def _close(self):
82
+ self._writer.close()
83
+
84
+ def _append_data(self, im, meta):
85
+ im = image_as_uint(im, bitdepth=8)
86
+ if im.ndim == 3 and im.shape[-1] == 1:
87
+ im = im[:, :, 0]
88
+ duration = self._duration
89
+ if isinstance(duration, list):
90
+ duration = duration[min(len(duration) - 1, self._writer._count)]
91
+ dispose = self._dispose
92
+ self._writer.add_image(im, duration, dispose)
93
+
94
+ return
95
+
96
+
97
+ def intToBin(i):
98
+ return i.to_bytes(2, byteorder="little")
99
+
100
+
101
+ class GifWriter: # pragma: no cover
102
+ """Class that for helping write the animated GIF file. This is based on
103
+ code from images2gif.py (part of visvis). The version here is modified
104
+ to allow streamed writing.
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ file,
110
+ opt_subrectangle=True,
111
+ opt_loop=0,
112
+ opt_quantizer=0,
113
+ opt_palette_size=256,
114
+ ):
115
+ self.fp = file
116
+
117
+ self.opt_subrectangle = opt_subrectangle
118
+ self.opt_loop = opt_loop
119
+ self.opt_quantizer = opt_quantizer
120
+ self.opt_palette_size = opt_palette_size
121
+
122
+ self._previous_image = None # as np array
123
+ self._global_palette = None # as bytes
124
+ self._count = 0
125
+
126
+ from PIL.GifImagePlugin import getdata
127
+
128
+ self.getdata = getdata
129
+
130
+ def add_image(self, im, duration, dispose):
131
+ # Prepare image
132
+ im_rect, rect = im, (0, 0)
133
+ if self.opt_subrectangle:
134
+ im_rect, rect = self.getSubRectangle(im)
135
+ im_pil = self.converToPIL(im_rect, self.opt_quantizer, self.opt_palette_size)
136
+
137
+ # Get pallette - apparently, this is the 3d element of the header
138
+ # (but it has not always been). Best we've got. Its not the same
139
+ # as im_pil.palette.tobytes().
140
+ from PIL.GifImagePlugin import getheader
141
+
142
+ palette = getheader(im_pil)[0][3]
143
+
144
+ # Write image
145
+ if self._count == 0:
146
+ self.write_header(im_pil, palette, self.opt_loop)
147
+ self._global_palette = palette
148
+ self.write_image(im_pil, palette, rect, duration, dispose)
149
+ # assert len(palette) == len(self._global_palette)
150
+
151
+ # Bookkeeping
152
+ self._previous_image = im
153
+ self._count += 1
154
+
155
+ def write_header(self, im, globalPalette, loop):
156
+ # Gather info
157
+ header = self.getheaderAnim(im)
158
+ appext = self.getAppExt(loop)
159
+ # Write
160
+ self.fp.write(header)
161
+ self.fp.write(globalPalette)
162
+ self.fp.write(appext)
163
+
164
+ def close(self):
165
+ self.fp.write(";".encode("utf-8")) # end gif
166
+
167
+ def write_image(self, im, palette, rect, duration, dispose):
168
+ fp = self.fp
169
+
170
+ # Gather local image header and data, using PIL's getdata. That
171
+ # function returns a list of bytes objects, but which parts are
172
+ # what has changed multiple times, so we put together the first
173
+ # parts until we have enough to form the image header.
174
+ data = self.getdata(im)
175
+ imdes = b""
176
+ while data and len(imdes) < 11:
177
+ imdes += data.pop(0)
178
+ assert len(imdes) == 11
179
+
180
+ # Make image descriptor suitable for using 256 local color palette
181
+ lid = self.getImageDescriptor(im, rect)
182
+ graphext = self.getGraphicsControlExt(duration, dispose)
183
+
184
+ # Write local header
185
+ if (palette != self._global_palette) or (dispose != 2):
186
+ # Use local color palette
187
+ fp.write(graphext)
188
+ fp.write(lid) # write suitable image descriptor
189
+ fp.write(palette) # write local color table
190
+ fp.write(b"\x08") # LZW minimum size code
191
+ else:
192
+ # Use global color palette
193
+ fp.write(graphext)
194
+ fp.write(imdes) # write suitable image descriptor
195
+
196
+ # Write image data
197
+ for d in data:
198
+ fp.write(d)
199
+
200
+ def getheaderAnim(self, im):
201
+ """Get animation header. To replace PILs getheader()[0]"""
202
+ bb = b"GIF89a"
203
+ bb += intToBin(im.size[0])
204
+ bb += intToBin(im.size[1])
205
+ bb += b"\x87\x00\x00"
206
+ return bb
207
+
208
+ def getImageDescriptor(self, im, xy=None):
209
+ """Used for the local color table properties per image.
210
+ Otherwise global color table applies to all frames irrespective of
211
+ whether additional colors comes in play that require a redefined
212
+ palette. Still a maximum of 256 color per frame, obviously.
213
+
214
+ Written by Ant1 on 2010-08-22
215
+ Modified by Alex Robinson in Janurari 2011 to implement subrectangles.
216
+ """
217
+
218
+ # Defaule use full image and place at upper left
219
+ if xy is None:
220
+ xy = (0, 0)
221
+
222
+ # Image separator,
223
+ bb = b"\x2C"
224
+
225
+ # Image position and size
226
+ bb += intToBin(xy[0]) # Left position
227
+ bb += intToBin(xy[1]) # Top position
228
+ bb += intToBin(im.size[0]) # image width
229
+ bb += intToBin(im.size[1]) # image height
230
+
231
+ # packed field: local color table flag1, interlace0, sorted table0,
232
+ # reserved00, lct size111=7=2^(7 + 1)=256.
233
+ bb += b"\x87"
234
+
235
+ # LZW minimum size code now comes later, begining of [imagedata] blocks
236
+ return bb
237
+
238
+ def getAppExt(self, loop):
239
+ """Application extension. This part specifies the amount of loops.
240
+ If loop is 0 or inf, it goes on infinitely.
241
+ """
242
+ if loop == 1:
243
+ return b""
244
+ if loop == 0:
245
+ loop = 2**16 - 1
246
+ bb = b""
247
+ if loop != 0: # omit the extension if we would like a nonlooping gif
248
+ bb = b"\x21\xFF\x0B" # application extension
249
+ bb += b"NETSCAPE2.0"
250
+ bb += b"\x03\x01"
251
+ bb += intToBin(loop)
252
+ bb += b"\x00" # end
253
+ return bb
254
+
255
+ def getGraphicsControlExt(self, duration=0.1, dispose=2):
256
+ """Graphics Control Extension. A sort of header at the start of
257
+ each image. Specifies duration and transparancy.
258
+
259
+ Dispose
260
+ -------
261
+ * 0 - No disposal specified.
262
+ * 1 - Do not dispose. The graphic is to be left in place.
263
+ * 2 - Restore to background color. The area used by the graphic
264
+ must be restored to the background color.
265
+ * 3 - Restore to previous. The decoder is required to restore the
266
+ area overwritten by the graphic with what was there prior to
267
+ rendering the graphic.
268
+ * 4-7 -To be defined.
269
+ """
270
+
271
+ bb = b"\x21\xF9\x04"
272
+ bb += chr((dispose & 3) << 2).encode("utf-8")
273
+ # low bit 1 == transparency,
274
+ # 2nd bit 1 == user input , next 3 bits, the low two of which are used,
275
+ # are dispose.
276
+ bb += intToBin(int(duration * 100 + 0.5)) # in 100th of seconds
277
+ bb += b"\x00" # no transparant color
278
+ bb += b"\x00" # end
279
+ return bb
280
+
281
+ def getSubRectangle(self, im):
282
+ """Calculate the minimal rectangle that need updating. Returns
283
+ a two-element tuple containing the cropped image and an x-y tuple.
284
+
285
+ Calculating the subrectangles takes extra time, obviously. However,
286
+ if the image sizes were reduced, the actual writing of the GIF
287
+ goes faster. In some cases applying this method produces a GIF faster.
288
+ """
289
+
290
+ # Cannot do subrectangle for first image
291
+ if self._count == 0:
292
+ return im, (0, 0)
293
+
294
+ prev = self._previous_image
295
+
296
+ # Get difference, sum over colors
297
+ diff = np.abs(im - prev)
298
+ if diff.ndim == 3:
299
+ diff = diff.sum(2)
300
+ # Get begin and end for both dimensions
301
+ X = np.argwhere(diff.sum(0))
302
+ Y = np.argwhere(diff.sum(1))
303
+ # Get rect coordinates
304
+ if X.size and Y.size:
305
+ x0, x1 = int(X[0]), int(X[-1] + 1)
306
+ y0, y1 = int(Y[0]), int(Y[-1] + 1)
307
+ else: # No change ... make it minimal
308
+ x0, x1 = 0, 2
309
+ y0, y1 = 0, 2
310
+
311
+ return im[y0:y1, x0:x1], (x0, y0)
312
+
313
+ def converToPIL(self, im, quantizer, palette_size=256):
314
+ """Convert image to Paletted PIL image.
315
+
316
+ PIL used to not do a very good job at quantization, but I guess
317
+ this has improved a lot (at least in Pillow). I don't think we need
318
+ neuqant (and we can add it later if we really want).
319
+ """
320
+
321
+ im_pil = ndarray_to_pil(im, "gif")
322
+
323
+ if quantizer in ("nq", "neuquant"):
324
+ # NeuQuant algorithm
325
+ nq_samplefac = 10 # 10 seems good in general
326
+ im_pil = im_pil.convert("RGBA") # NQ assumes RGBA
327
+ nqInstance = NeuQuant(im_pil, nq_samplefac) # Learn colors
328
+ im_pil = nqInstance.quantize(im_pil, colors=palette_size)
329
+ elif quantizer in (0, 1, 2):
330
+ # Adaptive PIL algorithm
331
+ if quantizer == 2:
332
+ im_pil = im_pil.convert("RGBA")
333
+ else:
334
+ im_pil = im_pil.convert("RGB")
335
+ im_pil = im_pil.quantize(colors=palette_size, method=quantizer)
336
+ else:
337
+ raise ValueError("Invalid value for quantizer: %r" % quantizer)
338
+ return im_pil
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/pyav.py ADDED
@@ -0,0 +1,1199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read/Write Videos (and images) using PyAV.
2
+
3
+ .. note::
4
+ To use this plugin you need to have `PyAV <https://pyav.org/docs/stable/>`_
5
+ installed::
6
+
7
+ pip install av
8
+
9
+ This plugin wraps pyAV, a pythonic binding for the FFMPEG library. It is similar
10
+ to our FFMPEG plugin, has improved performance, features a robust interface, and
11
+ aims to supersede the FFMPEG plugin in the future.
12
+
13
+
14
+ Methods
15
+ -------
16
+ .. note::
17
+ Check the respective function for a list of supported kwargs and detailed
18
+ documentation.
19
+
20
+ .. autosummary::
21
+ :toctree:
22
+
23
+ PyAVPlugin.read
24
+ PyAVPlugin.iter
25
+ PyAVPlugin.write
26
+ PyAVPlugin.properties
27
+ PyAVPlugin.metadata
28
+
29
+ Additional methods available inside the :func:`imopen <imageio.v3.imopen>`
30
+ context:
31
+
32
+ .. autosummary::
33
+ :toctree:
34
+
35
+ PyAVPlugin.init_video_stream
36
+ PyAVPlugin.write_frame
37
+ PyAVPlugin.set_video_filter
38
+ PyAVPlugin.container_metadata
39
+ PyAVPlugin.video_stream_metadata
40
+
41
+ Advanced API
42
+ ------------
43
+
44
+ In addition to the default ImageIO v3 API this plugin exposes custom functions
45
+ that are specific to reading/writing video and its metadata. These are available
46
+ inside the :func:`imopen <imageio.v3.imopen>` context and allow fine-grained
47
+ control over how the video is processed. The functions are documented above and
48
+ below you can find a usage example::
49
+
50
+ import imageio.v3 as iio
51
+
52
+ with iio.imopen("test.mp4", "w", plugin="pyav") as file:
53
+ file.init_video_stream("libx264")
54
+ file.container_metadata["comment"] = "This video was created using ImageIO."
55
+
56
+ for _ in range(5):
57
+ for frame in iio.imiter("imageio:newtonscradle.gif"):
58
+ file.write_frame(frame)
59
+
60
+ meta = iio.immeta("test.mp4", plugin="pyav")
61
+ assert meta["comment"] == "This video was created using ImageIO."
62
+
63
+
64
+
65
+ Pixel Formats (Colorspaces)
66
+ ---------------------------
67
+
68
+ By default, this plugin converts the video into 8-bit RGB (called ``rgb24`` in
69
+ ffmpeg). This is a useful behavior for many use-cases, but sometimes you may
70
+ want to use the video's native colorspace or you may wish to convert the video
71
+ into an entirely different colorspace. This is controlled using the ``format``
72
+ kwarg. You can use ``format=None`` to leave the image in its native colorspace
73
+ or specify any colorspace supported by FFMPEG as long as it is stridable, i.e.,
74
+ as long as it can be represented by a single numpy array. Some useful choices
75
+ include:
76
+
77
+ - rgb24 (default; 8-bit RGB)
78
+ - rgb48le (16-bit lower-endian RGB)
79
+ - bgr24 (8-bit BGR; openCVs default colorspace)
80
+ - gray (8-bit grayscale)
81
+ - yuv444p (8-bit channel-first YUV)
82
+
83
+ Further, FFMPEG maintains a list of available formats, albeit not as part of the
84
+ narrative docs. It can be `found here
85
+ <https://ffmpeg.org/doxygen/trunk/pixfmt_8h_source.html>`_ (warning: C source
86
+ code).
87
+
88
+ Filters
89
+ -------
90
+
91
+ On top of providing basic read/write functionality, this plugin allows you to
92
+ use the full collection of `video filters available in FFMPEG
93
+ <https://ffmpeg.org/ffmpeg-filters.html#Video-Filters>`_. This means that you
94
+ can apply excessive preprocessing to your video before retrieving it as a numpy
95
+ array or apply excessive post-processing before you encode your data.
96
+
97
+ Filters come in two forms: sequences or graphs. Filter sequences are, as the
98
+ name suggests, sequences of filters that are applied one after the other. They
99
+ are specified using the ``filter_sequence`` kwarg. Filter graphs, on the other
100
+ hand, come in the form of a directed graph and are specified using the
101
+ ``filter_graph`` kwarg.
102
+
103
+ .. note::
104
+ All filters are either sequences or graphs. If all you want is to apply a
105
+ single filter, you can do this by specifying a filter sequence with a single
106
+ entry.
107
+
108
+ A ``filter_sequence`` is a list of filters, each defined through a 2-element
109
+ tuple of the form ``(filter_name, filter_parameters)``. The first element of the
110
+ tuple is the name of the filter. The second element are the filter parameters,
111
+ which can be given either as a string or a dict. The string matches the same
112
+ format that you would use when specifying the filter using the ffmpeg
113
+ command-line tool and the dict has entries of the form ``parameter:value``. For
114
+ example::
115
+
116
+ import imageio.v3 as iio
117
+
118
+ # using a filter_parameters str
119
+ img1 = iio.imread(
120
+ "imageio:cockatoo.mp4",
121
+ plugin="pyav",
122
+ filter_sequence=[
123
+ ("rotate", "45*PI/180")
124
+ ]
125
+ )
126
+
127
+ # using a filter_parameters dict
128
+ img2 = iio.imread(
129
+ "imageio:cockatoo.mp4",
130
+ plugin="pyav",
131
+ filter_sequence=[
132
+ ("rotate", {"angle":"45*PI/180", "fillcolor":"AliceBlue"})
133
+ ]
134
+ )
135
+
136
+ A ``filter_graph``, on the other hand, is specified using a ``(nodes, edges)``
137
+ tuple. It is best explained using an example::
138
+
139
+ img = iio.imread(
140
+ "imageio:cockatoo.mp4",
141
+ plugin="pyav",
142
+ filter_graph=(
143
+ {
144
+ "split": ("split", ""),
145
+ "scale_overlay":("scale", "512:-1"),
146
+ "overlay":("overlay", "x=25:y=25:enable='between(t,1,8)'"),
147
+ },
148
+ [
149
+ ("video_in", "split", 0, 0),
150
+ ("split", "overlay", 0, 0),
151
+ ("split", "scale_overlay", 1, 0),
152
+ ("scale_overlay", "overlay", 0, 1),
153
+ ("overlay", "video_out", 0, 0),
154
+ ]
155
+ )
156
+ )
157
+
158
+ The above transforms the video to have picture-in-picture of itself in the top
159
+ left corner. As you can see, nodes are specified using a dict which has names as
160
+ its keys and filter tuples as values; the same tuples as the ones used when
161
+ defining a filter sequence. Edges are a list of a 4-tuples of the form
162
+ ``(node_out, node_in, output_idx, input_idx)`` and specify which two filters are
163
+ connected and which inputs/outputs should be used for this.
164
+
165
+ Further, there are two special nodes in a filter graph: ``video_in`` and
166
+ ``video_out``, which represent the graph's input and output respectively. These
167
+ names can not be chosen for other nodes (those nodes would simply be
168
+ overwritten), and for a graph to be valid there must be a path from the input to
169
+ the output and all nodes in the graph must be connected.
170
+
171
+ While most graphs are quite simple, they can become very complex and we
172
+ recommend that you read through the `FFMPEG documentation
173
+ <https://ffmpeg.org/ffmpeg-filters.html#Filtergraph-description>`_ and their
174
+ examples to better understand how to use them.
175
+
176
+ """
177
+
178
+ from fractions import Fraction
179
+ from math import ceil
180
+ from typing import Any, Dict, List, Optional, Tuple, Union, Generator
181
+
182
+ import av
183
+ import av.filter
184
+ import numpy as np
185
+ from numpy.lib.stride_tricks import as_strided
186
+
187
+ from ..core import Request
188
+ from ..core.request import URI_BYTES, InitializationError, IOMode
189
+ from ..core.v3_plugin_api import ImageProperties, PluginV3
190
+
191
+
192
+ def _format_to_dtype(format: av.VideoFormat) -> np.dtype:
193
+ """Convert a pyAV video format into a numpy dtype"""
194
+
195
+ if len(format.components) == 0:
196
+ # fake format
197
+ raise ValueError(
198
+ f"Can't determine dtype from format `{format.name}`. It has no channels."
199
+ )
200
+
201
+ endian = ">" if format.is_big_endian else "<"
202
+ dtype = "f" if "f32" in format.name else "u"
203
+ bits_per_channel = [x.bits for x in format.components]
204
+ n_bytes = str(int(ceil(bits_per_channel[0] / 8)))
205
+
206
+ return np.dtype(endian + dtype + n_bytes)
207
+
208
+
209
+ def _get_frame_shape(frame: av.VideoFrame) -> Tuple[int, ...]:
210
+ """Compute the frame's array shape
211
+
212
+ Parameters
213
+ ----------
214
+ frame : av.VideoFrame
215
+ A frame for which the resulting shape should be computed.
216
+
217
+ Returns
218
+ -------
219
+ shape : Tuple[int, ...]
220
+ A tuple describing the shape of the image data in the frame.
221
+
222
+ """
223
+
224
+ widths = [component.width for component in frame.format.components]
225
+ heights = [component.height for component in frame.format.components]
226
+ bits = np.array([component.bits for component in frame.format.components])
227
+ line_sizes = [plane.line_size for plane in frame.planes]
228
+
229
+ subsampled_width = widths[:-1] != widths[1:]
230
+ subsampled_height = heights[:-1] != heights[1:]
231
+ unaligned_components = np.any(bits % 8 != 0) or (line_sizes[:-1] != line_sizes[1:])
232
+ if subsampled_width or subsampled_height or unaligned_components:
233
+ raise IOError(
234
+ f"{frame.format.name} can't be expressed as a strided array."
235
+ "Use `format=` to select a format to convert into."
236
+ )
237
+
238
+ shape = [frame.height, frame.width]
239
+
240
+ # ffmpeg doesn't have a notion of channel-first or channel-last formats
241
+ # instead it stores frames in one or more planes which contain individual
242
+ # components of a pixel depending on the pixel format. For channel-first
243
+ # formats each component lives on a separate plane (n_planes) and for
244
+ # channel-last formats all components are packed on a single plane
245
+ # (n_channels)
246
+ n_planes = max([component.plane for component in frame.format.components]) + 1
247
+ if n_planes > 1:
248
+ shape = [n_planes] + shape
249
+
250
+ channels_per_plane = [0] * n_planes
251
+ for component in frame.format.components:
252
+ channels_per_plane[component.plane] += 1
253
+ n_channels = max(channels_per_plane)
254
+
255
+ if n_channels > 1:
256
+ shape = shape + [n_channels]
257
+
258
+ return tuple(shape)
259
+
260
+
261
+ class PyAVPlugin(PluginV3):
262
+ """Support for pyAV as backend.
263
+
264
+ Parameters
265
+ ----------
266
+ request : iio.Request
267
+ A request object that represents the users intent. It provides a
268
+ standard interface to access various the various ImageResources and
269
+ serves them to the plugin as a file object (or file). Check the docs for
270
+ details.
271
+ container : str
272
+ Only used during `iio_mode="w"`! If not None, overwrite the default container
273
+ format chosen by pyav.
274
+ kwargs : Any
275
+ Additional kwargs are forwarded to PyAV's constructor.
276
+
277
+ """
278
+
279
+ def __init__(self, request: Request, *, container: str = None, **kwargs) -> None:
280
+ """Initialize a new Plugin Instance.
281
+
282
+ See Plugin's docstring for detailed documentation.
283
+
284
+ Notes
285
+ -----
286
+ The implementation here stores the request as a local variable that is
287
+ exposed using a @property below. If you inherit from PluginV3, remember
288
+ to call ``super().__init__(request)``.
289
+
290
+ """
291
+
292
+ super().__init__(request)
293
+
294
+ self._container = None
295
+ self._video_stream = None
296
+ self._video_filter = None
297
+
298
+ if request.mode.io_mode == IOMode.read:
299
+ self._next_idx = 0
300
+ try:
301
+ if request._uri_type == 5: # 5 is the value of URI_HTTP
302
+ # pyav should read from HTTP by itself. This enables reading
303
+ # HTTP-based streams like DASH. Note that solving streams
304
+ # like this is temporary until the new request object gets
305
+ # implemented.
306
+ self._container = av.open(request.raw_uri, **kwargs)
307
+ else:
308
+ self._container = av.open(request.get_file(), **kwargs)
309
+ self._video_stream = self._container.streams.video[0]
310
+ self._decoder = self._container.decode(video=0)
311
+ except av.AVError:
312
+ if isinstance(request.raw_uri, bytes):
313
+ msg = "PyAV does not support these `<bytes>`"
314
+ else:
315
+ msg = f"PyAV does not support `{request.raw_uri}`"
316
+ raise InitializationError(msg) from None
317
+ else:
318
+ self.frames_written = 0
319
+ file_handle = self.request.get_file()
320
+ filename = getattr(file_handle, "name", None)
321
+ extension = self.request.extension or self.request.format_hint
322
+ if extension is None:
323
+ raise InitializationError("Can't determine output container to use.")
324
+
325
+ # hacky, but beats running our own format selection logic
326
+ # (since av_guess_format is not exposed)
327
+ try:
328
+ setattr(file_handle, "name", filename or "tmp" + extension)
329
+ except AttributeError:
330
+ pass # read-only, nothing we can do
331
+
332
+ try:
333
+ self._container = av.open(
334
+ file_handle, mode="w", format=container, **kwargs
335
+ )
336
+ except ValueError:
337
+ raise InitializationError(
338
+ f"PyAV can not write to `{self.request.raw_uri}`"
339
+ )
340
+
341
+ # ---------------------
342
+ # Standard V3 Interface
343
+ # ---------------------
344
+
345
+ def read(
346
+ self,
347
+ *,
348
+ index: int = ...,
349
+ format: str = "rgb24",
350
+ filter_sequence: List[Tuple[str, Union[str, dict]]] = None,
351
+ filter_graph: Tuple[dict, List] = None,
352
+ constant_framerate: bool = None,
353
+ thread_count: int = 0,
354
+ thread_type: str = None,
355
+ ) -> np.ndarray:
356
+ """Read frames from the video.
357
+
358
+ If ``index`` is an integer, this function reads the index-th frame from
359
+ the file. If ``index`` is ... (Ellipsis), this function reads all frames
360
+ from the video, stacks them along the first dimension, and returns a
361
+ batch of frames.
362
+
363
+ Parameters
364
+ ----------
365
+ index : int
366
+ The index of the frame to read, e.g. ``index=5`` reads the 5th
367
+ frame. If ``...``, read all the frames in the video and stack them
368
+ along a new, prepended, batch dimension.
369
+ format : str
370
+ Set the returned colorspace. If not None (default: rgb24), convert
371
+ the data into the given format before returning it. If ``None``
372
+ return the data in the encoded format if it can be expressed as a
373
+ strided array; otherwise raise an Exception.
374
+ filter_sequence : List[str, str, dict]
375
+ If not None, apply the given sequence of FFmpeg filters to each
376
+ ndimage. Check the (module-level) plugin docs for details and
377
+ examples.
378
+ filter_graph : (dict, List)
379
+ If not None, apply the given graph of FFmpeg filters to each
380
+ ndimage. The graph is given as a tuple of two dicts. The first dict
381
+ contains a (named) set of nodes, and the second dict contains a set
382
+ of edges between nodes of the previous dict. Check the (module-level)
383
+ plugin docs for details and examples.
384
+ constant_framerate : bool
385
+ If True assume the video's framerate is constant. This allows for
386
+ faster seeking inside the file. If False, the video is reset before
387
+ each read and searched from the beginning. If None (default), this
388
+ value will be read from the container format.
389
+ thread_count : int
390
+ How many threads to use when decoding a frame. The default is 0,
391
+ which will set the number using ffmpeg's default, which is based on
392
+ the codec, number of available cores, threadding model, and other
393
+ considerations.
394
+ thread_type : str
395
+ The threading model to be used. One of
396
+
397
+ - `"SLICE"`: threads assemble parts of the current frame
398
+ - `"FRAME"`: threads may assemble future frames
399
+ - None (default): Uses ``"FRAME"`` if ``index=...`` and ffmpeg's
400
+ default otherwise.
401
+
402
+
403
+ Returns
404
+ -------
405
+ frame : np.ndarray
406
+ A numpy array containing loaded frame data.
407
+
408
+ Notes
409
+ -----
410
+ Accessing random frames repeatedly is costly (O(k), where k is the
411
+ average distance between two keyframes). You should do so only sparingly
412
+ if possible. In some cases, it can be faster to bulk-read the video (if
413
+ it fits into memory) and to then access the returned ndarray randomly.
414
+
415
+ The current implementation may cause problems for b-frames, i.e.,
416
+ bidirectionaly predicted pictures. I lack test videos to write unit
417
+ tests for this case.
418
+
419
+ Reading from an index other than ``...``, i.e. reading a single frame,
420
+ currently doesn't support filters that introduce delays.
421
+
422
+ """
423
+
424
+ if index is ...:
425
+ props = self.properties(format=format)
426
+ uses_filter = (
427
+ self._video_filter is not None
428
+ or filter_graph is not None
429
+ or filter_sequence is not None
430
+ )
431
+
432
+ self._container.seek(0)
433
+ if not uses_filter and props.shape[0] != 0:
434
+ frames = np.empty(props.shape, dtype=props.dtype)
435
+ for idx, frame in enumerate(
436
+ self.iter(
437
+ format=format,
438
+ filter_sequence=filter_sequence,
439
+ filter_graph=filter_graph,
440
+ thread_count=thread_count,
441
+ thread_type=thread_type or "FRAME",
442
+ )
443
+ ):
444
+ frames[idx] = frame
445
+ else:
446
+ frames = np.stack(
447
+ [
448
+ x
449
+ for x in self.iter(
450
+ format=format,
451
+ filter_sequence=filter_sequence,
452
+ filter_graph=filter_graph,
453
+ thread_count=thread_count,
454
+ thread_type=thread_type or "FRAME",
455
+ )
456
+ ]
457
+ )
458
+
459
+ # reset stream container, because threading model can't change after
460
+ # first access
461
+ self._video_stream.close()
462
+ self._video_stream = self._container.streams.video[0]
463
+
464
+ return frames
465
+
466
+ if thread_type is not None and thread_type != self._video_stream.thread_type:
467
+ self._video_stream.thread_type = thread_type
468
+ if (
469
+ thread_count != 0
470
+ and thread_count != self._video_stream.codec_context.thread_count
471
+ ):
472
+ # in FFMPEG thread_count == 0 means use the default count, which we
473
+ # change to mean don't change the thread count.
474
+ self._video_stream.codec_context.thread_count = thread_count
475
+
476
+ if constant_framerate is None:
477
+ constant_framerate = not self._container.format.variable_fps
478
+
479
+ # note: cheap for contigous incremental reads
480
+ self._seek(index, constant_framerate=constant_framerate)
481
+ desired_frame = next(self._decoder)
482
+ self._next_idx += 1
483
+
484
+ self.set_video_filter(filter_sequence, filter_graph)
485
+ if self._video_filter is not None:
486
+ desired_frame = self._video_filter.send(desired_frame)
487
+
488
+ return self._unpack_frame(desired_frame, format=format)
489
+
490
+ def iter(
491
+ self,
492
+ *,
493
+ format: str = "rgb24",
494
+ filter_sequence: List[Tuple[str, Union[str, dict]]] = None,
495
+ filter_graph: Tuple[dict, List] = None,
496
+ thread_count: int = 0,
497
+ thread_type: str = None,
498
+ ) -> np.ndarray:
499
+ """Yield frames from the video.
500
+
501
+ Parameters
502
+ ----------
503
+ frame : np.ndarray
504
+ A numpy array containing loaded frame data.
505
+ format : str
506
+ Convert the data into the given format before returning it. If None,
507
+ return the data in the encoded format if it can be expressed as a
508
+ strided array; otherwise raise an Exception.
509
+ filter_sequence : List[str, str, dict]
510
+ Set the returned colorspace. If not None (default: rgb24), convert
511
+ the data into the given format before returning it. If ``None``
512
+ return the data in the encoded format if it can be expressed as a
513
+ strided array; otherwise raise an Exception.
514
+ filter_graph : (dict, List)
515
+ If not None, apply the given graph of FFmpeg filters to each
516
+ ndimage. The graph is given as a tuple of two dicts. The first dict
517
+ contains a (named) set of nodes, and the second dict contains a set
518
+ of edges between nodes of the previous dict. Check the (module-level)
519
+ plugin docs for details and examples.
520
+ thread_count : int
521
+ How many threads to use when decoding a frame. The default is 0,
522
+ which will set the number using ffmpeg's default, which is based on
523
+ the codec, number of available cores, threadding model, and other
524
+ considerations.
525
+ thread_type : str
526
+ The threading model to be used. One of
527
+
528
+ - `"SLICE"` (default): threads assemble parts of the current frame
529
+ - `"FRAME"`: threads may assemble future frames (faster for bulk reading)
530
+
531
+
532
+ Yields
533
+ ------
534
+ frame : np.ndarray
535
+ A (decoded) video frame.
536
+
537
+
538
+ """
539
+
540
+ self._video_stream.thread_type = thread_type or "SLICE"
541
+ self._video_stream.codec_context.thread_count = thread_count
542
+
543
+ self.set_video_filter(filter_sequence, filter_graph)
544
+
545
+ for frame in self._decoder:
546
+ self._next_idx += 1
547
+
548
+ if self._video_filter is not None:
549
+ try:
550
+ frame = self._video_filter.send(frame)
551
+ except StopIteration:
552
+ break
553
+
554
+ if frame is None:
555
+ continue
556
+
557
+ yield self._unpack_frame(frame, format=format)
558
+
559
+ if self._video_filter is not None:
560
+ for frame in self._video_filter:
561
+ yield self._unpack_frame(frame, format=format)
562
+
563
+ def write(
564
+ self,
565
+ ndimage: Union[np.ndarray, List[np.ndarray]],
566
+ *,
567
+ codec: str = None,
568
+ is_batch: bool = True,
569
+ fps: int = 24,
570
+ in_pixel_format: str = "rgb24",
571
+ out_pixel_format: str = None,
572
+ filter_sequence: List[Tuple[str, Union[str, dict]]] = None,
573
+ filter_graph: Tuple[dict, List] = None,
574
+ ) -> Optional[bytes]:
575
+ """Save a ndimage as a video.
576
+
577
+ Given a batch of frames (stacked along the first axis) or a list of
578
+ frames, encode them and add the result to the ImageResource.
579
+
580
+ Parameters
581
+ ----------
582
+ ndimage : ArrayLike, List[ArrayLike]
583
+ The ndimage to encode and write to the ImageResource.
584
+ codec : str
585
+ The codec to use when encoding frames. Only needed on first write
586
+ and ignored on subsequent writes.
587
+ is_batch : bool
588
+ If True (default), the ndimage is a batch of images, otherwise it is
589
+ a single image. This parameter has no effect on lists of ndimages.
590
+ fps : str
591
+ The resulting videos frames per second.
592
+ in_pixel_format : str
593
+ The pixel format of the incoming ndarray. Defaults to "rgb24" and can
594
+ be any stridable pix_fmt supported by FFmpeg.
595
+ out_pixel_format : str
596
+ The pixel format to use while encoding frames. If None (default)
597
+ use the codec's default.
598
+ filter_sequence : List[str, str, dict]
599
+ If not None, apply the given sequence of FFmpeg filters to each
600
+ ndimage. Check the (module-level) plugin docs for details and
601
+ examples.
602
+ filter_graph : (dict, List)
603
+ If not None, apply the given graph of FFmpeg filters to each
604
+ ndimage. The graph is given as a tuple of two dicts. The first dict
605
+ contains a (named) set of nodes, and the second dict contains a set
606
+ of edges between nodes of the previous dict. Check the (module-level)
607
+ plugin docs for details and examples.
608
+
609
+ Returns
610
+ -------
611
+ encoded_image : bytes or None
612
+ If the chosen ImageResource is the special target ``"<bytes>"`` then
613
+ write will return a byte string containing the encoded image data.
614
+ Otherwise, it returns None.
615
+
616
+ Notes
617
+ -----
618
+ When writing ``<bytes>``, the video is finalized immediately after the
619
+ first write call and calling write multiple times to append frames is
620
+ not possible.
621
+
622
+ """
623
+
624
+ if isinstance(ndimage, list):
625
+ # frames shapes must agree for video
626
+ if any(f.shape != ndimage[0].shape for f in ndimage):
627
+ raise ValueError("All frames should have the same shape")
628
+ elif not is_batch:
629
+ ndimage = np.asarray(ndimage)[None, ...]
630
+ else:
631
+ ndimage = np.asarray(ndimage)
632
+
633
+ if self._video_stream is None:
634
+ self.init_video_stream(codec, fps=fps, pixel_format=out_pixel_format)
635
+
636
+ self.set_video_filter(filter_sequence, filter_graph)
637
+
638
+ for img in ndimage:
639
+ self.write_frame(img, pixel_format=in_pixel_format)
640
+
641
+ if self.request._uri_type == URI_BYTES:
642
+ # bytes are immutuable, so we have to flush immediately
643
+ # and can't support appending
644
+ self._flush_writer()
645
+ self._container.close()
646
+
647
+ return self.request.get_file().getvalue()
648
+
649
+ def properties(self, index: int = ..., *, format: str = "rgb24") -> ImageProperties:
650
+ """Standardized ndimage metadata.
651
+
652
+ Parameters
653
+ ----------
654
+ index : int
655
+ The index of the ndimage for which to return properties. If ``...``
656
+ (Ellipsis, default), return the properties for the resulting batch
657
+ of frames.
658
+ format : str
659
+ If not None (default: rgb24), convert the data into the given format
660
+ before returning it. If None return the data in the encoded format
661
+ if that can be expressed as a strided array; otherwise raise an
662
+ Exception.
663
+
664
+ Returns
665
+ -------
666
+ properties : ImageProperties
667
+ A dataclass filled with standardized image metadata.
668
+
669
+ Notes
670
+ -----
671
+ This function is efficient and won't process any pixel data.
672
+
673
+ The provided metadata does not include modifications by any filters
674
+ (through ``filter_sequence`` or ``filter_graph``).
675
+
676
+ """
677
+
678
+ video_width = self._video_stream.codec_context.width
679
+ video_height = self._video_stream.codec_context.height
680
+ pix_format = format or self._video_stream.codec_context.pix_fmt
681
+ frame_template = av.VideoFrame(video_width, video_height, pix_format)
682
+
683
+ shape = _get_frame_shape(frame_template)
684
+ if index is ...:
685
+ n_frames = self._video_stream.frames
686
+ shape = (n_frames,) + shape
687
+
688
+ return ImageProperties(
689
+ shape=tuple(shape),
690
+ dtype=_format_to_dtype(frame_template.format),
691
+ n_images=shape[0] if index is ... else None,
692
+ is_batch=index is ...,
693
+ )
694
+
695
+ def metadata(
696
+ self,
697
+ index: int = ...,
698
+ exclude_applied: bool = True,
699
+ constant_framerate: bool = None,
700
+ ) -> Dict[str, Any]:
701
+ """Format-specific metadata.
702
+
703
+ Returns a dictionary filled with metadata that is either stored in the
704
+ container, the video stream, or the frame's side-data.
705
+
706
+ Parameters
707
+ ----------
708
+ index : int
709
+ If ... (Ellipsis, default) return global metadata (the metadata
710
+ stored in the container and video stream). If not ..., return the
711
+ side data stored in the frame at the given index.
712
+ exclude_applied : bool
713
+ Currently, this parameter has no effect. It exists for compliance with
714
+ the ImageIO v3 API.
715
+ constant_framerate : bool
716
+ If True assume the video's framerate is constant. This allows for
717
+ faster seeking inside the file. If False, the video is reset before
718
+ each read and searched from the beginning. If None (default), this
719
+ value will be read from the container format.
720
+
721
+ Returns
722
+ -------
723
+ metadata : dict
724
+ A dictionary filled with format-specific metadata fields and their
725
+ values.
726
+
727
+ """
728
+
729
+ metadata = dict()
730
+
731
+ if index is ...:
732
+ # useful flags defined on the container and/or video stream
733
+ metadata.update(
734
+ {
735
+ "video_format": self._video_stream.codec_context.pix_fmt,
736
+ "codec": self._video_stream.codec.name,
737
+ "long_codec": self._video_stream.codec.long_name,
738
+ "profile": self._video_stream.profile,
739
+ "fps": float(self._video_stream.guessed_rate),
740
+ }
741
+ )
742
+ if self._video_stream.duration is not None:
743
+ duration = float(
744
+ self._video_stream.duration * self._video_stream.time_base
745
+ )
746
+ metadata.update({"duration": duration})
747
+
748
+ metadata.update(self.container_metadata)
749
+ metadata.update(self.video_stream_metadata)
750
+ return metadata
751
+
752
+ if constant_framerate is None:
753
+ constant_framerate = not self._container.format.variable_fps
754
+
755
+ self._seek(index, constant_framerate=constant_framerate)
756
+ desired_frame = next(self._decoder)
757
+ self._next_idx += 1
758
+
759
+ # useful flags defined on the frame
760
+ metadata.update(
761
+ {
762
+ "key_frame": bool(desired_frame.key_frame),
763
+ "time": desired_frame.time,
764
+ "interlaced_frame": bool(desired_frame.interlaced_frame),
765
+ "frame_type": desired_frame.pict_type.name,
766
+ }
767
+ )
768
+
769
+ # side data
770
+ metadata.update(
771
+ {item.type.name: bytes(item) for item in desired_frame.side_data}
772
+ )
773
+
774
+ return metadata
775
+
776
+ def close(self) -> None:
777
+ """Close the Video."""
778
+
779
+ is_write = self.request.mode.io_mode == IOMode.write
780
+ if is_write and self._video_stream is not None:
781
+ self._flush_writer()
782
+
783
+ if self._video_stream is not None:
784
+ try:
785
+ self._video_stream.close()
786
+ except ValueError:
787
+ pass # stream already closed
788
+
789
+ if self._container is not None:
790
+ self._container.close()
791
+
792
+ self.request.finish()
793
+
794
+ def __enter__(self) -> "PyAVPlugin":
795
+ return super().__enter__()
796
+
797
+ # ------------------------------
798
+ # Add-on Interface inside imopen
799
+ # ------------------------------
800
+
801
+ def init_video_stream(
802
+ self,
803
+ codec: str,
804
+ *,
805
+ fps: float = 24,
806
+ pixel_format: str = None,
807
+ max_keyframe_interval: int = None,
808
+ force_keyframes: bool = None,
809
+ ) -> None:
810
+ """Initialize a new video stream.
811
+
812
+ This function adds a new video stream to the ImageResource using the
813
+ selected encoder (codec), framerate, and colorspace.
814
+
815
+ Parameters
816
+ ----------
817
+ codec : str
818
+ The codec to use, e.g. ``"libx264"`` or ``"vp9"``.
819
+ fps : float
820
+ The desired framerate of the video stream (frames per second).
821
+ pixel_format : str
822
+ The pixel format to use while encoding frames. If None (default) use
823
+ the codec's default.
824
+ max_keyframe_interval : int
825
+ The maximum distance between two intra frames (I-frames). Also known
826
+ as GOP size. If unspecified use the codec's default. Note that not
827
+ every I-frame is a keyframe; see the notes for details.
828
+ force_keyframes : bool
829
+ If True, limit inter frames dependency to frames within the current
830
+ keyframe interval (GOP), i.e., force every I-frame to be a keyframe.
831
+ If unspecified, use the codec's default.
832
+
833
+ Notes
834
+ -----
835
+ You can usually leave ``max_keyframe_interval`` and ``force_keyframes``
836
+ at their default values, unless you try to generate seek-optimized video
837
+ or have a similar specialist use-case. In this case, ``force_keyframes``
838
+ controls the ability to seek to _every_ I-frame, and
839
+ ``max_keyframe_interval`` controls how close to a random frame you can
840
+ seek. Low values allow more fine-grained seek at the expense of
841
+ file-size (and thus I/O performance).
842
+
843
+ """
844
+
845
+ fps = Fraction.from_float(fps)
846
+ stream = self._container.add_stream(codec, fps)
847
+ stream.time_base = Fraction(1 / fps).limit_denominator(int(2**16 - 1))
848
+ if pixel_format is not None:
849
+ stream.pix_fmt = pixel_format
850
+ if max_keyframe_interval is not None:
851
+ stream.gop_size = max_keyframe_interval
852
+ if force_keyframes is not None:
853
+ stream.closed_gop = force_keyframes
854
+
855
+ self._video_stream = stream
856
+
857
+ def write_frame(self, frame: np.ndarray, *, pixel_format: str = "rgb24") -> None:
858
+ """Add a frame to the video stream.
859
+
860
+ This function appends a new frame to the video. It assumes that the
861
+ stream previously has been initialized. I.e., ``init_video_stream`` has
862
+ to be called before calling this function for the write to succeed.
863
+
864
+ Parameters
865
+ ----------
866
+ frame : np.ndarray
867
+ The image to be appended/written to the video stream.
868
+ pixel_format : str
869
+ The colorspace (pixel format) of the incoming frame.
870
+
871
+ Notes
872
+ -----
873
+ Frames may be held in a buffer, e.g., by the filter pipeline used during
874
+ writing or by FFMPEG to batch them prior to encoding. Make sure to
875
+ ``.close()`` the plugin or to use a context manager to ensure that all
876
+ frames are written to the ImageResource.
877
+
878
+ """
879
+
880
+ # manual packing of ndarray into frame
881
+ # (this should live in pyAV, but it doesn't support all the formats we
882
+ # want and PRs there are slow)
883
+ pixel_format = av.VideoFormat(pixel_format)
884
+ img_dtype = _format_to_dtype(pixel_format)
885
+ width = frame.shape[2 if pixel_format.is_planar else 1]
886
+ height = frame.shape[1 if pixel_format.is_planar else 0]
887
+ av_frame = av.VideoFrame(width, height, pixel_format.name)
888
+ if pixel_format.is_planar:
889
+ for idx, plane in enumerate(av_frame.planes):
890
+ plane_array = np.frombuffer(plane, dtype=img_dtype)
891
+ plane_array = as_strided(
892
+ plane_array,
893
+ shape=(plane.height, plane.width),
894
+ strides=(plane.line_size, img_dtype.itemsize),
895
+ )
896
+ plane_array[...] = frame[idx]
897
+ else:
898
+ if pixel_format.name.startswith("bayer_"):
899
+ # ffmpeg doesn't describe bayer formats correctly
900
+ # see https://github.com/imageio/imageio/issues/761#issuecomment-1059318851
901
+ # and following for details.
902
+ n_channels = 1
903
+ else:
904
+ n_channels = len(pixel_format.components)
905
+
906
+ plane = av_frame.planes[0]
907
+ plane_shape = (plane.height, plane.width)
908
+ plane_strides = (plane.line_size, n_channels * img_dtype.itemsize)
909
+ if n_channels > 1:
910
+ plane_shape += (n_channels,)
911
+ plane_strides += (img_dtype.itemsize,)
912
+
913
+ plane_array = as_strided(
914
+ np.frombuffer(plane, dtype=img_dtype),
915
+ shape=plane_shape,
916
+ strides=plane_strides,
917
+ )
918
+ plane_array[...] = frame
919
+
920
+ stream = self._video_stream
921
+ av_frame.time_base = stream.codec_context.time_base
922
+ av_frame.pts = self.frames_written
923
+ self.frames_written += 1
924
+
925
+ if self._video_filter is not None:
926
+ av_frame = self._video_filter.send(av_frame)
927
+ if av_frame is None:
928
+ return
929
+
930
+ if stream.frames == 0:
931
+ stream.width = av_frame.width
932
+ stream.height = av_frame.height
933
+
934
+ for packet in stream.encode(av_frame):
935
+ self._container.mux(packet)
936
+
937
+ def set_video_filter(
938
+ self,
939
+ filter_sequence: List[Tuple[str, Union[str, dict]]] = None,
940
+ filter_graph: Tuple[dict, List] = None,
941
+ ) -> None:
942
+ """Set the filter(s) to use.
943
+
944
+ This function creates a new FFMPEG filter graph to use when reading or
945
+ writing video. In the case of reading, frames are passed through the
946
+ filter graph before begin returned and, in case of writing, frames are
947
+ passed through the filter before being written to the video.
948
+
949
+ Parameters
950
+ ----------
951
+ filter_sequence : List[str, str, dict]
952
+ If not None, apply the given sequence of FFmpeg filters to each
953
+ ndimage. Check the (module-level) plugin docs for details and
954
+ examples.
955
+ filter_graph : (dict, List)
956
+ If not None, apply the given graph of FFmpeg filters to each
957
+ ndimage. The graph is given as a tuple of two dicts. The first dict
958
+ contains a (named) set of nodes, and the second dict contains a set
959
+ of edges between nodes of the previous dict. Check the
960
+ (module-level) plugin docs for details and examples.
961
+
962
+ Notes
963
+ -----
964
+ Changing a filter graph with lag during reading or writing will
965
+ currently cause frames in the filter queue to be lost.
966
+
967
+ """
968
+
969
+ if filter_sequence is None and filter_graph is None:
970
+ self._video_filter = None
971
+ return
972
+
973
+ if filter_sequence is None:
974
+ filter_sequence = list()
975
+
976
+ node_descriptors: Dict[str, Tuple[str, Union[str, Dict]]]
977
+ edges: List[Tuple[str, str, int, int]]
978
+ if filter_graph is None:
979
+ node_descriptors, edges = dict(), [("video_in", "video_out", 0, 0)]
980
+ else:
981
+ node_descriptors, edges = filter_graph
982
+
983
+ graph = av.filter.Graph()
984
+
985
+ previous_node = graph.add_buffer(template=self._video_stream)
986
+ for filter_name, argument in filter_sequence:
987
+ if isinstance(argument, str):
988
+ current_node = graph.add(filter_name, argument)
989
+ else:
990
+ current_node = graph.add(filter_name, **argument)
991
+ previous_node.link_to(current_node)
992
+ previous_node = current_node
993
+
994
+ nodes = dict()
995
+ nodes["video_in"] = previous_node
996
+ nodes["video_out"] = graph.add("buffersink")
997
+ for name, (filter_name, arguments) in node_descriptors.items():
998
+ if isinstance(arguments, str):
999
+ nodes[name] = graph.add(filter_name, arguments)
1000
+ else:
1001
+ nodes[name] = graph.add(filter_name, **arguments)
1002
+
1003
+ for from_note, to_node, out_idx, in_idx in edges:
1004
+ nodes[from_note].link_to(nodes[to_node], out_idx, in_idx)
1005
+
1006
+ graph.configure()
1007
+
1008
+ def video_filter():
1009
+ # this starts a co-routine
1010
+ # send frames using graph.send()
1011
+ frame = yield None
1012
+
1013
+ # send and receive frames in "parallel"
1014
+ while frame is not None:
1015
+ graph.push(frame)
1016
+ try:
1017
+ frame = yield graph.pull()
1018
+ except av.error.BlockingIOError:
1019
+ # filter has lag and needs more frames
1020
+ frame = yield None
1021
+ except av.error.EOFError:
1022
+ break
1023
+
1024
+ try:
1025
+ # send EOF in av>=9.0
1026
+ graph.push(None)
1027
+ except ValueError: # pragma: no cover
1028
+ # handle av<9.0
1029
+ pass
1030
+
1031
+ # all frames have been sent, empty the filter
1032
+ while True:
1033
+ try:
1034
+ yield graph.pull()
1035
+ except av.error.EOFError:
1036
+ break # EOF
1037
+ except av.error.BlockingIOError: # pragma: no cover
1038
+ # handle av<9.0
1039
+ break
1040
+
1041
+ self._video_filter = video_filter()
1042
+ self._video_filter.send(None)
1043
+
1044
+ @property
1045
+ def container_metadata(self):
1046
+ """Container-specific metadata.
1047
+
1048
+ A dictionary containing metadata stored at the container level.
1049
+
1050
+ """
1051
+ return self._container.metadata
1052
+
1053
+ @property
1054
+ def video_stream_metadata(self):
1055
+ """Stream-specific metadata.
1056
+
1057
+ A dictionary containing metadata stored at the stream level.
1058
+
1059
+ """
1060
+ return self._video_stream.metadata
1061
+
1062
+ # -------------------------------
1063
+ # Internals and private functions
1064
+ # -------------------------------
1065
+
1066
+ def _unpack_frame(self, frame: av.VideoFrame, *, format: str = None) -> np.ndarray:
1067
+ """Convert a av.VideoFrame into a ndarray
1068
+
1069
+ Parameters
1070
+ ----------
1071
+ frame : av.VideoFrame
1072
+ The frame to unpack.
1073
+ format : str
1074
+ If not None, convert the frame to the given format before unpacking.
1075
+
1076
+ """
1077
+
1078
+ if format is not None:
1079
+ frame = frame.reformat(format=format)
1080
+
1081
+ dtype = _format_to_dtype(frame.format)
1082
+ shape = _get_frame_shape(frame)
1083
+
1084
+ planes = list()
1085
+ for idx in range(len(frame.planes)):
1086
+ n_channels = sum(
1087
+ [
1088
+ x.bits // (dtype.itemsize * 8)
1089
+ for x in frame.format.components
1090
+ if x.plane == idx
1091
+ ]
1092
+ )
1093
+ av_plane = frame.planes[idx]
1094
+ plane_shape = (av_plane.height, av_plane.width)
1095
+ plane_strides = (av_plane.line_size, n_channels * dtype.itemsize)
1096
+ if n_channels > 1:
1097
+ plane_shape += (n_channels,)
1098
+ plane_strides += (dtype.itemsize,)
1099
+
1100
+ np_plane = as_strided(
1101
+ np.frombuffer(av_plane, dtype=dtype),
1102
+ shape=plane_shape,
1103
+ strides=plane_strides,
1104
+ )
1105
+ planes.append(np_plane)
1106
+
1107
+ if len(planes) > 1:
1108
+ # Note: the planes *should* exist inside a contigous memory block
1109
+ # somewhere inside av.Frame however pyAV does not appear to expose this,
1110
+ # so we are forced to copy the planes individually instead of wrapping
1111
+ # them :(
1112
+ out = np.concatenate(planes).reshape(shape)
1113
+ else:
1114
+ out = planes[0]
1115
+
1116
+ return out
1117
+
1118
+ def _seek(self, index, *, constant_framerate: bool = True) -> Generator:
1119
+ """Seeks to the frame at the given index."""
1120
+
1121
+ if index == self._next_idx:
1122
+ return # fast path :)
1123
+
1124
+ # we must decode at least once before we seek otherwise the
1125
+ # returned frames become corrupt.
1126
+ if self._next_idx == 0:
1127
+ next(self._decoder)
1128
+ self._next_idx += 1
1129
+
1130
+ if index == self._next_idx:
1131
+ return # fast path :)
1132
+
1133
+ # remove this branch until I find a way to efficiently find the next
1134
+ # keyframe. keeping this as a reminder
1135
+ # if self._next_idx < index and index < self._next_keyframe_idx:
1136
+ # frames_to_yield = index - self._next_idx
1137
+ if not constant_framerate and index > self._next_idx:
1138
+ frames_to_yield = index - self._next_idx
1139
+ elif not constant_framerate:
1140
+ # seek backwards and can't link idx and pts
1141
+ self._container.seek(0)
1142
+ self._decoder = self._container.decode(video=0)
1143
+ self._next_idx = 0
1144
+
1145
+ frames_to_yield = index
1146
+ else:
1147
+ # we know that the time between consecutive frames is constant
1148
+ # hence we can link index and pts
1149
+
1150
+ # how many pts lie between two frames
1151
+ sec_delta = 1 / self._video_stream.guessed_rate
1152
+ pts_delta = sec_delta / self._video_stream.time_base
1153
+
1154
+ index_pts = int(index * pts_delta)
1155
+
1156
+ # this only seeks to the closed (preceeding) keyframe
1157
+ self._container.seek(index_pts, stream=self._video_stream)
1158
+ self._decoder = self._container.decode(video=0)
1159
+
1160
+ # this may be made faster if we could get the keyframe's time without
1161
+ # decoding it
1162
+ keyframe = next(self._decoder)
1163
+ keyframe_time = keyframe.pts * keyframe.time_base
1164
+ keyframe_pts = int(keyframe_time / self._video_stream.time_base)
1165
+ keyframe_index = keyframe_pts // pts_delta
1166
+
1167
+ self._container.seek(index_pts, stream=self._video_stream)
1168
+ self._next_idx = keyframe_index
1169
+
1170
+ frames_to_yield = index - keyframe_index
1171
+
1172
+ for _ in range(frames_to_yield):
1173
+ next(self._decoder)
1174
+ self._next_idx += 1
1175
+
1176
+ def _flush_writer(self):
1177
+ """Flush the filter and encoder
1178
+
1179
+ This will reset the filter to `None` and send EoF to the encoder,
1180
+ i.e., after calling, no more frames may be written.
1181
+
1182
+ """
1183
+
1184
+ stream = self._video_stream
1185
+
1186
+ if self._video_filter is not None:
1187
+ # flush encoder
1188
+ for av_frame in self._video_filter:
1189
+ if stream.frames == 0:
1190
+ stream.width = av_frame.width
1191
+ stream.height = av_frame.height
1192
+ for packet in stream.encode(av_frame):
1193
+ self._container.mux(packet)
1194
+ self._video_filter = None
1195
+
1196
+ # flush stream
1197
+ for packet in stream.encode():
1198
+ self._container.mux(packet)
1199
+ self._video_stream = None
evalkit_tf446/lib/python3.10/site-packages/imageio/plugins/rawpy.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Read/Write images using rawpy.
2
+
3
+ rawpy is an easy-to-use Python wrapper for the LibRaw library.
4
+ It also contains some extra functionality for finding and repairing hot/dead pixels.
5
+ """
6
+
7
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
8
+ import rawpy
9
+ import numpy as np
10
+
11
+ from ..core.request import URI_BYTES, InitializationError, IOMode, Request
12
+ from ..core.v3_plugin_api import ImageProperties, PluginV3
13
+ from ..typing import ArrayLike
14
+
15
+
16
+ class RawPyPlugin(PluginV3):
17
+ """A class representing the rawpy plugin.
18
+
19
+ Methods
20
+ -------
21
+
22
+ .. autosummary::
23
+ :toctree: _plugins/rawpy
24
+
25
+ RawPyPlugin.read
26
+ """
27
+
28
+ def __init__(self, request: Request) -> None:
29
+ """Instantiates a new rawpy plugin object
30
+
31
+ Parameters
32
+ ----------
33
+ request: Request
34
+ A request object representing the resource to be operated on.
35
+ """
36
+
37
+ super().__init__(request)
38
+
39
+ self._image_file = None
40
+
41
+ if request.mode.io_mode == IOMode.read:
42
+ try:
43
+ self._image_file = rawpy.imread(request.get_file())
44
+ except (
45
+ rawpy.NotSupportedError,
46
+ rawpy.LibRawFileUnsupportedError,
47
+ rawpy.LibRawIOError,
48
+ ):
49
+ if request._uri_type == URI_BYTES:
50
+ raise InitializationError(
51
+ "RawPy can not read the provided bytes."
52
+ ) from None
53
+ else:
54
+ raise InitializationError(
55
+ f"RawPy can not read {request.raw_uri}."
56
+ ) from None
57
+ elif request.mode.io_mode == IOMode.write:
58
+ raise InitializationError("RawPy does not support writing.") from None
59
+
60
+ def close(self) -> None:
61
+ if self._image_file:
62
+ self._image_file.close()
63
+
64
+ self._request.finish()
65
+
66
+ def read(self, *, index: int = 0, **kwargs) -> np.ndarray:
67
+ """Read Raw Image.
68
+
69
+ Returns
70
+ -------
71
+ nd_image: ndarray
72
+ The image data
73
+ """
74
+
75
+ nd_image: np.ndarray
76
+
77
+ try:
78
+ nd_image = self._image_file.postprocess(**kwargs)
79
+ except Exception:
80
+ pass
81
+
82
+ if index is Ellipsis:
83
+ nd_image = nd_image[None, ...]
84
+
85
+ return nd_image
86
+
87
+ def write(self, ndimage: Union[ArrayLike, List[ArrayLike]]) -> Optional[bytes]:
88
+ """RawPy does not support writing."""
89
+ raise NotImplementedError()
90
+
91
+ def iter(self) -> Iterator[np.ndarray]:
92
+ """Load the image.
93
+
94
+ Returns
95
+ -------
96
+ nd_image: ndarray
97
+ The image data
98
+ """
99
+
100
+ try:
101
+ yield self.read()
102
+ except Exception:
103
+ pass
104
+
105
+ def metadata(
106
+ self, index: int = None, exclude_applied: bool = True
107
+ ) -> Dict[str, Any]:
108
+ """Read ndimage metadata.
109
+
110
+ Parameters
111
+ ----------
112
+ exclude_applied : bool
113
+ If True, exclude metadata fields that are applied to the image while
114
+ reading. For example, if the binary data contains a rotation flag,
115
+ the image is rotated by default and the rotation flag is excluded
116
+ from the metadata to avoid confusion.
117
+
118
+ Returns
119
+ -------
120
+ metadata : dict
121
+ A dictionary of format-specific metadata.
122
+
123
+ """
124
+
125
+ metadata = {}
126
+
127
+ image_size = self._image_file.sizes
128
+
129
+ metadata["black_level_per_channel"] = self._image_file.black_level_per_channel
130
+ metadata["camera_white_level_per_channel"] = (
131
+ self._image_file.camera_white_level_per_channel
132
+ )
133
+ metadata["color_desc"] = self._image_file.color_desc
134
+ metadata["color_matrix"] = self._image_file.color_matrix
135
+ metadata["daylight_whitebalance"] = self._image_file.daylight_whitebalance
136
+ metadata["dtype"] = self._image_file.raw_image.dtype
137
+ metadata["flip"] = image_size.flip
138
+ metadata["num_colors"] = self._image_file.num_colors
139
+ metadata["tone_curve"] = self._image_file.tone_curve
140
+ metadata["width"] = image_size.width
141
+ metadata["height"] = image_size.height
142
+ metadata["raw_width"] = image_size.raw_width
143
+ metadata["raw_height"] = image_size.raw_height
144
+ metadata["raw_shape"] = self._image_file.raw_image.shape
145
+ metadata["iwidth"] = image_size.iwidth
146
+ metadata["iheight"] = image_size.iheight
147
+ metadata["pixel_aspect"] = image_size.pixel_aspect
148
+ metadata["white_level"] = self._image_file.white_level
149
+
150
+ if exclude_applied:
151
+ metadata.pop("black_level_per_channel", None)
152
+ metadata.pop("camera_white_level_per_channel", None)
153
+ metadata.pop("color_desc", None)
154
+ metadata.pop("color_matrix", None)
155
+ metadata.pop("daylight_whitebalance", None)
156
+ metadata.pop("dtype", None)
157
+ metadata.pop("flip", None)
158
+ metadata.pop("num_colors", None)
159
+ metadata.pop("tone_curve", None)
160
+ metadata.pop("raw_width", None)
161
+ metadata.pop("raw_height", None)
162
+ metadata.pop("raw_shape", None)
163
+ metadata.pop("iwidth", None)
164
+ metadata.pop("iheight", None)
165
+ metadata.pop("white_level", None)
166
+
167
+ return metadata
168
+
169
+ def properties(self, index: int = None) -> ImageProperties:
170
+ """Standardized ndimage metadata
171
+
172
+ Returns
173
+ -------
174
+ properties : ImageProperties
175
+ A dataclass filled with standardized image metadata.
176
+
177
+ Notes
178
+ -----
179
+ This does not decode pixel data and is fast for large images.
180
+
181
+ """
182
+
183
+ ImageSize = self._image_file.sizes
184
+
185
+ width: int = ImageSize.width
186
+ height: int = ImageSize.height
187
+ shape: Tuple[int, ...] = (height, width)
188
+
189
+ dtype = self._image_file.raw_image.dtype
190
+
191
+ return ImageProperties(shape=shape, dtype=dtype)
evalkit_tf446/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_tf446/lib/python3.10/site-packages/imageio/py.typed ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/imageio/testing.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Distributed under the (new) BSD License. See LICENSE.txt for more info.
3
+
4
+ """ Functionality used for testing. This code itself is not covered in tests.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import pytest
10
+
11
+ # Get root dir
12
+ THIS_DIR = os.path.abspath(os.path.dirname(__file__))
13
+ ROOT_DIR = THIS_DIR
14
+ for i in range(9):
15
+ ROOT_DIR = os.path.dirname(ROOT_DIR)
16
+ if os.path.isfile(os.path.join(ROOT_DIR, ".gitignore")):
17
+ break
18
+
19
+
20
+ # Functions to use from invoke tasks
21
+
22
+
23
+ def test_unit(cov_report="term"):
24
+ """Run all unit tests. Returns exit code."""
25
+ orig_dir = os.getcwd()
26
+ os.chdir(ROOT_DIR)
27
+ try:
28
+ _clear_imageio()
29
+ _enable_faulthandler()
30
+ return pytest.main(
31
+ [
32
+ "-v",
33
+ "--cov",
34
+ "imageio",
35
+ "--cov-config",
36
+ ".coveragerc",
37
+ "--cov-report",
38
+ cov_report,
39
+ "tests",
40
+ ]
41
+ )
42
+ finally:
43
+ os.chdir(orig_dir)
44
+ import imageio
45
+
46
+ print("Tests were performed on", str(imageio))
47
+
48
+
49
+ # Requirements
50
+
51
+
52
+ def _enable_faulthandler():
53
+ """Enable faulthandler (if we can), so that we get tracebacks
54
+ on segfaults.
55
+ """
56
+ try:
57
+ import faulthandler
58
+
59
+ faulthandler.enable()
60
+ print("Faulthandler enabled")
61
+ except Exception:
62
+ print("Could not enable faulthandler")
63
+
64
+
65
+ def _clear_imageio():
66
+ # Remove ourselves from sys.modules to force an import
67
+ for key in list(sys.modules.keys()):
68
+ if key.startswith("imageio"):
69
+ del sys.modules[key]
evalkit_tf446/lib/python3.10/site-packages/imageio/typing.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from typing import Union, BinaryIO
3
+ from pathlib import Path
4
+
5
+ try:
6
+ from numpy.typing import ArrayLike
7
+ except ImportError:
8
+ # numpy<1.20 fall back to using ndarray
9
+ from numpy import ndarray as ArrayLike
10
+
11
+ ImageResource = Union[str, bytes, BytesIO, Path, BinaryIO]
12
+
13
+
14
+ __all__ = [
15
+ "ArrayLike",
16
+ "ImageResource",
17
+ ]
evalkit_tf446/lib/python3.10/site-packages/imageio/v2.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ import re
5
+ import warnings
6
+ from numbers import Number
7
+ from pathlib import Path
8
+ from typing import Dict
9
+
10
+ import numpy as np
11
+
12
+ from imageio.core.legacy_plugin_wrapper import LegacyPlugin
13
+ from imageio.core.util import Array
14
+ from imageio.core.v3_plugin_api import PluginV3
15
+
16
+ from . import formats
17
+ from .config import known_extensions, known_plugins
18
+ from .core import RETURN_BYTES
19
+ from .core.imopen import imopen
20
+
21
+ MEMTEST_DEFAULT_MIM = "256MB"
22
+ MEMTEST_DEFAULT_MVOL = "1GB"
23
+
24
+
25
+ mem_re = re.compile(r"^(\d+\.?\d*)\s*([kKMGTPEZY]?i?)B?$")
26
+ sizes = {"": 1, None: 1}
27
+ for i, si in enumerate([""] + list("kMGTPEZY")):
28
+ sizes[si] = 1000**i
29
+ if si:
30
+ sizes[si.upper() + "i"] = 1024**i
31
+
32
+
33
+ def to_nbytes(arg, default=None):
34
+ if not arg:
35
+ arg = float("inf")
36
+
37
+ if arg is True:
38
+ arg = default
39
+
40
+ if isinstance(arg, Number):
41
+ return arg
42
+
43
+ match = mem_re.match(arg)
44
+ if match is None:
45
+ raise ValueError(
46
+ "Memory size could not be parsed "
47
+ "(is your capitalisation correct?): {}".format(arg)
48
+ )
49
+
50
+ num, unit = match.groups()
51
+
52
+ try:
53
+ return float(num) * sizes[unit]
54
+ except KeyError: # pragma: no cover
55
+ # Note: I don't think we can reach this
56
+ raise ValueError(
57
+ "Memory size unit not recognised "
58
+ "(is your capitalisation correct?): {}".format(unit)
59
+ )
60
+
61
+
62
+ def help(name=None):
63
+ """help(name=None)
64
+
65
+ Print the documentation of the format specified by name, or a list
66
+ of supported formats if name is omitted.
67
+
68
+ Parameters
69
+ ----------
70
+ name : str
71
+ Can be the name of a format, a filename extension, or a full
72
+ filename. See also the :doc:`formats page <../formats/index>`.
73
+ """
74
+ if not name:
75
+ print(formats)
76
+ else:
77
+ print(formats[name])
78
+
79
+
80
+ def decypher_format_arg(format_name: str) -> Dict[str, str]:
81
+ """Split format into plugin and format
82
+
83
+ The V2 API aliases plugins and supported formats. This function
84
+ splits these so that they can be fed separately to `iio.imopen`.
85
+
86
+ """
87
+
88
+ plugin = None
89
+ extension = None
90
+
91
+ if format_name is None:
92
+ pass # nothing to do
93
+ elif Path(format_name).suffix.lower() in known_extensions:
94
+ extension = Path(format_name).suffix.lower()
95
+ elif format_name in known_plugins:
96
+ plugin = format_name
97
+ elif format_name.upper() in known_plugins:
98
+ plugin = format_name.upper()
99
+ elif format_name.lower() in known_extensions:
100
+ extension = format_name.lower()
101
+ elif "." + format_name.lower() in known_extensions:
102
+ extension = "." + format_name.lower()
103
+ else:
104
+ raise IndexError(f"No format known by name `{plugin}`.")
105
+
106
+ return {"plugin": plugin, "extension": extension}
107
+
108
+
109
+ class LegacyReader:
110
+ def __init__(self, plugin_instance: PluginV3, **kwargs):
111
+ self.instance = plugin_instance
112
+ self.last_index = 0
113
+ self.closed = False
114
+
115
+ if (
116
+ type(self.instance).__name__ == "PillowPlugin"
117
+ and kwargs.get("pilmode") is not None
118
+ ):
119
+ kwargs["mode"] = kwargs["pilmode"]
120
+ del kwargs["pilmode"]
121
+
122
+ self.read_args = kwargs
123
+
124
+ def close(self):
125
+ if not self.closed:
126
+ self.instance.close()
127
+ self.closed = True
128
+
129
+ def __enter__(self):
130
+ return self
131
+
132
+ def __exit__(self, type, value, traceback):
133
+ self.close()
134
+
135
+ def __del__(self):
136
+ self.close()
137
+
138
+ @property
139
+ def request(self):
140
+ return self.instance.request
141
+
142
+ @property
143
+ def format(self):
144
+ raise TypeError("V3 Plugins don't have a format.")
145
+
146
+ def get_length(self):
147
+ return self.instance.properties(index=...).n_images
148
+
149
+ def get_data(self, index):
150
+ self.last_index = index
151
+ img = self.instance.read(index=index, **self.read_args)
152
+ metadata = self.instance.metadata(index=index, exclude_applied=False)
153
+ return Array(img, metadata)
154
+
155
+ def get_next_data(self):
156
+ return self.get_data(self.last_index + 1)
157
+
158
+ def set_image_index(self, index):
159
+ self.last_index = index - 1
160
+
161
+ def get_meta_data(self, index=None):
162
+ return self.instance.metadata(index=index, exclude_applied=False)
163
+
164
+ def iter_data(self):
165
+ for idx, img in enumerate(self.instance.iter()):
166
+ metadata = self.instance.metadata(index=idx, exclude_applied=False)
167
+ yield Array(img, metadata)
168
+
169
+ def __iter__(self):
170
+ return self.iter_data()
171
+
172
+ def __len__(self):
173
+ return self.get_length()
174
+
175
+
176
+ class LegacyWriter:
177
+ def __init__(self, plugin_instance: PluginV3, **kwargs):
178
+ self.instance = plugin_instance
179
+ self.last_index = 0
180
+ self.closed = False
181
+
182
+ if type(self.instance).__name__ == "PillowPlugin" and "pilmode" in kwargs:
183
+ kwargs["mode"] = kwargs["pilmode"]
184
+ del kwargs["pilmode"]
185
+
186
+ self.write_args = kwargs
187
+
188
+ def close(self):
189
+ if not self.closed:
190
+ self.instance.close()
191
+ self.closed = True
192
+
193
+ def __enter__(self):
194
+ return self
195
+
196
+ def __exit__(self, type, value, traceback):
197
+ self.close()
198
+
199
+ def __del__(self):
200
+ self.close()
201
+
202
+ @property
203
+ def request(self):
204
+ return self.instance.request
205
+
206
+ @property
207
+ def format(self):
208
+ raise TypeError("V3 Plugins don't have a format.")
209
+
210
+ def append_data(self, im, meta=None):
211
+ # TODO: write metadata in the future; there is currently no
212
+ # generic way to do this with v3 plugins :(
213
+ if meta is not None:
214
+ warnings.warn(
215
+ "V3 Plugins currently don't have a uniform way to"
216
+ " write metadata, so any metadata is ignored."
217
+ )
218
+
219
+ # total_meta = dict()
220
+ # if meta is None:
221
+ # meta = {}
222
+ # if hasattr(im, "meta") and isinstance(im.meta, dict):
223
+ # total_meta.update(im.meta)
224
+ # total_meta.update(meta)
225
+
226
+ return self.instance.write(im, **self.write_args)
227
+
228
+ def set_meta_data(self, meta):
229
+ # TODO: write metadata
230
+ raise NotImplementedError(
231
+ "V3 Plugins don't have a uniform way to write metadata (yet)."
232
+ )
233
+
234
+
235
+ def is_batch(ndimage):
236
+ if isinstance(ndimage, (list, tuple)):
237
+ return True
238
+
239
+ ndimage = np.asarray(ndimage)
240
+ if ndimage.ndim <= 2:
241
+ return False
242
+ elif ndimage.ndim == 3 and ndimage.shape[2] < 5:
243
+ return False
244
+
245
+ return True
246
+
247
+
248
+ def is_volume(ndimage):
249
+ ndimage = np.asarray(ndimage)
250
+ if not is_batch(ndimage):
251
+ return False
252
+
253
+ if ndimage.ndim == 3 and ndimage.shape[2] >= 5:
254
+ return True
255
+ elif ndimage.ndim == 4 and ndimage.shape[3] < 5:
256
+ return True
257
+ else:
258
+ return False
259
+
260
+
261
+ # Base functions that return a reader/writer
262
+
263
+
264
+ def get_reader(uri, format=None, mode="?", **kwargs):
265
+ """get_reader(uri, format=None, mode='?', **kwargs)
266
+
267
+ Returns a :class:`.Reader` object which can be used to read data
268
+ and meta data from the specified file.
269
+
270
+ Parameters
271
+ ----------
272
+ uri : {str, pathlib.Path, bytes, file}
273
+ The resource to load the image from, e.g. a filename, pathlib.Path,
274
+ http address or file object, see the docs for more info.
275
+ format : str
276
+ The format to use to read the file. By default imageio selects
277
+ the appropriate for you based on the filename and its contents.
278
+ mode : {'i', 'I', 'v', 'V', '?'}
279
+ Used to give the reader a hint on what the user expects (default "?"):
280
+ "i" for an image, "I" for multiple images, "v" for a volume,
281
+ "V" for multiple volumes, "?" for don't care.
282
+ kwargs : ...
283
+ Further keyword arguments are passed to the reader. See :func:`.help`
284
+ to see what arguments are available for a particular format.
285
+ """
286
+
287
+ imopen_args = decypher_format_arg(format)
288
+ imopen_args["legacy_mode"] = True
289
+
290
+ image_file = imopen(uri, "r" + mode, **imopen_args)
291
+
292
+ if isinstance(image_file, LegacyPlugin):
293
+ return image_file.legacy_get_reader(**kwargs)
294
+ else:
295
+ return LegacyReader(image_file, **kwargs)
296
+
297
+
298
+ def get_writer(uri, format=None, mode="?", **kwargs):
299
+ """get_writer(uri, format=None, mode='?', **kwargs)
300
+
301
+ Returns a :class:`.Writer` object which can be used to write data
302
+ and meta data to the specified file.
303
+
304
+ Parameters
305
+ ----------
306
+ uri : {str, pathlib.Path, file}
307
+ The resource to write the image to, e.g. a filename, pathlib.Path
308
+ or file object, see the docs for more info.
309
+ format : str
310
+ The format to use to write the file. By default imageio selects
311
+ the appropriate for you based on the filename.
312
+ mode : {'i', 'I', 'v', 'V', '?'}
313
+ Used to give the writer a hint on what the user expects (default '?'):
314
+ "i" for an image, "I" for multiple images, "v" for a volume,
315
+ "V" for multiple volumes, "?" for don't care.
316
+ kwargs : ...
317
+ Further keyword arguments are passed to the writer. See :func:`.help`
318
+ to see what arguments are available for a particular format.
319
+ """
320
+
321
+ imopen_args = decypher_format_arg(format)
322
+ imopen_args["legacy_mode"] = True
323
+
324
+ image_file = imopen(uri, "w" + mode, **imopen_args)
325
+ if isinstance(image_file, LegacyPlugin):
326
+ return image_file.legacy_get_writer(**kwargs)
327
+ else:
328
+ return LegacyWriter(image_file, **kwargs)
329
+
330
+
331
+ # Images
332
+
333
+
334
+ def imread(uri, format=None, **kwargs):
335
+ """imread(uri, format=None, **kwargs)
336
+
337
+ Reads an image from the specified file. Returns a numpy array, which
338
+ comes with a dict of meta data at its 'meta' attribute.
339
+
340
+ Note that the image data is returned as-is, and may not always have
341
+ a dtype of uint8 (and thus may differ from what e.g. PIL returns).
342
+
343
+ Parameters
344
+ ----------
345
+ uri : {str, pathlib.Path, bytes, file}
346
+ The resource to load the image from, e.g. a filename, pathlib.Path,
347
+ http address or file object, see the docs for more info.
348
+ format : str
349
+ The format to use to read the file. By default imageio selects
350
+ the appropriate for you based on the filename and its contents.
351
+ kwargs : ...
352
+ Further keyword arguments are passed to the reader. See :func:`.help`
353
+ to see what arguments are available for a particular format.
354
+ """
355
+
356
+ imopen_args = decypher_format_arg(format)
357
+ imopen_args["legacy_mode"] = True
358
+
359
+ with imopen(uri, "ri", **imopen_args) as file:
360
+ result = file.read(index=0, **kwargs)
361
+
362
+ return result
363
+
364
+
365
+ def imwrite(uri, im, format=None, **kwargs):
366
+ """imwrite(uri, im, format=None, **kwargs)
367
+
368
+ Write an image to the specified file.
369
+
370
+ Parameters
371
+ ----------
372
+ uri : {str, pathlib.Path, file}
373
+ The resource to write the image to, e.g. a filename, pathlib.Path
374
+ or file object, see the docs for more info.
375
+ im : numpy.ndarray
376
+ The image data. Must be NxM, NxMx3 or NxMx4.
377
+ format : str
378
+ The format to use to write the file. By default imageio selects
379
+ the appropriate for you based on the filename and its contents.
380
+ kwargs : ...
381
+ Further keyword arguments are passed to the writer. See :func:`.help`
382
+ to see what arguments are available for a particular format.
383
+ """
384
+
385
+ # Test image
386
+ imt = type(im)
387
+ im = np.asarray(im)
388
+ if not np.issubdtype(im.dtype, np.number):
389
+ raise ValueError("Image is not numeric, but {}.".format(imt.__name__))
390
+
391
+ if is_batch(im) or im.ndim < 2:
392
+ raise ValueError("Image must be 2D (grayscale, RGB, or RGBA).")
393
+
394
+ imopen_args = decypher_format_arg(format)
395
+ imopen_args["legacy_mode"] = True
396
+ with imopen(uri, "wi", **imopen_args) as file:
397
+ return file.write(im, **kwargs)
398
+
399
+
400
+ # Multiple images
401
+
402
+
403
+ def mimread(uri, format=None, memtest=MEMTEST_DEFAULT_MIM, **kwargs):
404
+ """mimread(uri, format=None, memtest="256MB", **kwargs)
405
+
406
+ Reads multiple images from the specified file. Returns a list of
407
+ numpy arrays, each with a dict of meta data at its 'meta' attribute.
408
+
409
+ Parameters
410
+ ----------
411
+ uri : {str, pathlib.Path, bytes, file}
412
+ The resource to load the images from, e.g. a filename,pathlib.Path,
413
+ http address or file object, see the docs for more info.
414
+ format : str
415
+ The format to use to read the file. By default imageio selects
416
+ the appropriate for you based on the filename and its contents.
417
+ memtest : {bool, int, float, str}
418
+ If truthy, this function will raise an error if the resulting
419
+ list of images consumes greater than the amount of memory specified.
420
+ This is to protect the system from using so much memory that it needs
421
+ to resort to swapping, and thereby stall the computer. E.g.
422
+ ``mimread('hunger_games.avi')``.
423
+
424
+ If the argument is a number, that will be used as the threshold number
425
+ of bytes.
426
+
427
+ If the argument is a string, it will be interpreted as a number of bytes with
428
+ SI/IEC prefixed units (e.g. '1kB', '250MiB', '80.3YB').
429
+
430
+ - Units are case sensitive
431
+ - k, M etc. represent a 1000-fold change, where Ki, Mi etc. represent 1024-fold
432
+ - The "B" is optional, but if present, must be capitalised
433
+
434
+ If the argument is True, the default will be used, for compatibility reasons.
435
+
436
+ Default: '256MB'
437
+ kwargs : ...
438
+ Further keyword arguments are passed to the reader. See :func:`.help`
439
+ to see what arguments are available for a particular format.
440
+ """
441
+
442
+ # used for mimread and mvolread
443
+ nbyte_limit = to_nbytes(memtest, MEMTEST_DEFAULT_MIM)
444
+
445
+ images = list()
446
+ nbytes = 0
447
+
448
+ imopen_args = decypher_format_arg(format)
449
+ imopen_args["legacy_mode"] = True
450
+ with imopen(uri, "rI", **imopen_args) as file:
451
+ for image in file.iter(**kwargs):
452
+ images.append(image)
453
+ nbytes += image.nbytes
454
+ if nbytes > nbyte_limit:
455
+ raise RuntimeError(
456
+ "imageio.mimread() has read over {}B of "
457
+ "image data.\nStopped to avoid memory problems."
458
+ " Use imageio.get_reader(), increase threshold, or memtest=False".format(
459
+ int(nbyte_limit)
460
+ )
461
+ )
462
+
463
+ if len(images) == 1 and is_batch(images[0]):
464
+ images = [*images[0]]
465
+
466
+ return images
467
+
468
+
469
+ def mimwrite(uri, ims, format=None, **kwargs):
470
+ """mimwrite(uri, ims, format=None, **kwargs)
471
+
472
+ Write multiple images to the specified file.
473
+
474
+ Parameters
475
+ ----------
476
+ uri : {str, pathlib.Path, file}
477
+ The resource to write the images to, e.g. a filename, pathlib.Path
478
+ or file object, see the docs for more info.
479
+ ims : sequence of numpy arrays
480
+ The image data. Each array must be NxM, NxMx3 or NxMx4.
481
+ format : str
482
+ The format to use to read the file. By default imageio selects
483
+ the appropriate for you based on the filename and its contents.
484
+ kwargs : ...
485
+ Further keyword arguments are passed to the writer. See :func:`.help`
486
+ to see what arguments are available for a particular format.
487
+ """
488
+
489
+ if not is_batch(ims):
490
+ raise ValueError("Image data must be a sequence of ndimages.")
491
+
492
+ imopen_args = decypher_format_arg(format)
493
+ imopen_args["legacy_mode"] = True
494
+ with imopen(uri, "wI", **imopen_args) as file:
495
+ return file.write(ims, is_batch=True, **kwargs)
496
+
497
+
498
+ # Volumes
499
+
500
+
501
+ def volread(uri, format=None, **kwargs):
502
+ """volread(uri, format=None, **kwargs)
503
+
504
+ Reads a volume from the specified file. Returns a numpy array, which
505
+ comes with a dict of meta data at its 'meta' attribute.
506
+
507
+ Parameters
508
+ ----------
509
+ uri : {str, pathlib.Path, bytes, file}
510
+ The resource to load the volume from, e.g. a filename, pathlib.Path,
511
+ http address or file object, see the docs for more info.
512
+ format : str
513
+ The format to use to read the file. By default imageio selects
514
+ the appropriate for you based on the filename and its contents.
515
+ kwargs : ...
516
+ Further keyword arguments are passed to the reader. See :func:`.help`
517
+ to see what arguments are available for a particular format.
518
+ """
519
+
520
+ imopen_args = decypher_format_arg(format)
521
+ imopen_args["legacy_mode"] = True
522
+ with imopen(uri, "rv", **imopen_args) as file:
523
+ return file.read(index=0, **kwargs)
524
+
525
+
526
+ def volwrite(uri, im, format=None, **kwargs):
527
+ """volwrite(uri, vol, format=None, **kwargs)
528
+
529
+ Write a volume to the specified file.
530
+
531
+ Parameters
532
+ ----------
533
+ uri : {str, pathlib.Path, file}
534
+ The resource to write the image to, e.g. a filename, pathlib.Path
535
+ or file object, see the docs for more info.
536
+ vol : numpy.ndarray
537
+ The image data. Must be NxMxL (or NxMxLxK if each voxel is a tuple).
538
+ format : str
539
+ The format to use to read the file. By default imageio selects
540
+ the appropriate for you based on the filename and its contents.
541
+ kwargs : ...
542
+ Further keyword arguments are passed to the writer. See :func:`.help`
543
+ to see what arguments are available for a particular format.
544
+ """
545
+
546
+ # Test image
547
+ im = np.asarray(im)
548
+ if not is_volume(im):
549
+ raise ValueError("Image must be 3D, or 4D if each voxel is a tuple.")
550
+
551
+ imopen_args = decypher_format_arg(format)
552
+ imopen_args["legacy_mode"] = True
553
+
554
+ with imopen(uri, "wv", **imopen_args) as file:
555
+ return file.write(im, is_batch=False, **kwargs)
556
+
557
+
558
+ # Multiple volumes
559
+
560
+
561
+ def mvolread(uri, format=None, memtest=MEMTEST_DEFAULT_MVOL, **kwargs):
562
+ """mvolread(uri, format=None, memtest='1GB', **kwargs)
563
+
564
+ Reads multiple volumes from the specified file. Returns a list of
565
+ numpy arrays, each with a dict of meta data at its 'meta' attribute.
566
+
567
+ Parameters
568
+ ----------
569
+ uri : {str, pathlib.Path, bytes, file}
570
+ The resource to load the volumes from, e.g. a filename, pathlib.Path,
571
+ http address or file object, see the docs for more info.
572
+ format : str
573
+ The format to use to read the file. By default imageio selects
574
+ the appropriate for you based on the filename and its contents.
575
+ memtest : {bool, int, float, str}
576
+ If truthy, this function will raise an error if the resulting
577
+ list of images consumes greater than the amount of memory specified.
578
+ This is to protect the system from using so much memory that it needs
579
+ to resort to swapping, and thereby stall the computer. E.g.
580
+ ``mimread('hunger_games.avi')``.
581
+
582
+ If the argument is a number, that will be used as the threshold number
583
+ of bytes.
584
+
585
+ If the argument is a string, it will be interpreted as a number of bytes with
586
+ SI/IEC prefixed units (e.g. '1kB', '250MiB', '80.3YB').
587
+
588
+ - Units are case sensitive
589
+ - k, M etc. represent a 1000-fold change, where Ki, Mi etc. represent 1024-fold
590
+ - The "B" is optional, but if present, must be capitalised
591
+
592
+ If the argument is True, the default will be used, for compatibility reasons.
593
+
594
+ Default: '1GB'
595
+ kwargs : ...
596
+ Further keyword arguments are passed to the reader. See :func:`.help`
597
+ to see what arguments are available for a particular format.
598
+ """
599
+
600
+ # used for mimread and mvolread
601
+ nbyte_limit = to_nbytes(memtest, MEMTEST_DEFAULT_MVOL)
602
+
603
+ images = list()
604
+ nbytes = 0
605
+ imopen_args = decypher_format_arg(format)
606
+ imopen_args["legacy_mode"] = True
607
+ with imopen(uri, "rV", **imopen_args) as file:
608
+ for image in file.iter(**kwargs):
609
+ images.append(image)
610
+ nbytes += image.nbytes
611
+ if nbytes > nbyte_limit:
612
+ raise RuntimeError(
613
+ "imageio.mimread() has read over {}B of "
614
+ "image data.\nStopped to avoid memory problems."
615
+ " Use imageio.get_reader(), increase threshold, or memtest=False".format(
616
+ int(nbyte_limit)
617
+ )
618
+ )
619
+
620
+ return images
621
+
622
+
623
+ def mvolwrite(uri, ims, format=None, **kwargs):
624
+ """mvolwrite(uri, vols, format=None, **kwargs)
625
+
626
+ Write multiple volumes to the specified file.
627
+
628
+ Parameters
629
+ ----------
630
+ uri : {str, pathlib.Path, file}
631
+ The resource to write the volumes to, e.g. a filename, pathlib.Path
632
+ or file object, see the docs for more info.
633
+ ims : sequence of numpy arrays
634
+ The image data. Each array must be NxMxL (or NxMxLxK if each
635
+ voxel is a tuple).
636
+ format : str
637
+ The format to use to read the file. By default imageio selects
638
+ the appropriate for you based on the filename and its contents.
639
+ kwargs : ...
640
+ Further keyword arguments are passed to the writer. See :func:`.help`
641
+ to see what arguments are available for a particular format.
642
+ """
643
+
644
+ for im in ims:
645
+ if not is_volume(im):
646
+ raise ValueError("Image must be 3D, or 4D if each voxel is a tuple.")
647
+
648
+ imopen_args = decypher_format_arg(format)
649
+ imopen_args["legacy_mode"] = True
650
+ with imopen(uri, "wV", **imopen_args) as file:
651
+ return file.write(ims, is_batch=True, **kwargs)
652
+
653
+
654
+ # aliases
655
+ read = get_reader
656
+ save = get_writer
657
+ imsave = imwrite
658
+ mimsave = mimwrite
659
+ volsave = volwrite
660
+ mvolsave = mvolwrite
661
+
662
+ __all__ = [
663
+ "imread",
664
+ "mimread",
665
+ "volread",
666
+ "mvolread",
667
+ "imwrite",
668
+ "mimwrite",
669
+ "volwrite",
670
+ "mvolwrite",
671
+ # misc
672
+ "help",
673
+ "get_reader",
674
+ "get_writer",
675
+ "RETURN_BYTES",
676
+ ]
evalkit_tf446/lib/python3.10/site-packages/imageio/v2.pyi ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ from typing import Dict, Literal, Union, List, overload
5
+
6
+ import numpy as np
7
+
8
+ from .core.imopen import imopen
9
+ from .core import RETURN_BYTES, Array
10
+ from .typing import ImageResource, ArrayLike
11
+ from .core.format import Format
12
+
13
+ MEMTEST_DEFAULT_MIM = "256MB"
14
+ MEMTEST_DEFAULT_MVOL = "1GB"
15
+
16
+ def to_nbytes(arg: float = None, default=None) -> float: ...
17
+ def help(name=None) -> None: ...
18
+ def decypher_format_arg(format_name: Union[str, None]) -> Dict[str, str]: ...
19
+ def get_reader(
20
+ uri: ImageResource, format: Format = None, mode: str = "?", **kwargs
21
+ ) -> Format.Reader: ...
22
+ def get_writer(
23
+ uri: ImageResource, format: Format = None, mode: str = "?", **kwargs
24
+ ) -> Format.Writer: ...
25
+ def imread(uri: ImageResource, format: Format = None, **kwargs) -> Array: ...
26
+ @overload
27
+ def imwrite(
28
+ uri: Literal["<bytes>"], im: ArrayLike, format: Format = None, **kwargs
29
+ ) -> bytes: ...
30
+ @overload
31
+ def imwrite(
32
+ uri: ImageResource, im: ArrayLike, format: Format = None, **kwargs
33
+ ) -> None: ...
34
+ def mimread(
35
+ uri: ImageResource, format: Format = None, memtest=MEMTEST_DEFAULT_MIM, **kwargs
36
+ ) -> List[Array]: ...
37
+ @overload
38
+ def mimwrite(
39
+ uri: Literal["<bytes>"], ims: List[ArrayLike], format: Format = None, **kwargs
40
+ ) -> bytes: ...
41
+ @overload
42
+ def mimwrite(
43
+ uri: ImageResource, ims: List[ArrayLike], format: Format = None, **kwargs
44
+ ) -> None: ...
45
+ def volread(uri: ImageResource, format: Format = None, **kwargs) -> Array: ...
46
+ @overload
47
+ def volwrite(
48
+ uri: Literal["<bytes>"], im: ArrayLike, format: Format = None, **kwargs
49
+ ) -> bytes: ...
50
+ @overload
51
+ def volwrite(
52
+ uri: ImageResource, im: ArrayLike, format: Format = None, **kwargs
53
+ ) -> None: ...
54
+ def mvolread(
55
+ uri: ImageResource,
56
+ format: Format = None,
57
+ memtest: float = MEMTEST_DEFAULT_MVOL,
58
+ **kwargs
59
+ ) -> List[Array]: ...
60
+ @overload
61
+ def mvolwrite(
62
+ uri: Literal["<bytes>"], ims: List[ArrayLike], format: Format = None, **kwargs
63
+ ) -> bytes: ...
64
+ @overload
65
+ def mvolwrite(
66
+ uri: ImageResource, ims: List[ArrayLike], format: Format = None, **kwargs
67
+ ) -> None: ...
68
+
69
+ # aliases
70
+ read = get_reader
71
+ save = get_writer
72
+ imsave = imwrite
73
+ mimsave = mimwrite
74
+ volsave = volwrite
75
+ mvolsave = mvolwrite
evalkit_tf446/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"]
evalkit_tf446/lib/python3.10/site-packages/imageio/v3.pyi ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Iterator, List, Literal, Optional, Union, overload
2
+
3
+ import numpy as np
4
+
5
+ from .core.imopen import imopen as imopen
6
+ from .core.v3_plugin_api import ImageProperties
7
+ from .typing import ArrayLike, ImageResource
8
+
9
+ def imread(
10
+ uri: ImageResource,
11
+ *,
12
+ index: Optional[int] = 0,
13
+ plugin: str = None,
14
+ extension: str = None,
15
+ format_hint: str = None,
16
+ **kwargs
17
+ ) -> np.ndarray: ...
18
+ def imiter(
19
+ uri: ImageResource,
20
+ *,
21
+ plugin: str = None,
22
+ extension: str = None,
23
+ format_hint: str = None,
24
+ **kwargs
25
+ ) -> Iterator[np.ndarray]: ...
26
+ @overload
27
+ def imwrite(
28
+ uri: Literal["<bytes>"],
29
+ image: Union[ArrayLike, List[ArrayLike]],
30
+ *,
31
+ plugin: str = None,
32
+ extension: str = None,
33
+ format_hint: str = None,
34
+ **kwargs
35
+ ) -> bytes: ...
36
+ @overload
37
+ def imwrite(
38
+ uri: ImageResource,
39
+ image: Union[ArrayLike, List[ArrayLike]],
40
+ *,
41
+ plugin: str = None,
42
+ extension: str = None,
43
+ format_hint: str = None,
44
+ **kwargs
45
+ ) -> None: ...
46
+ def improps(
47
+ uri,
48
+ *,
49
+ index: Optional[int] = 0,
50
+ plugin: str = None,
51
+ extension: str = None,
52
+ **kwargs
53
+ ) -> ImageProperties: ...
54
+ def immeta(
55
+ uri,
56
+ *,
57
+ index: Optional[int] = 0,
58
+ plugin: str = None,
59
+ extension: str = None,
60
+ exclude_applied: bool = True,
61
+ **kwargs
62
+ ) -> Dict[str, Any]: ...
evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.97 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc ADDED
Binary file (41.4 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-310.pyc ADDED
Binary file (30.2 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-310.pyc ADDED
Binary file (25.2 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-310.pyc ADDED
Binary file (14.3 kB). View file