imicpe 0.0.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- imicpe-0.0.9/DESCRIPTION.md +29 -0
- imicpe-0.0.9/LICENSE +21 -0
- imicpe-0.0.9/PKG-INFO +44 -0
- imicpe-0.0.9/README.md +93 -0
- imicpe-0.0.9/pyproject.toml +36 -0
- imicpe-0.0.9/setup.cfg +4 -0
- imicpe-0.0.9/src/imicpe/__init__.py +0 -0
- imicpe-0.0.9/src/imicpe/optim/__init__.py +8 -0
- imicpe-0.0.9/src/imicpe/optim/metrics.py +9 -0
- imicpe-0.0.9/src/imicpe/optim/operators.py +369 -0
- imicpe-0.0.9/src/imicpe/optim/pnnDataset.py +122 -0
- imicpe-0.0.9/src/imicpe/optim/pnnTrainer.py +137 -0
- imicpe-0.0.9/src/imicpe/optim/pnnUtils.py +52 -0
- imicpe-0.0.9/src/imicpe.egg-info/PKG-INFO +44 -0
- imicpe-0.0.9/src/imicpe.egg-info/SOURCES.txt +15 -0
- imicpe-0.0.9/src/imicpe.egg-info/dependency_links.txt +1 -0
- imicpe-0.0.9/src/imicpe.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
|
|
2
|
+
A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
|
|
3
|
+
Developped and maintained for teaching usage only!
|
|
4
|
+
|
|
5
|
+
# Installation
|
|
6
|
+
|
|
7
|
+
## In a Jupyter Notebook
|
|
8
|
+
|
|
9
|
+
```!pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
10
|
+
|
|
11
|
+
## In a local environment
|
|
12
|
+
|
|
13
|
+
```pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
14
|
+
|
|
15
|
+
# Usage example
|
|
16
|
+
|
|
17
|
+
The example below uses the kurtosis method available in the `tsa` subpackage of `msicpe`.
|
|
18
|
+
It requires `numpy.randn` to generate a gaussian distribution of N points.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import numpy as np
|
|
22
|
+
from msicpe.tsa import kurtosis
|
|
23
|
+
N=10000
|
|
24
|
+
|
|
25
|
+
x=np.randn(1,N)
|
|
26
|
+
kurt=kurtosis(x)
|
|
27
|
+
|
|
28
|
+
print(kurt)
|
|
29
|
+
```
|
imicpe-0.0.9/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [year] [fullname]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
imicpe-0.0.9/PKG-INFO
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: imicpe
|
|
3
|
+
Version: 0.0.9
|
|
4
|
+
Summary: Toolbox for Maths,Signal,Image Teaching @ CPE
|
|
5
|
+
Author-email: Marion Foare <marion.foare@cpe.fr>, Eric Van Reeth <eric.vanreeth@cpe.fr>, Arthur Gautheron <arthur.gautheron@cpe.fr>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Project-URL: Homepage, https://www.cpe.fr
|
|
8
|
+
Project-URL: Documentation, https://toolbox-imi-cpe-msi-1bcfcdd75992c038486502447f7f6937f3492f60127.pages.in2p3.fr/
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
|
|
18
|
+
Developped and maintained for teaching usage only!
|
|
19
|
+
|
|
20
|
+
# Installation
|
|
21
|
+
|
|
22
|
+
## In a Jupyter Notebook
|
|
23
|
+
|
|
24
|
+
```!pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
25
|
+
|
|
26
|
+
## In a local environment
|
|
27
|
+
|
|
28
|
+
```pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
29
|
+
|
|
30
|
+
# Usage example
|
|
31
|
+
|
|
32
|
+
The example below uses the kurtosis method available in the `tsa` subpackage of `msicpe`.
|
|
33
|
+
It requires `numpy.randn` to generate a gaussian distribution of N points.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import numpy as np
|
|
37
|
+
from msicpe.tsa import kurtosis
|
|
38
|
+
N=10000
|
|
39
|
+
|
|
40
|
+
x=np.randn(1,N)
|
|
41
|
+
kurt=kurtosis(x)
|
|
42
|
+
|
|
43
|
+
print(kurt)
|
|
44
|
+
```
|
imicpe-0.0.9/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# toolbox
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
## Getting started
|
|
6
|
+
|
|
7
|
+
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
|
8
|
+
|
|
9
|
+
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
|
10
|
+
|
|
11
|
+
## Add your files
|
|
12
|
+
|
|
13
|
+
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
|
14
|
+
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
cd existing_repo
|
|
18
|
+
git remote add origin https://gitlab.in2p3.fr/cpe/msi/toolbox.git
|
|
19
|
+
git branch -M main
|
|
20
|
+
git push -uf origin main
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Integrate with your tools
|
|
24
|
+
|
|
25
|
+
- [ ] [Set up project integrations](https://gitlab.in2p3.fr/cpe/msi/toolbox/-/settings/integrations)
|
|
26
|
+
|
|
27
|
+
## Collaborate with your team
|
|
28
|
+
|
|
29
|
+
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
|
30
|
+
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
|
31
|
+
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
|
32
|
+
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
|
33
|
+
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
|
34
|
+
|
|
35
|
+
## Test and Deploy
|
|
36
|
+
|
|
37
|
+
Use the built-in continuous integration in GitLab.
|
|
38
|
+
|
|
39
|
+
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
|
40
|
+
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
|
41
|
+
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
|
42
|
+
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
|
43
|
+
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
|
44
|
+
|
|
45
|
+
***
|
|
46
|
+
|
|
47
|
+
# Editing this README
|
|
48
|
+
|
|
49
|
+
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
|
50
|
+
|
|
51
|
+
## Suggestions for a good README
|
|
52
|
+
|
|
53
|
+
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
|
54
|
+
|
|
55
|
+
## Name
|
|
56
|
+
Choose a self-explaining name for your project.
|
|
57
|
+
|
|
58
|
+
## Description
|
|
59
|
+
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
|
60
|
+
|
|
61
|
+
## Badges
|
|
62
|
+
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
|
63
|
+
|
|
64
|
+
## Visuals
|
|
65
|
+
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
|
72
|
+
|
|
73
|
+
## Support
|
|
74
|
+
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
|
75
|
+
|
|
76
|
+
## Roadmap
|
|
77
|
+
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
|
78
|
+
|
|
79
|
+
## Contributing
|
|
80
|
+
State if you are open to contributions and what your requirements are for accepting them.
|
|
81
|
+
|
|
82
|
+
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
|
83
|
+
|
|
84
|
+
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
|
85
|
+
|
|
86
|
+
## Authors and acknowledgment
|
|
87
|
+
Show your appreciation to those who have contributed to the project.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
For open source projects, say how it is licensed.
|
|
91
|
+
|
|
92
|
+
## Project status
|
|
93
|
+
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
|
|
2
|
+
#dynamic = ["version"]
|
|
3
|
+
|
|
4
|
+
[build-system]
|
|
5
|
+
requires = ["setuptools>=65", "setuptools_scm>=8.0","wheel"]
|
|
6
|
+
build-backend = "setuptools.build_meta"
|
|
7
|
+
|
|
8
|
+
[tool.setuptools.packages.find]
|
|
9
|
+
where = ["src"]
|
|
10
|
+
|
|
11
|
+
[tool.setuptools.package-data]
|
|
12
|
+
mypkg = ["*.txt", "*.mat"]
|
|
13
|
+
|
|
14
|
+
#[tool.setuptools_scm]
|
|
15
|
+
|
|
16
|
+
[project]
|
|
17
|
+
version="0.0.9"
|
|
18
|
+
name = "imicpe"
|
|
19
|
+
authors = [
|
|
20
|
+
{ name="Marion Foare", email="marion.foare@cpe.fr" },
|
|
21
|
+
{ name="Eric Van Reeth", email="eric.vanreeth@cpe.fr" },
|
|
22
|
+
{ name="Arthur Gautheron", email="arthur.gautheron@cpe.fr" },
|
|
23
|
+
]
|
|
24
|
+
description = "Toolbox for Maths,Signal,Image Teaching @ CPE"
|
|
25
|
+
readme = {file = "DESCRIPTION.md", content-type = "text/markdown"}
|
|
26
|
+
license = {text = "MIT License"}
|
|
27
|
+
requires-python = ">=3.8"
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"License :: OSI Approved :: MIT License",
|
|
31
|
+
"Operating System :: OS Independent",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://www.cpe.fr"
|
|
36
|
+
Documentation = "https://toolbox-imi-cpe-msi-1bcfcdd75992c038486502447f7f6937f3492f60127.pages.in2p3.fr/"
|
imicpe-0.0.9/setup.cfg
ADDED
|
File without changes
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from .metrics import mse, snr
|
|
2
|
+
from .operators import Id, D, Dt, L, Lt, generateDiff3D, generatePSF, A, At, S, St, opNorm, matNorm
|
|
3
|
+
from .pnnDataset import BSDSDataset, NoisyDataset
|
|
4
|
+
from .pnnTrainer import Trainer, Metrics
|
|
5
|
+
from .pnnUtils import chooseDevice, torchImg2Numpy, getData
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
cameraman = os.path.join(os.path.dirname(__file__), 'cameraman.tif')
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import ndimage
|
|
4
|
+
import igl
|
|
5
|
+
|
|
6
|
+
############################################################
|
|
7
|
+
## identity operator
|
|
8
|
+
############################################################
|
|
9
|
+
def Id(x):
|
|
10
|
+
"""
|
|
11
|
+
Id Opérateur identité
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
X (numpy.ndarray) signal 1D
|
|
15
|
+
ou: image non vectorisée 2D
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
(numpy.ndarray) X
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
return x
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
############################################################
|
|
25
|
+
## differential forward and backward operators
|
|
26
|
+
############################################################
|
|
27
|
+
# gradient
|
|
28
|
+
def D(x):
|
|
29
|
+
"""
|
|
30
|
+
D Calcule le gradient par différences finies à droite.
|
|
31
|
+
Autrement dit, D(x) calcule le produit matriciel Dx.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
X (numpy.ndarray) signal 1D
|
|
35
|
+
ou: image non vectorisée 2D
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
(numpy.ndarray) Gradient de X
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
if x.ndim == 1:
|
|
42
|
+
grad = np.concatenate((x[1:] - x[:-1], [0]))/2.
|
|
43
|
+
|
|
44
|
+
elif x.ndim == 2:
|
|
45
|
+
sz = x.shape
|
|
46
|
+
Dx_im = np.concatenate(( x[:,1:] - x[:,:-1] , np.zeros((sz[0],1)) ), axis=1)/ 2.
|
|
47
|
+
Dy_im = np.concatenate(( x[1:,:] - x[:-1,:] , np.zeros((1,sz[1])) ), axis=0)/ 2.
|
|
48
|
+
|
|
49
|
+
grad = np.array([Dx_im,Dy_im])
|
|
50
|
+
return grad
|
|
51
|
+
|
|
52
|
+
def Dt(x):
|
|
53
|
+
"""
|
|
54
|
+
Dt Calcule l’adjoint gradient par différences finies à droite.
|
|
55
|
+
Autrement dit, Dt(x) calcule le produit matriciel D'x.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
X (numpy.ndarray) signal 1D
|
|
59
|
+
ou: image non vectorisée 2D
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
(numpy.ndarray) Divergence de X
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
if x.ndim == 1:
|
|
66
|
+
div = - np.concatenate(([x[0]], x[1:-1] - x[:-2], [-x[-2]])) /2.
|
|
67
|
+
|
|
68
|
+
elif x.ndim == 3:
|
|
69
|
+
x1 = x[0]
|
|
70
|
+
x2 = x[1]
|
|
71
|
+
div = - np.concatenate((x1[:,[0]], x1[:,1:-1] - x1[:,:-2], -x1[:,[-2]]), axis=1) /2. \
|
|
72
|
+
- np.concatenate((x2[[0],:], x2[1:-1,:] - x2[:-2,:], -x2[[-2],:]), axis=0) /2.
|
|
73
|
+
return div
|
|
74
|
+
|
|
75
|
+
# laplacian
|
|
76
|
+
def L(x):
|
|
77
|
+
"""
|
|
78
|
+
L Calcule la dérivée seconde d’un signal, ou le laplacien dans le cas d’une image.
|
|
79
|
+
Autrement dit, L(x) calcule le produit matriciel Lx.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
X (numpy.ndarray) signal 1D
|
|
83
|
+
ou: image non vectorisée 2D
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
(numpy.ndarray) Laplacien de X
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
if x.ndim == 1:
|
|
90
|
+
ker = np.array([1, -2, 1])
|
|
91
|
+
#lap = np.convolve(x,ker,'same')
|
|
92
|
+
lap = ndimage.convolve1d(x,ker,mode='nearest')
|
|
93
|
+
elif x.ndim == 2:
|
|
94
|
+
ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
|
|
95
|
+
#ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
|
|
96
|
+
lap = ndimage.convolve(x,ker,mode='nearest')
|
|
97
|
+
return lap
|
|
98
|
+
|
|
99
|
+
def Lt(x):
|
|
100
|
+
"""
|
|
101
|
+
Lt Calcule l’adjoint du laplacien.
|
|
102
|
+
Autrement dit, Lt(x) calcule le produit matriciel L'x.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
X (numpy.ndarray) signal 1D
|
|
106
|
+
ou: image non vectorisée 2D
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
(numpy.ndarray) Adjoint du Laplacien de X
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
if x.ndim == 1:
|
|
113
|
+
ker = np.array([1, -2, 1])
|
|
114
|
+
#lap = np.correlate(x,ker,'same')
|
|
115
|
+
lap = ndimage.correlate1d(x,ker,mode='nearest')
|
|
116
|
+
elif x.ndim == 2:
|
|
117
|
+
ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
|
|
118
|
+
#ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
|
|
119
|
+
lap = ndimage.correlate(x,ker,mode='nearest')
|
|
120
|
+
return lap
|
|
121
|
+
|
|
122
|
+
def generateDiff3D(vert, faces, dtype):
|
|
123
|
+
"""
|
|
124
|
+
generateDiff3D Génère la matrice de différentiation de type DTYPE (ordre 1 ou 2) en 3D
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
VERT (numpy.ndarray) matrice Nx3 dont la i-ème ligne correspond au vecteur
|
|
128
|
+
de coordonnées (X,Y,Z) du i-ème point du maillage
|
|
129
|
+
FACES (numpy.ndarray) matrice Nx3 dont la i-ème ligne donne les numéros des
|
|
130
|
+
3 points composant un triangle du maillage
|
|
131
|
+
DTYPE(str) 'gradient', 'laplacian'
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
(numpy.ndarray) matrice 3D de différentiation de type DTYPE
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
if dtype == 'gradient':
|
|
138
|
+
matG = igl.grad(vert, faces)
|
|
139
|
+
elif dtype == 'laplacien':
|
|
140
|
+
matG = igl.cotmatrix(vert, faces)
|
|
141
|
+
|
|
142
|
+
return (matG/np.amax(matG)).toarray()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
############################################################
|
|
147
|
+
## blurring operators
|
|
148
|
+
############################################################
|
|
149
|
+
def generatePSF(dim,blurtype,kernelSize):
|
|
150
|
+
"""
|
|
151
|
+
generatePSF Génère le noyau de convolution d’un flou de dimension DIM, de type BLURTYPE,
|
|
152
|
+
et de taille KERNELSIZE.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
DIM (str) ’1D’ ou ’2D’
|
|
156
|
+
BLURTYPE (str) ’none’, ’gaussian’ ou ’uniform’
|
|
157
|
+
KERNELSIZE (int) entier impair
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
(numpy.ndarray) Noyau de convolution
|
|
161
|
+
|
|
162
|
+
-> voir les fonctions A(x,h) et At(x,h).
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
# compute kernel
|
|
166
|
+
if blurtype == 'none':
|
|
167
|
+
h = np.array([1.])
|
|
168
|
+
|
|
169
|
+
elif blurtype == 'gaussian':
|
|
170
|
+
std = kernelSize/6
|
|
171
|
+
x = np.linspace(-(kernelSize-1)/2, (kernelSize-1)/2, kernelSize)
|
|
172
|
+
arg = -x**2/(2*std**2)
|
|
173
|
+
h = np.exp(arg)
|
|
174
|
+
|
|
175
|
+
elif blurtype == 'uniform':
|
|
176
|
+
h = np.ones(kernelSize)
|
|
177
|
+
|
|
178
|
+
# kernel normalization
|
|
179
|
+
h = h/sum(h)
|
|
180
|
+
|
|
181
|
+
# return kernel
|
|
182
|
+
if dim == '1D':
|
|
183
|
+
ker = h
|
|
184
|
+
elif dim == '2D':
|
|
185
|
+
ker = np.tensordot(h,h, axes=0)
|
|
186
|
+
|
|
187
|
+
return ker
|
|
188
|
+
|
|
189
|
+
def A(x,psf):
|
|
190
|
+
"""
|
|
191
|
+
A Permet de flouter l’image X par un flou de noyau PSF.
|
|
192
|
+
Autrement dit, A(x,h) calcule le produit de convolution h*x, ou de manière équivalente, calcule
|
|
193
|
+
le produit matriciel Hx.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
X (numpy.ndarray) signal 1D
|
|
197
|
+
ou: image non vectorisée 2D
|
|
198
|
+
PSF (numpy.ndarray) doit être générée à partir de la fonction generatePSF
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
(numpy.ndarray) Convolution de X par le noyau PSF
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
if x.ndim == 1:
|
|
205
|
+
b = np.convolve(x,psf,'same')
|
|
206
|
+
elif x.ndim == 2:
|
|
207
|
+
b = ndimage.convolve(x,psf,mode='nearest')
|
|
208
|
+
|
|
209
|
+
return b
|
|
210
|
+
|
|
211
|
+
def At(x,psf):
|
|
212
|
+
"""
|
|
213
|
+
At Permet de flouter l’image X par un flou de noyau la transposée de PSF.
|
|
214
|
+
Autrement dit, A(x,h) calcule le produit de convolution h'*x, ou de manière équivalente, calcule
|
|
215
|
+
le produit matriciel H'x.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
X (numpy.ndarray) signal 1D
|
|
219
|
+
ou: image non vectorisée 2D
|
|
220
|
+
PSF (numpy.ndarray) doit être générée à partir de la fonction generatePSF
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
(numpy.ndarray) Correlation de X par le noyau PSF
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
if x.ndim == 1:
|
|
227
|
+
b = np.correlate(x,psf,'same')
|
|
228
|
+
elif x.ndim == 2:
|
|
229
|
+
b = ndimage.correlate(x,psf,mode='nearest')
|
|
230
|
+
|
|
231
|
+
return b
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
############################################################
|
|
236
|
+
## TP3 - cartoon + texture decomposition operators (only 2D)
|
|
237
|
+
############################################################
|
|
238
|
+
def S(x):
|
|
239
|
+
"""
|
|
240
|
+
S Convolue X avec un noyau KER.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
X (numpy.ndarray) image non vectorisée 2D
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
(numpy.ndarray) Convolution de X par le noyau KER
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
h,w = x.shape
|
|
250
|
+
|
|
251
|
+
ox = np.linspace(-w/2+1/2, w/2-1/2, w)
|
|
252
|
+
oy = np.linspace(-h/2+1/2, h/2-1/2, h)
|
|
253
|
+
X,Y = np.meshgrid(ox, oy)
|
|
254
|
+
dist = np.sqrt(X**2/w**2 + Y**2/h**2); # anisotropic distance
|
|
255
|
+
n = 5
|
|
256
|
+
fc = 1/3 # in [0,1] since dist is normalized
|
|
257
|
+
ker = 1./(1 + (dist/fc)**(2*n))
|
|
258
|
+
|
|
259
|
+
imf = np.real(np.fft.ifft2(np.fft.ifftshift(ker*np.fft.fftshift(np.fft.fft2(x)))))
|
|
260
|
+
|
|
261
|
+
return imf
|
|
262
|
+
|
|
263
|
+
def St(x):
|
|
264
|
+
"""
|
|
265
|
+
S Corrèle X avec un noyau KER.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
X (numpy.ndarray) image non vectorisée 2D
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
(numpy.ndarray) Correlation de X par le noyau KER
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
h,w = x.shape
|
|
275
|
+
|
|
276
|
+
ox = np.linspace(-w/2+1/2, w/2-1/2, w)
|
|
277
|
+
oy = np.linspace(-h/2+1/2, h/2-1/2, h)
|
|
278
|
+
X,Y = np.meshgrid(ox, oy)
|
|
279
|
+
dist = np.sqrt(X**2/w**2 + Y**2/h**2); # anisotropic distance
|
|
280
|
+
n = 5
|
|
281
|
+
fc = 1/3 # in [0,1] since dist is normalized
|
|
282
|
+
ker = 1./(1 + (dist/fc)**(2*n))
|
|
283
|
+
|
|
284
|
+
imf = np.real(np.fft.ifft2(np.fft.ifftshift(np.conj(ker)*np.fft.fftshift(np.fft.fft2(x)))))
|
|
285
|
+
|
|
286
|
+
return imf
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
############################################################
|
|
291
|
+
## Operator and matrix norm
|
|
292
|
+
############################################################
|
|
293
|
+
def opNorm(op,opt,dim):
|
|
294
|
+
"""
|
|
295
|
+
opNorm Calcule la norme de l'opérateur OP, dont
|
|
296
|
+
l'opérateur transposé est OPT, en dimension DIM
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
OP (function) opérateur direct
|
|
300
|
+
OPT (function) opérateur adjoint
|
|
301
|
+
DIM (str) '1D', '2D'
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
(float) norme de l'opérateur OP
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
def T(x):
|
|
308
|
+
return opt(op(x))
|
|
309
|
+
|
|
310
|
+
if dim == '1D':
|
|
311
|
+
xn = np.random.standard_normal((64))
|
|
312
|
+
elif dim == '2D':
|
|
313
|
+
xn = np.random.standard_normal((64,64))
|
|
314
|
+
|
|
315
|
+
xnn = xn
|
|
316
|
+
|
|
317
|
+
n = np.zeros((1000,),float)
|
|
318
|
+
n[1] = 1
|
|
319
|
+
tol = 1e-4
|
|
320
|
+
rhon = n[1]+2*tol
|
|
321
|
+
|
|
322
|
+
k = 1
|
|
323
|
+
while abs(n[k]-rhon)/n[k] >= tol:
|
|
324
|
+
xn = T(xnn)
|
|
325
|
+
xnn = T(xn)
|
|
326
|
+
|
|
327
|
+
rhon = n[k]
|
|
328
|
+
n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
|
|
329
|
+
|
|
330
|
+
k = k+1
|
|
331
|
+
|
|
332
|
+
N = n[k-1] + 1e-16
|
|
333
|
+
return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def matNorm(M):
|
|
337
|
+
"""
|
|
338
|
+
matNorm Calcule la norme de la matrice M
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
M (numpy.ndarray) matrice dont on souhaite calculer la norme
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
(float) norme de la matrice M
|
|
345
|
+
"""
|
|
346
|
+
|
|
347
|
+
def T(x):
|
|
348
|
+
return np.dot(M.T, np.dot(M,x))
|
|
349
|
+
|
|
350
|
+
xn = np.random.standard_normal((M.shape[1]))
|
|
351
|
+
xnn = xn
|
|
352
|
+
|
|
353
|
+
n = np.zeros((1000,),float)
|
|
354
|
+
n[1] = 1
|
|
355
|
+
tol = 1e-4
|
|
356
|
+
rhon = n[1]+2*tol
|
|
357
|
+
|
|
358
|
+
k = 1
|
|
359
|
+
while abs(n[k]-rhon)/n[k] >= tol:
|
|
360
|
+
xn = T(xnn)
|
|
361
|
+
xnn = T(xn)
|
|
362
|
+
|
|
363
|
+
rhon = n[k]
|
|
364
|
+
n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
|
|
365
|
+
|
|
366
|
+
k = k+1
|
|
367
|
+
|
|
368
|
+
N = n[k-1] + 1e-16
|
|
369
|
+
return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch import Generator
|
|
3
|
+
from torch.utils.data import Dataset, TensorDataset
|
|
4
|
+
from torchvision.transforms import ToTensor
|
|
5
|
+
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
""" dataset classes """
|
|
13
|
+
class BSDSDataset(Dataset):
|
|
14
|
+
def __init__(self, root_dir="data/bsds500", mode="train",
|
|
15
|
+
image_size=(256, 256), image_cnt=None,
|
|
16
|
+
gray=False, device="cpu"):
|
|
17
|
+
""" BSDS500 Dataset construction
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
root_dir: str or Path object
|
|
22
|
+
Local path to the dataset
|
|
23
|
+
mode: str
|
|
24
|
+
Dataset type: "train", "val" or "test"
|
|
25
|
+
image_size: tuple of int
|
|
26
|
+
Crop the image to the given size
|
|
27
|
+
image_cnt: int
|
|
28
|
+
If specified, extract at most the given number of images
|
|
29
|
+
gray: bool
|
|
30
|
+
If True, convert images to grayscale
|
|
31
|
+
device: str or torch.device
|
|
32
|
+
Device where the dataset is created
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
# Properties
|
|
36
|
+
self.root_dir = Path(root_dir)
|
|
37
|
+
self.mode = mode
|
|
38
|
+
self.image_size = image_size
|
|
39
|
+
self.gray = gray
|
|
40
|
+
self.device = device
|
|
41
|
+
|
|
42
|
+
# Create the list of corresponding images (sorted for reprocibility purpose)
|
|
43
|
+
self.image_list = sorted((self.root_dir / self.mode).glob("*.jpg"))
|
|
44
|
+
if image_cnt is not None:
|
|
45
|
+
self.image_list = self.image_list[:image_cnt]
|
|
46
|
+
|
|
47
|
+
def __repr__(self):
|
|
48
|
+
""" Nice representation when displaying the variable """
|
|
49
|
+
return f"BSDSDataset(mode={self.mode}, image_size={self.image_size})"
|
|
50
|
+
|
|
51
|
+
def __len__(self):
|
|
52
|
+
""" Number of samples """
|
|
53
|
+
return len(self.image_list)
|
|
54
|
+
|
|
55
|
+
def __getitem__(self, idx):
|
|
56
|
+
""" Reading a sample """
|
|
57
|
+
|
|
58
|
+
# set image path and id
|
|
59
|
+
image_path = self.image_list[idx]
|
|
60
|
+
image_id = int(image_path.stem)
|
|
61
|
+
|
|
62
|
+
# load and crop clean image
|
|
63
|
+
clean_image = Image.open(image_path).convert('RGB')
|
|
64
|
+
i = max(0, (clean_image.size[0] - self.image_size[0]) // 2)
|
|
65
|
+
j = max(0, (clean_image.size[1] - self.image_size[1]) // 2)
|
|
66
|
+
clean_image = clean_image.crop([
|
|
67
|
+
i, j,
|
|
68
|
+
min(clean_image.size[0], i + self.image_size[0]),
|
|
69
|
+
min(clean_image.size[1], j + self.image_size[1]),
|
|
70
|
+
])
|
|
71
|
+
clean_image = ToTensor()(clean_image).to(self.device) # move to the requested device
|
|
72
|
+
|
|
73
|
+
# optional conversion to grayscale
|
|
74
|
+
if self.gray:
|
|
75
|
+
clean_image = clean_image.mean(-3, keepdim=True)
|
|
76
|
+
|
|
77
|
+
return clean_image, image_id
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class NoisyDataset(Dataset):
|
|
81
|
+
def __init__(self, dataset, degradation_model, sigma=0.1, seed=None):
|
|
82
|
+
""" Noisy Dataset construction
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
dataset: torch.utils.data.Dataset
|
|
87
|
+
Original BSDS dataset
|
|
88
|
+
degradation_model: function handle
|
|
89
|
+
Function modeling the degradation model
|
|
90
|
+
sigma: float
|
|
91
|
+
Standard deviation of the noise (default: 0.1)
|
|
92
|
+
seed: int
|
|
93
|
+
If specified, the whole dataset is reproductible with given seed.
|
|
94
|
+
"""
|
|
95
|
+
self.dataset = dataset
|
|
96
|
+
self.degradation_model = degradation_model
|
|
97
|
+
self.sigma = sigma
|
|
98
|
+
self.seed = seed if seed is not None else Generator().seed()
|
|
99
|
+
|
|
100
|
+
def __repr__(self):
|
|
101
|
+
return f"NoisyDataset(dataset={self.dataset}, sigma={self.sigma})"
|
|
102
|
+
|
|
103
|
+
def __len__(self):
|
|
104
|
+
return len(self.dataset)
|
|
105
|
+
|
|
106
|
+
def __getitem__(self, idx):
|
|
107
|
+
clean_image, image_id = self.dataset[idx]
|
|
108
|
+
|
|
109
|
+
# generate noisy image
|
|
110
|
+
noisy_image = self.degradation_model(clean_image, self.sigma, seed=self.seed)
|
|
111
|
+
|
|
112
|
+
return noisy_image, clean_image, int(image_id)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def toTensorDataset(self):
|
|
116
|
+
""" Store the whole dataset in memory """
|
|
117
|
+
noised_images, clean_images, images_id = zip(*self)
|
|
118
|
+
return TensorDataset(
|
|
119
|
+
torch.stack(noised_images),
|
|
120
|
+
torch.stack(clean_images),
|
|
121
|
+
torch.tensor(images_id),
|
|
122
|
+
)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch.utils.data import DataLoader
|
|
3
|
+
|
|
4
|
+
from tqdm.notebook import tqdm
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
""" Trainer class """
|
|
9
|
+
class Trainer():
|
|
10
|
+
def __init__(self,
|
|
11
|
+
model, optimizer, loss,
|
|
12
|
+
batch_size,
|
|
13
|
+
train_dataset, val_dataset=None,
|
|
14
|
+
check_val_every_n_epoch=1):
|
|
15
|
+
|
|
16
|
+
self.model = model
|
|
17
|
+
self.optimizer = optimizer
|
|
18
|
+
self.loss = loss
|
|
19
|
+
self.batch_size = batch_size
|
|
20
|
+
self.train_dataloader = train_dataset
|
|
21
|
+
self.val_dataloader = val_dataset
|
|
22
|
+
self.check_val_every_n_epoch = check_val_every_n_epoch
|
|
23
|
+
self.metrics = Metrics()
|
|
24
|
+
self.history = {}
|
|
25
|
+
self.epoch = 0
|
|
26
|
+
|
|
27
|
+
# dataloaders
|
|
28
|
+
self.train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
|
|
29
|
+
if self.val_dataloader is None:
|
|
30
|
+
self.val_dataloader = None
|
|
31
|
+
else:
|
|
32
|
+
self.val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=True)
|
|
33
|
+
|
|
34
|
+
def run(self, num_epoch):
|
|
35
|
+
""" Run training until the given number of epochs is reached """
|
|
36
|
+
try:
|
|
37
|
+
# progress bar
|
|
38
|
+
training_pbar = tqdm(
|
|
39
|
+
iterable=range(self.epoch, num_epoch),
|
|
40
|
+
initial=self.epoch,
|
|
41
|
+
total=num_epoch,
|
|
42
|
+
desc="Training",
|
|
43
|
+
unit="epoch"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
for _ in training_pbar:
|
|
47
|
+
self.training_epoch()
|
|
48
|
+
training_pbar.set_postfix(self.history["Training"][-1][1])
|
|
49
|
+
if self.epoch % self.check_val_every_n_epoch == 0:
|
|
50
|
+
self.validation_epoch()
|
|
51
|
+
epoch, metrics = self.history["Validation"][-1]
|
|
52
|
+
print(f"Validation epoch {epoch:4d} | " + " | ".join((f"{k}: {v:.2e}" for k, v in metrics.items())))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
except KeyboardInterrupt:
|
|
56
|
+
""" Stop training if Ctrl-C is pressed """
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
def training_epoch(self):
|
|
60
|
+
""" Train for one epoch """
|
|
61
|
+
device = self.device
|
|
62
|
+
self.metrics.init()
|
|
63
|
+
for x, target, *_ in self.train_dataloader:
|
|
64
|
+
x = x.to(device)
|
|
65
|
+
target = target.to(device)
|
|
66
|
+
|
|
67
|
+
y = self.model(x)
|
|
68
|
+
loss = self.loss(y, target)
|
|
69
|
+
self.optimizer.zero_grad()
|
|
70
|
+
loss.backward()
|
|
71
|
+
self.optimizer.step()
|
|
72
|
+
|
|
73
|
+
self.metrics.accumulate(loss, x, y, target)
|
|
74
|
+
|
|
75
|
+
self.epoch += 1
|
|
76
|
+
self.log("Training", self.epoch, self.metrics.summarize())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def validation_epoch(self):
|
|
80
|
+
""" Run a validation step """
|
|
81
|
+
if self.val_dataloader is None:
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
device = self.device
|
|
85
|
+
self.metrics.init()
|
|
86
|
+
with torch.no_grad():
|
|
87
|
+
for x, target, *_ in self.val_dataloader:
|
|
88
|
+
x = x.to(device)
|
|
89
|
+
target = target.to(device)
|
|
90
|
+
|
|
91
|
+
y = self.model(x)
|
|
92
|
+
loss = self.loss(y, target)
|
|
93
|
+
|
|
94
|
+
self.metrics.accumulate(loss, x, y, target)
|
|
95
|
+
|
|
96
|
+
self.log("Validation", self.epoch, self.metrics.summarize())
|
|
97
|
+
|
|
98
|
+
def log(self, mode, epoch, metrics):
|
|
99
|
+
history = self.history.setdefault(mode, [])
|
|
100
|
+
history.append((epoch, metrics))
|
|
101
|
+
#print(f"{mode} epoch {epoch:4d} | " + " | ".join((f"{k}: {v:.2e}" for k, v in metrics.items())))
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def device(self):
|
|
105
|
+
""" Training device defined from the device of the first parameter of the model """
|
|
106
|
+
return next(self.model.parameters()).device
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Metrics:
|
|
112
|
+
""" Compute metrics from training and validation steps """
|
|
113
|
+
def init(self):
|
|
114
|
+
self.metrics = dict()
|
|
115
|
+
self.cnt = 0
|
|
116
|
+
self.tic = time.perf_counter()
|
|
117
|
+
|
|
118
|
+
def accumulate(self, loss, x, y, target):
|
|
119
|
+
with torch.no_grad():
|
|
120
|
+
self.metrics["Loss"] = self.metrics.get("Loss", 0) + loss.item()
|
|
121
|
+
self.metrics["PSNR"] = self.metrics.get("PSNR", 0) + self.__PSNR__(y, target).mean().item()
|
|
122
|
+
self.cnt += 1
|
|
123
|
+
|
|
124
|
+
def summarize(self):
|
|
125
|
+
self.toc = time.perf_counter()
|
|
126
|
+
metrics = {k: v / self.cnt for k, v in self.metrics.items()}
|
|
127
|
+
metrics["Wall time"] = self.toc - self.tic
|
|
128
|
+
return metrics
|
|
129
|
+
|
|
130
|
+
def __PSNR__(self, img1, img2):
|
|
131
|
+
# optional: get last 3 dimensions (CxNxM) to ensure compatibility with a single sample
|
|
132
|
+
dims = list(range(max(0, img1.ndim - 3), img1.ndim))
|
|
133
|
+
# otherwise:
|
|
134
|
+
#dims = list(range(1, img1.ndim))
|
|
135
|
+
|
|
136
|
+
# necessity to take the mean along only the last 3 dimensions
|
|
137
|
+
return 10 * torch.log10(1. / (img1 - img2).pow(2).mean(dims))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def chooseDevice(device=None):
|
|
5
|
+
if device == None:
|
|
6
|
+
# setting device on GPU if available, else MPS (Apple M1) or CPU
|
|
7
|
+
if torch.cuda.is_available():
|
|
8
|
+
device = torch.device('cuda') # CUDA backend for NVIDIA or AMD graphic cards
|
|
9
|
+
else:
|
|
10
|
+
try:
|
|
11
|
+
if torch.backends.mps.is_available():
|
|
12
|
+
device = torch.device('mps') # MPS for Apple M# processors
|
|
13
|
+
else:
|
|
14
|
+
device = torch.device('cpu')
|
|
15
|
+
except AttributeError:
|
|
16
|
+
device = torch.device('cpu')
|
|
17
|
+
else:
|
|
18
|
+
device = torch.device(device)
|
|
19
|
+
|
|
20
|
+
print('Using device:', device)
|
|
21
|
+
print()
|
|
22
|
+
|
|
23
|
+
# additional info when using cuda
|
|
24
|
+
if device.type == 'cuda':
|
|
25
|
+
print(torch.cuda.get_device_name(0))
|
|
26
|
+
print('Memory Usage:')
|
|
27
|
+
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
|
|
28
|
+
print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
|
|
29
|
+
|
|
30
|
+
return device
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def torchImg2Numpy(image):
|
|
35
|
+
# reorder dimensions (C, N, M) -> (M, N, C) and move to CPU
|
|
36
|
+
image = torch.moveaxis(image, [0, 1, 2], [2, 0, 1]).to('cpu')
|
|
37
|
+
|
|
38
|
+
if image.shape[-1] == 1:
|
|
39
|
+
image = image[..., 0]
|
|
40
|
+
|
|
41
|
+
return image.numpy()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def getData(trainer, mode):
|
|
45
|
+
data = dict()
|
|
46
|
+
for epoch, record in trainer.history[mode]:
|
|
47
|
+
data.setdefault("epoch", []).append(epoch)
|
|
48
|
+
for metric, value in record.items():
|
|
49
|
+
data.setdefault(metric, []).append(value)
|
|
50
|
+
|
|
51
|
+
return data
|
|
52
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: imicpe
|
|
3
|
+
Version: 0.0.9
|
|
4
|
+
Summary: Toolbox for Maths,Signal,Image Teaching @ CPE
|
|
5
|
+
Author-email: Marion Foare <marion.foare@cpe.fr>, Eric Van Reeth <eric.vanreeth@cpe.fr>, Arthur Gautheron <arthur.gautheron@cpe.fr>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Project-URL: Homepage, https://www.cpe.fr
|
|
8
|
+
Project-URL: Documentation, https://toolbox-imi-cpe-msi-1bcfcdd75992c038486502447f7f6937f3492f60127.pages.in2p3.fr/
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
|
|
18
|
+
Developped and maintained for teaching usage only!
|
|
19
|
+
|
|
20
|
+
# Installation
|
|
21
|
+
|
|
22
|
+
## In a Jupyter Notebook
|
|
23
|
+
|
|
24
|
+
```!pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
25
|
+
|
|
26
|
+
## In a local environment
|
|
27
|
+
|
|
28
|
+
```pip install -i https://test.pypi.org/simple/ -U imicpe```
|
|
29
|
+
|
|
30
|
+
# Usage example
|
|
31
|
+
|
|
32
|
+
The example below uses the kurtosis method available in the `tsa` subpackage of `msicpe`.
|
|
33
|
+
It requires `numpy.randn` to generate a gaussian distribution of N points.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import numpy as np
|
|
37
|
+
from msicpe.tsa import kurtosis
|
|
38
|
+
N=10000
|
|
39
|
+
|
|
40
|
+
x=np.randn(1,N)
|
|
41
|
+
kurt=kurtosis(x)
|
|
42
|
+
|
|
43
|
+
print(kurt)
|
|
44
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
DESCRIPTION.md
|
|
2
|
+
LICENSE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/imicpe/__init__.py
|
|
6
|
+
src/imicpe.egg-info/PKG-INFO
|
|
7
|
+
src/imicpe.egg-info/SOURCES.txt
|
|
8
|
+
src/imicpe.egg-info/dependency_links.txt
|
|
9
|
+
src/imicpe.egg-info/top_level.txt
|
|
10
|
+
src/imicpe/optim/__init__.py
|
|
11
|
+
src/imicpe/optim/metrics.py
|
|
12
|
+
src/imicpe/optim/operators.py
|
|
13
|
+
src/imicpe/optim/pnnDataset.py
|
|
14
|
+
src/imicpe/optim/pnnTrainer.py
|
|
15
|
+
src/imicpe/optim/pnnUtils.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
imicpe
|