napari-dpr 0.1.0__cp311-cp311-win_amd64.whl

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.
@@ -0,0 +1,103 @@
1
+ # distutils: language = c++
2
+ import numpy as np
3
+ cimport numpy as np
4
+ from libc.math cimport fabs, ceil
5
+ import scipy.ndimage as ndi
6
+ from scipy.interpolate import RectBivariateSpline
7
+
8
+ np.import_array()
9
+
10
+ ctypedef np.float64_t DTYPE_t
11
+
12
+ def dpr_set_parameters(double psf, double gain=1, double background=-1, temporal=None):
13
+ if background < 0:
14
+ background = ceil(17 * psf)
15
+ return {'gain': gain, 'background': background, 'temporal': temporal}
16
+
17
+ cpdef tuple dpr_update_single(np.ndarray[DTYPE_t, ndim=2] i, double psf, dict opt):
18
+ cdef:
19
+ int h = i.shape[0]
20
+ int w = i.shape[1]
21
+ int r = <int>ceil(opt['background'])
22
+ double g = opt['gain']
23
+ np.ndarray[DTYPE_t, ndim=2] localmin = np.zeros((h, w))
24
+ np.ndarray[DTYPE_t, ndim=2] i_localmin = np.zeros((h, w))
25
+ int u, v
26
+
27
+ i = i - i.min()
28
+ for u in range(h):
29
+ for v in range(w):
30
+ sub = i[max(0, u - r):min(h, u + r + 1), max(0, v - r):min(w, v + r + 1)]
31
+ localmin[u, v] = np.min(sub)
32
+ i_localmin[u, v] = i[u, v] - localmin[u, v]
33
+
34
+ psf /= 1.6651
35
+ x0 = np.linspace(-0.5, 0.5, w)
36
+ y0 = np.linspace(-0.5, 0.5, h)
37
+ x = np.linspace(-0.5, 0.5, round(5 * w / psf))
38
+ y = np.linspace(-0.5, 0.5, round(5 * h / psf))
39
+
40
+ interp_m = RectBivariateSpline(y0, x0, i_localmin)(y, x)
41
+ interp_m[interp_m < 0] = 0
42
+ interp_m = np.pad(interp_m, 10)
43
+
44
+ interp_i = RectBivariateSpline(y0, x0, i)(y, x)
45
+ interp_i[interp_i < 0] = 0
46
+ interp_i = np.pad(interp_i, 10)
47
+
48
+ hn, wn = interp_i.shape
49
+ norm = interp_m / (ndi.gaussian_filter(interp_m, 10) + 1e-5)
50
+
51
+ sobel_x = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
52
+ sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
53
+ gx = ndi.convolve(norm, sobel_y, mode='reflect') / (norm + 1e-5)
54
+ gy = ndi.convolve(norm, sobel_x, mode='reflect') / (norm + 1e-5)
55
+
56
+ gain_val = 0.5 * g + 1
57
+ dx = gain_val * gx
58
+ dy = gain_val * gy
59
+ dx[np.abs(dx) > 10] = 0
60
+ dy[np.abs(dy) > 10] = 0
61
+
62
+ out = np.zeros((hn, wn))
63
+ cdef int nx, ny, fx, fy, sx, sy
64
+ cdef double wx, wy, w1, w2, w3, w4, val
65
+
66
+ for nx in range(10, hn - 10):
67
+ for ny in range(10, wn - 10):
68
+ wx, wy = dx[nx, ny], dy[nx, ny]
69
+ fx, fy = int(wx), int(wy)
70
+ sx, sy = int(np.sign(wx)), int(np.sign(wy))
71
+ w1 = (1 - fabs(wx - fx)) * (1 - fabs(wy - fy))
72
+ w2 = (1 - fabs(wx - fx)) * fabs(wy - fy)
73
+ w3 = fabs(wx - fx) * (1 - fabs(wy - fy))
74
+ w4 = fabs(wx - fx) * fabs(wy - fy)
75
+ val = interp_i[nx, ny]
76
+ out[nx + fx, ny + fy] += w1 * val
77
+ out[nx + fx, ny + fy + sy] += w2 * val
78
+ out[nx + fx + sx, ny + fy] += w3 * val
79
+ out[nx + fx + sx, ny + fy + sy] += w4 * val
80
+
81
+ return out[10:-10, 10:-10], interp_i[10:-10, 10:-10], g, r
82
+
83
+ cpdef tuple dpr_stack(np.ndarray[DTYPE_t, ndim=3] s, double psf, dict opt):
84
+ cdef int f = s.shape[2]
85
+ dpr0, mag0, _, _ = dpr_update_single(s[:, :, 0], psf, opt)
86
+ shp = dpr0.shape
87
+ out = np.zeros((shp[0], shp[1], f))
88
+ mag = np.zeros((shp[0], shp[1], f))
89
+ cdef int i
90
+ for i in range(f):
91
+ dpr, m, _, _ = dpr_update_single(s[:, :, i], psf, opt)
92
+ out[:, :, i] = dpr
93
+ mag[:, :, i] = m
94
+ if opt.get('temporal') == 'mean':
95
+ out = np.mean(out, axis=2)
96
+ elif opt.get('temporal') == 'var':
97
+ out = np.var(out, axis=2)
98
+ return out, mag
99
+ cpdef tuple apply_dpr(np.ndarray[DTYPE_t, ndim=3] im, double psf=4, double gain=2, double background=10, temporal='mean'):
100
+ if im.ndim == 2:
101
+ im = im[:, :, np.newaxis]
102
+ opt = dpr_set_parameters(psf, gain, background, temporal)
103
+ return dpr_stack(im, psf, opt)
napari_dpr/example.py ADDED
@@ -0,0 +1,46 @@
1
+ """
2
+ Example script for using napari-dpr programmatically.
3
+ """
4
+ import os
5
+ import sys
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import napari
9
+ from napari_dpr.dpr_core import apply_dpr
10
+ from napari_dpr.run_dpr import run_example
11
+
12
+ def example_with_test_image():
13
+ """Run an example using the test image or random data if not available."""
14
+ print("Running DPR example with test image...")
15
+ # run_example returns the dpr_out and magnified images
16
+ dpr_out, magnified = run_example()
17
+ print("Done.")
18
+
19
+ def example_with_napari():
20
+ """Run an example using napari viewer."""
21
+ print("Running DPR example with napari...")
22
+
23
+ # Create a random test image
24
+ test_image = np.random.random((100, 100, 5)).astype(np.float64)
25
+
26
+ # Start napari viewer with the test image
27
+ viewer = napari.Viewer()
28
+ viewer.add_image(test_image, name='test_image')
29
+
30
+ # Process the image with DPR
31
+ dpr_out, magnified = apply_dpr(test_image, psf=4.0)
32
+
33
+ # Add the processed images to the viewer
34
+ viewer.add_image(dpr_out, name='DPR_enhanced')
35
+ viewer.add_image(magnified.sum(axis=2), name='magnified')
36
+
37
+ # Start the napari event loop
38
+ napari.run()
39
+
40
+ if __name__ == "__main__":
41
+ if len(sys.argv) > 1 and sys.argv[1] == '--napari':
42
+ example_with_napari()
43
+ else:
44
+ example_with_test_image()
45
+
46
+ print("To run with napari viewer: python -m napari_dpr.example --napari")
napari_dpr/napari.yaml ADDED
@@ -0,0 +1,10 @@
1
+ name: napari-dpr
2
+ display_name: DPR Resolution Enhancement
3
+ contributions:
4
+ commands:
5
+ - id: napari-dpr.enhance_image
6
+ title: Enhance resolution with DPR
7
+ python_name: napari_dpr._widget:enhance_image
8
+ widgets:
9
+ - command: napari-dpr.enhance_image
10
+ display_name: DPR Enhancement
napari_dpr/run.dpr.py ADDED
@@ -0,0 +1,68 @@
1
+ # run_dpr.py
2
+ import os
3
+ import numpy as np
4
+ import tifffile as tf
5
+ from napari_dpr.dpr_core import apply_dpr
6
+ import matplotlib.pyplot as plt
7
+ import time
8
+ from pathlib import Path
9
+
10
+ def run_example(input_file=None):
11
+ """Run DPR on an example image file."""
12
+
13
+ # If no input file is provided, try to find the test image in standard locations
14
+ if input_file is None:
15
+ # Try several possible locations for the test image
16
+ possible_paths = [
17
+ "test_data/test_image.tif", # Repository structure
18
+ "../test_data/test_image.tif", # If run from src directory
19
+ "../../test_data/test_image.tif", # If run from deeper directory
20
+ os.path.join(os.path.dirname(__file__), '../../test_data/test_image.tif') # Relative to script
21
+ ]
22
+
23
+ for path in possible_paths:
24
+ if os.path.exists(path):
25
+ input_file = path
26
+ break
27
+
28
+ if input_file is None:
29
+ # If no test image is found, generate a random one
30
+ print("No test image found, generating random data...")
31
+ input_image = np.random.rand(64, 64, 5).astype(np.float64)
32
+ else:
33
+ print(f"Using test image: {input_file}")
34
+ else:
35
+ print(f"Using provided image: {input_file}")
36
+
37
+ # Load the image if a file was found or provided
38
+ if input_file is not None:
39
+ input_image = tf.imread(input_file)
40
+ # Ensure correct dimensions (HEIGHT, WIDTH, TIME)
41
+ if input_image.ndim == 3 and input_image.shape[0] < input_image.shape[1]:
42
+ input_image = input_image.transpose([1, 2, 0])
43
+
44
+ # Ensure 3D image (HEIGHT, WIDTH, TIME)
45
+ if input_image.ndim == 2:
46
+ input_image = input_image[:, :, np.newaxis]
47
+
48
+ # Process with DPR
49
+ print(f"Processing image of shape {input_image.shape}...")
50
+ start = time.time()
51
+ dpr_out, magnified = apply_dpr(input_image, psf=4.0)
52
+ print(f"Time taken: {time.time() - start:.2f} seconds")
53
+
54
+ # Display results
55
+ plt.figure(figsize=(12, 6))
56
+ plt.subplot(121)
57
+ plt.title("Original (Magnified)")
58
+ plt.imshow(magnified.sum(2))
59
+ plt.subplot(122)
60
+ plt.title("DPR Enhanced")
61
+ plt.imshow(dpr_out)
62
+ plt.tight_layout()
63
+ plt.show()
64
+
65
+ return dpr_out, magnified
66
+
67
+ if __name__ == "__main__":
68
+ run_example()
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: napari-dpr
3
+ Version: 0.1.0
4
+ Summary: Napari plugin for DPR Resolution Enhancement
5
+ Author-email: JenuC <jenu.chacko@wisc.edu>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jenuc/napari-dpr
8
+ Project-URL: Bug Tracker, https://github.com/jenuc/napari-dpr/issues
9
+ Project-URL: Documentation, https://github.com/jenuc/napari-dpr#README.md
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Framework :: napari
19
+ Classifier: Intended Audience :: Science/Research
20
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
21
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: napari>=0.4.18
26
+ Requires-Dist: numpy>=1.24.3
27
+ Requires-Dist: scipy>=1.10.1
28
+ Requires-Dist: matplotlib>=3.7.2
29
+ Requires-Dist: cython>=0.29.0
30
+ Requires-Dist: setuptools>=42.0.0
31
+ Requires-Dist: tifffile
32
+ Requires-Dist: pillow
33
+ Requires-Dist: magicgui>=0.5.0
34
+ Requires-Dist: qtpy
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest; extra == "dev"
37
+ Requires-Dist: build; extra == "dev"
38
+ Requires-Dist: twine; extra == "dev"
39
+ Requires-Dist: cibuildwheel; extra == "dev"
40
+ Provides-Extra: testing
41
+ Requires-Dist: pytest; extra == "testing"
42
+ Requires-Dist: pytest-qt; extra == "testing"
43
+ Dynamic: license-file
44
+
45
+ # napari-dpr
46
+
47
+ [![License MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/licenses/MIT)
48
+ [![PyPI version](https://img.shields.io/pypi/v/napari-dpr.svg)](https://pypi.org/project/napari-dpr)
49
+ [![Python Version](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://python.org)
50
+ [![napari hub](https://img.shields.io/badge/napari-hub-purple.svg)](https://napari-hub.org/plugins/napari-dpr)
51
+
52
+ > ## ⚠️ IMPORTANT: Original Work Acknowledgment
53
+ > This napari plugin is based on and extends the work from the original [DPR-Resolution_enhancement_with_deblurring_by_pixel_reassignment](https://github.com/biomicroscopy/DPR-Resolution_enhancement_with_deblurring_by_pixel_reassignment) repository.
54
+ >
55
+ > The algorithm was originally developed by Zhao, B. and Mertz, J., as described in their paper ["Resolution enhancement with deblurring by pixel reassignment (DPR)"](https://www.spiedigitallibrary.org/journals/advanced-photonics/volume-5/issue-06/066004/Resolution-enhancement-with-deblurring-by-pixel-reassignment/10.1117/1.AP.5.6.066004.full) (DOI: 10.1117/1.AP.5.6.066004).
56
+ >
57
+ > <img src="docs/images/schematic.png" alt="DPR Algorithm Schematic" width="50%">
58
+ >
59
+ > **If you use this plugin for your research, please cite the original paper:**
60
+ > ```
61
+ > Zhao, B., and Mertz, J. "Resolution enhancement with deblurring by pixel reassignment (DPR)."
62
+ > Advanced Photonics, 5(6), 066004 (2023). DOI: 10.1117/1.AP.5.6.066004
63
+ > ```
64
+
65
+ A napari plugin for image resolution enhancement using Deconvolution by Pixel Reassignment (DPR).
66
+
67
+ ## Description
68
+
69
+ DPR is a technique for enhancing the resolution of images, particularly useful in microscopy. This plugin provides easy access to DPR functionality within napari, allowing for quick and intuitive image enhancement without leaving your viewer.
70
+
71
+ The algorithm works by:
72
+ 1. Applying a specialized deconvolution approach
73
+ 2. Reassigning pixels based on local information
74
+ 3. Enhancing fine details while preserving image structure
75
+
76
+ ## Installation
77
+
78
+ You can install `napari-dpr` via [pip]:
79
+
80
+ ```bash
81
+ pip install napari-dpr
82
+ ```
83
+
84
+ ## Usage
85
+
86
+ 1. Open napari and load an image
87
+ 2. In the menu, go to `Plugins > DPR Enhancement`
88
+ 3. Select your image from the dropdown
89
+ 4. Adjust parameters as needed:
90
+ - **PSF**: Point spread function size (typical values: 2-6)
91
+ - **Gain**: Enhancement gain (typical values: 1-3)
92
+ - **Background**: Background subtraction (typical values: 5-20)
93
+ 5. Click "Enhance Resolution"
94
+ 6. Two new layers will be added to your viewer:
95
+ - `[original_name]_DPR_enhanced`: The DPR-enhanced image
96
+ - `[original_name]_magnified`: The magnified original for comparison
97
+
98
+ ## Parameters
99
+
100
+ - **PSF** (Point Spread Function): Controls the width of the point spread function used in the algorithm. Larger values capture wider spatial correlations but may reduce detail resolution.
101
+ - **Gain**: Controls the enhancement strength. Higher values increase contrast but may introduce artifacts.
102
+ - **Background**: Controls background subtraction. Higher values remove more background but may affect relevant image features.
103
+
104
+ ## Standalone Usage
105
+
106
+ You can also use the DPR algorithm programmatically:
107
+
108
+ ```python
109
+ from napari_dpr.dpr_core import apply_dpr
110
+ import numpy as np
111
+ import matplotlib.pyplot as plt
112
+
113
+ # Load your image data (should be 3D: HEIGHT, WIDTH, TIME)
114
+ image_data = your_image_loading_function()
115
+ if image_data.ndim == 2:
116
+ image_data = image_data[:, :, np.newaxis] # Add time dimension if 2D
117
+
118
+ # Apply DPR
119
+ dpr_enhanced, magnified = apply_dpr(image_data, psf=4.0, gain=2.0, background=10.0)
120
+
121
+ # Visualize results
122
+ plt.figure(figsize=(12, 6))
123
+ plt.subplot(121)
124
+ plt.title("Original (Magnified)")
125
+ plt.imshow(magnified.sum(axis=2))
126
+ plt.subplot(122)
127
+ plt.title("DPR Enhanced")
128
+ plt.imshow(dpr_enhanced)
129
+ plt.tight_layout()
130
+ plt.show()
131
+ ```
132
+
133
+ ## Contributing
134
+
135
+ Contributions are welcome! Please feel free to submit a Pull Request.
136
+
137
+ ## License
138
+
139
+ Distributed under the terms of the [MIT] license,
140
+ "napari-dpr" is free and open source software.
141
+
142
+ ## Issues
143
+
144
+ If you encounter any problems, please [file an issue] along with a detailed description.
145
+
146
+ [file an issue]: https://github.com/jenuc/napari-dpr/issues
147
+ [napari]: https://github.com/napari/napari
148
+ [pip]: https://pypi.org/project/pip/
149
+ [MIT]: https://opensource.org/licenses/MIT
@@ -0,0 +1,19 @@
1
+ napari_dpr/__init__.py,sha256=HFUdQMoqtTsOemML-GXsGoAC8q-EGgfAbqgQzhqfRwY,165
2
+ napari_dpr/_widget.py,sha256=LrK4YI6hLRAWMXPEsyBWuvmgx3OctScp1rW0hLnixlI,2932
3
+ napari_dpr/dpr.py,sha256=6pNcqYCI7HQXJv2nU33ZFyhEJu4Po5Fo3xG5Z1L8WIc,5267
4
+ napari_dpr/dpr_core.cp310-win_amd64.pyd,sha256=XSPkw-7w569QoqQytaG7Qr2c-4tefdOF91GfzsoSI94,102912
5
+ napari_dpr/dpr_core.cp311-win_amd64.pyd,sha256=BBJt5ZE8xOT7E15eCgRnUzGuxX7zYHU535RBPxS-rq4,103424
6
+ napari_dpr/dpr_core.cp312-win_amd64.pyd,sha256=CCpiLdPcziOmnP9l6psT1tUDTRiWMqqOxvVu-74QpX8,102400
7
+ napari_dpr/dpr_core.cp313-win_amd64.pyd,sha256=ZD7GLCDa5D2QzTWAKOVXfv69Zw6oJ6Op1ryw-Vs9lLc,101888
8
+ napari_dpr/dpr_core.cp39-win_amd64.pyd,sha256=YnljIT3EbCAuhz1w2pHmi4HfIj7xUb7wUNtoLnFAcOY,102912
9
+ napari_dpr/dpr_core.cpp,sha256=ynsq30HyYVN_rSID2rUj2e0_lPdyhxsAZ3w-b7k-SvI,617011
10
+ napari_dpr/dpr_core.pyx,sha256=GGnCR37RnWW_IDBHwuqrCevCUJHo5p7cNhQyKUQlvIs,3804
11
+ napari_dpr/example.py,sha256=n5gKHk70XL3VyvjJvJq6S6k7onPu0s_X6VCArfDomFw,1472
12
+ napari_dpr/napari.yaml,sha256=52yyMHUE3xPkS-3rVPKhqRRDXN2fyF6mjS021FzihkA,309
13
+ napari_dpr/run.dpr.py,sha256=NDr2QhzYMjr0ZqudspgzOCZhMxaqRrbejwaS7lPs6_4,2427
14
+ napari_dpr-0.1.0.dist-info/licenses/LICENSE,sha256=fG9FETcFv5KCjRjPEb6STyAZKUMRQbLDJzc9Rgy728M,1082
15
+ napari_dpr-0.1.0.dist-info/METADATA,sha256=MGXs35HRiqrZaiiryQvINwoYbQH4_RUIuDJe7ygfwdw,6142
16
+ napari_dpr-0.1.0.dist-info/WHEEL,sha256=pkI-s5KKCTCXRcuamRCpmUHK9lBRiVf1mC9_VUZSXgc,101
17
+ napari_dpr-0.1.0.dist-info/entry_points.txt,sha256=EWQt54qiAOwySprF_niJSapFgqHgkTB2TNnyYXiVQa0,54
18
+ napari_dpr-0.1.0.dist-info/top_level.txt,sha256=i9hH6jDl1Ge8GHx1LoWvm1k5DLu4b7-59b5ceuaWxuI,11
19
+ napari_dpr-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-win_amd64
5
+
@@ -0,0 +1,2 @@
1
+ [napari.manifest]
2
+ napari-dpr = napari_dpr:napari.yaml
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 JenuC
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.
@@ -0,0 +1 @@
1
+ napari_dpr