pixelgpu 0.1.0__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.
- pixelgpu-0.1.0/LICENSE +201 -0
- pixelgpu-0.1.0/PKG-INFO +90 -0
- pixelgpu-0.1.0/README.md +67 -0
- pixelgpu-0.1.0/pixelgpu/__init__.py +5 -0
- pixelgpu-0.1.0/pixelgpu/analyzer.py +158 -0
- pixelgpu-0.1.0/pixelgpu/backends.py +55 -0
- pixelgpu-0.1.0/pixelgpu/cli.py +20 -0
- pixelgpu-0.1.0/pixelgpu/models.py +13 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/PKG-INFO +90 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/SOURCES.txt +14 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/dependency_links.txt +1 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/entry_points.txt +2 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/requires.txt +18 -0
- pixelgpu-0.1.0/pixelgpu.egg-info/top_level.txt +1 -0
- pixelgpu-0.1.0/pyproject.toml +24 -0
- pixelgpu-0.1.0/setup.cfg +4 -0
pixelgpu-0.1.0/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.
|
pixelgpu-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pixelgpu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cross backend image and pixel analysis with Python, CUDA, C++ and SYCL adapters
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: numpy>=1.23
|
|
9
|
+
Requires-Dist: Pillow>=9.0
|
|
10
|
+
Provides-Extra: cuda
|
|
11
|
+
Requires-Dist: cupy-cuda12x>=12.0; extra == "cuda"
|
|
12
|
+
Provides-Extra: sycl
|
|
13
|
+
Requires-Dist: dpctl>=0.15; extra == "sycl"
|
|
14
|
+
Requires-Dist: dpnp>=0.14; extra == "sycl"
|
|
15
|
+
Provides-Extra: notebook
|
|
16
|
+
Requires-Dist: matplotlib>=3.6; extra == "notebook"
|
|
17
|
+
Requires-Dist: ipython>=8; extra == "notebook"
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
20
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
21
|
+
Requires-Dist: pybind11>=2.11; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# pixelgpu
|
|
25
|
+
|
|
26
|
+
A starter Python package for image metadata inspection, pixel classification,
|
|
27
|
+
RGB/HEX frequency counting, block grouping, grayscale, vector maps,
|
|
28
|
+
quantization, visualizations, exports and backend selection.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install -e .
|
|
34
|
+
# Optional NVIDIA CUDA adapter
|
|
35
|
+
pip install -e ".[cuda]"
|
|
36
|
+
# Optional SYCL adapter (requires a compatible oneAPI/SYCL runtime and drivers)
|
|
37
|
+
pip install -e ".[sycl]"
|
|
38
|
+
# Notebook display helpers
|
|
39
|
+
pip install -e ".[notebook]"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from pixelgpu import ImageAnalyzer
|
|
46
|
+
|
|
47
|
+
analyzer = ImageAnalyzer("photo.png", backend="auto")
|
|
48
|
+
report = analyzer.analyze(block_size=16, quantize_levels=8)
|
|
49
|
+
|
|
50
|
+
print(report.metadata)
|
|
51
|
+
print(report.summary)
|
|
52
|
+
analyzer.display(max_pixels=100)
|
|
53
|
+
analyzer.save("results", formats=("json", "csv", "txt"))
|
|
54
|
+
analyzer.save_visualizations("results/maps")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
In Jupyter, `analyzer.display()` uses rich notebook output when IPython is
|
|
58
|
+
available. The pixel table is deliberately capped by `max_pixels` so large
|
|
59
|
+
images do not overwhelm notebook output. Full data remains available in
|
|
60
|
+
`report.pixels` and export files.
|
|
61
|
+
|
|
62
|
+
## Backends
|
|
63
|
+
|
|
64
|
+
- `python`: NumPy reference implementation, always available.
|
|
65
|
+
- `cuda`: CuPy adapter, NVIDIA CUDA runtime required.
|
|
66
|
+
- `sycl`: dpctl/dpnp adapter, compatible SYCL runtime required.
|
|
67
|
+
- `cpp`: optional pybind11 extension source is in `cpp/`; build it with CMake.
|
|
68
|
+
- `auto`: currently prefers CUDA when available, otherwise Python. SYCL can be
|
|
69
|
+
selected explicitly with `backend="sycl"`.
|
|
70
|
+
|
|
71
|
+
This is a starter implementation, not a claim that one binary works on every
|
|
72
|
+
GPU. GPU support depends on vendor drivers, runtime versions, architecture,
|
|
73
|
+
and installed Python packages. The SYCL adapter currently performs grayscale
|
|
74
|
+
and quantization operations through dpnp; the rest of the analysis pipeline
|
|
75
|
+
uses the common NumPy path.
|
|
76
|
+
|
|
77
|
+
## C++ extension
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
cmake -S cpp -B cpp/build
|
|
81
|
+
cmake --build cpp/build --config Release
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The generated extension is optional. The package remains usable without it.
|
|
85
|
+
|
|
86
|
+
## Output
|
|
87
|
+
|
|
88
|
+
`save()` writes a JSON report, CSV pixel rows, and a human-readable TXT summary.
|
|
89
|
+
`save_visualizations()` writes grayscale, quantized, RGB-channel and block
|
|
90
|
+
average maps as PNG files.
|
pixelgpu-0.1.0/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# pixelgpu
|
|
2
|
+
|
|
3
|
+
A starter Python package for image metadata inspection, pixel classification,
|
|
4
|
+
RGB/HEX frequency counting, block grouping, grayscale, vector maps,
|
|
5
|
+
quantization, visualizations, exports and backend selection.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install -e .
|
|
11
|
+
# Optional NVIDIA CUDA adapter
|
|
12
|
+
pip install -e ".[cuda]"
|
|
13
|
+
# Optional SYCL adapter (requires a compatible oneAPI/SYCL runtime and drivers)
|
|
14
|
+
pip install -e ".[sycl]"
|
|
15
|
+
# Notebook display helpers
|
|
16
|
+
pip install -e ".[notebook]"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from pixelgpu import ImageAnalyzer
|
|
23
|
+
|
|
24
|
+
analyzer = ImageAnalyzer("photo.png", backend="auto")
|
|
25
|
+
report = analyzer.analyze(block_size=16, quantize_levels=8)
|
|
26
|
+
|
|
27
|
+
print(report.metadata)
|
|
28
|
+
print(report.summary)
|
|
29
|
+
analyzer.display(max_pixels=100)
|
|
30
|
+
analyzer.save("results", formats=("json", "csv", "txt"))
|
|
31
|
+
analyzer.save_visualizations("results/maps")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
In Jupyter, `analyzer.display()` uses rich notebook output when IPython is
|
|
35
|
+
available. The pixel table is deliberately capped by `max_pixels` so large
|
|
36
|
+
images do not overwhelm notebook output. Full data remains available in
|
|
37
|
+
`report.pixels` and export files.
|
|
38
|
+
|
|
39
|
+
## Backends
|
|
40
|
+
|
|
41
|
+
- `python`: NumPy reference implementation, always available.
|
|
42
|
+
- `cuda`: CuPy adapter, NVIDIA CUDA runtime required.
|
|
43
|
+
- `sycl`: dpctl/dpnp adapter, compatible SYCL runtime required.
|
|
44
|
+
- `cpp`: optional pybind11 extension source is in `cpp/`; build it with CMake.
|
|
45
|
+
- `auto`: currently prefers CUDA when available, otherwise Python. SYCL can be
|
|
46
|
+
selected explicitly with `backend="sycl"`.
|
|
47
|
+
|
|
48
|
+
This is a starter implementation, not a claim that one binary works on every
|
|
49
|
+
GPU. GPU support depends on vendor drivers, runtime versions, architecture,
|
|
50
|
+
and installed Python packages. The SYCL adapter currently performs grayscale
|
|
51
|
+
and quantization operations through dpnp; the rest of the analysis pipeline
|
|
52
|
+
uses the common NumPy path.
|
|
53
|
+
|
|
54
|
+
## C++ extension
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
cmake -S cpp -B cpp/build
|
|
58
|
+
cmake --build cpp/build --config Release
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The generated extension is optional. The package remains usable without it.
|
|
62
|
+
|
|
63
|
+
## Output
|
|
64
|
+
|
|
65
|
+
`save()` writes a JSON report, CSV pixel rows, and a human-readable TXT summary.
|
|
66
|
+
`save_visualizations()` writes grayscale, quantized, RGB-channel and block
|
|
67
|
+
average maps as PNG files.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from collections import Counter
|
|
6
|
+
import numpy as np
|
|
7
|
+
from PIL import Image, ImageOps
|
|
8
|
+
from .backends import choose_backend, process_arrays
|
|
9
|
+
from .models import AnalysisReport
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger("pixelgpu")
|
|
12
|
+
if not log.handlers:
|
|
13
|
+
handler = logging.StreamHandler()
|
|
14
|
+
handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
|
|
15
|
+
log.addHandler(handler)
|
|
16
|
+
log.setLevel(logging.INFO)
|
|
17
|
+
|
|
18
|
+
class ImageAnalyzer:
|
|
19
|
+
"""Analyze an image and expose full arrays plus notebook-friendly summaries."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, image, backend="auto", logger=None):
|
|
22
|
+
self.path = Path(image) if isinstance(image, (str, Path)) else None
|
|
23
|
+
self.backend = choose_backend(backend)
|
|
24
|
+
self.logger = logger or log
|
|
25
|
+
try:
|
|
26
|
+
if isinstance(image, Image.Image):
|
|
27
|
+
pil = image.copy()
|
|
28
|
+
else:
|
|
29
|
+
pil = Image.open(self.path)
|
|
30
|
+
self.original_mode = pil.mode
|
|
31
|
+
self.original_format = pil.format
|
|
32
|
+
self.original_size_bytes = self.path.stat().st_size if self.path and self.path.exists() else None
|
|
33
|
+
self.image = ImageOps.exif_transpose(pil).convert("RGB")
|
|
34
|
+
self.rgb = np.asarray(self.image, dtype=np.uint8)
|
|
35
|
+
self.logger.info("Loaded image: %s", self.rgb.shape)
|
|
36
|
+
except Exception:
|
|
37
|
+
self.logger.exception("Unable to load image")
|
|
38
|
+
raise
|
|
39
|
+
|
|
40
|
+
def analyze(self, block_size=16, quantize_levels=8, top_colors=30):
|
|
41
|
+
try:
|
|
42
|
+
if block_size < 1:
|
|
43
|
+
raise ValueError("block_size must be >= 1")
|
|
44
|
+
if not 2 <= quantize_levels <= 256:
|
|
45
|
+
raise ValueError("quantize_levels must be between 2 and 256")
|
|
46
|
+
h, w, _ = self.rgb.shape
|
|
47
|
+
self.logger.info("Starting analysis using backend=%s", self.backend)
|
|
48
|
+
gray, quantized = process_arrays(self.rgb, self.backend, quantize_levels)
|
|
49
|
+
|
|
50
|
+
flat = self.rgb.reshape(-1, 3)
|
|
51
|
+
packed = (flat[:, 0].astype(np.uint32) << 16) | (flat[:, 1].astype(np.uint32) << 8) | flat[:, 2]
|
|
52
|
+
unique, counts = np.unique(packed, return_counts=True)
|
|
53
|
+
order = np.argsort(counts)[::-1][:top_colors]
|
|
54
|
+
colors = []
|
|
55
|
+
for idx in order:
|
|
56
|
+
value = int(unique[idx])
|
|
57
|
+
r, g, b = (value >> 16) & 255, (value >> 8) & 255, value & 255
|
|
58
|
+
colors.append({"rgb": [r, g, b], "hex": f"#{r:02X}{g:02X}{b:02X}", "count": int(counts[idx]), "fraction": float(counts[idx] / (h*w))})
|
|
59
|
+
|
|
60
|
+
bh = (h + block_size - 1) // block_size
|
|
61
|
+
bw = (w + block_size - 1) // block_size
|
|
62
|
+
block_map = np.zeros((bh, bw, 3), dtype=np.uint8)
|
|
63
|
+
for by in range(bh):
|
|
64
|
+
for bx in range(bw):
|
|
65
|
+
tile = self.rgb[by*block_size:min((by+1)*block_size,h), bx*block_size:min((bx+1)*block_size,w)]
|
|
66
|
+
block_map[by, bx] = np.rint(tile.mean(axis=(0,1))).astype(np.uint8)
|
|
67
|
+
|
|
68
|
+
metadata = {
|
|
69
|
+
"filename": self.path.name if self.path else None,
|
|
70
|
+
"format": self.original_format,
|
|
71
|
+
"original_mode": self.original_mode,
|
|
72
|
+
"normalized_mode": "RGB",
|
|
73
|
+
"width": w, "height": h, "channels": 3,
|
|
74
|
+
"bit_depth_per_channel": 8, "total_pixels": int(h*w),
|
|
75
|
+
"array_shape": list(self.rgb.shape), "dtype": str(self.rgb.dtype),
|
|
76
|
+
"file_size_bytes": self.original_size_bytes,
|
|
77
|
+
"backend": self.backend
|
|
78
|
+
}
|
|
79
|
+
summary = {
|
|
80
|
+
"unique_rgb_colors": int(len(unique)),
|
|
81
|
+
"mean_rgb": np.round(self.rgb.mean(axis=(0,1)), 3).tolist(),
|
|
82
|
+
"min_rgb": self.rgb.min(axis=(0,1)).tolist(),
|
|
83
|
+
"max_rgb": self.rgb.max(axis=(0,1)).tolist(),
|
|
84
|
+
"grayscale_mean": float(gray.mean()),
|
|
85
|
+
"quantization_levels": int(quantize_levels),
|
|
86
|
+
"block_size": int(block_size),
|
|
87
|
+
"block_grid": [int(bh), int(bw)]
|
|
88
|
+
}
|
|
89
|
+
self.report = AnalysisReport(metadata, summary, self.rgb, gray, quantized, block_map, colors)
|
|
90
|
+
self.logger.info("Analysis complete: %d pixels, %d unique colors", h*w, len(unique))
|
|
91
|
+
return self.report
|
|
92
|
+
except Exception:
|
|
93
|
+
self.logger.exception("Image analysis failed")
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
def _require_report(self):
|
|
97
|
+
if not hasattr(self, "report"):
|
|
98
|
+
return self.analyze()
|
|
99
|
+
return self.report
|
|
100
|
+
|
|
101
|
+
def display(self, max_pixels=100, show_maps=True):
|
|
102
|
+
report = self._require_report()
|
|
103
|
+
print(json.dumps({"metadata": report.metadata, "summary": report.summary, "top_colors": report.color_counts[:10]}, indent=2))
|
|
104
|
+
n = max(0, min(int(max_pixels), report.pixels.shape[0] * report.pixels.shape[1]))
|
|
105
|
+
sample = report.pixels.reshape(-1, 3)[:n]
|
|
106
|
+
print(f"\\nPixel sample: first {n} of {report.metadata['total_pixels']} pixels")
|
|
107
|
+
print("index | RGB | HEX")
|
|
108
|
+
for i, (r, g, b) in enumerate(sample):
|
|
109
|
+
print(f"{i:6d} | ({r:3d}, {g:3d}, {b:3d}) | #{r:02X}{g:02X}{b:02X}")
|
|
110
|
+
try:
|
|
111
|
+
from IPython.display import display, Markdown
|
|
112
|
+
import matplotlib.pyplot as plt
|
|
113
|
+
display(Markdown("### PixelGPU image maps"))
|
|
114
|
+
fig, axes = plt.subplots(1, 4, figsize=(16, 4))
|
|
115
|
+
axes[0].imshow(report.pixels); axes[0].set_title("RGB")
|
|
116
|
+
axes[1].imshow(report.grayscale, cmap="gray", vmin=0, vmax=255); axes[1].set_title("Grayscale")
|
|
117
|
+
axes[2].imshow(report.quantized); axes[2].set_title("Quantized")
|
|
118
|
+
axes[3].imshow(report.block_map); axes[3].set_title("Block average map")
|
|
119
|
+
for ax in axes: ax.axis("off")
|
|
120
|
+
plt.tight_layout()
|
|
121
|
+
display(fig)
|
|
122
|
+
plt.close(fig)
|
|
123
|
+
except ImportError:
|
|
124
|
+
if show_maps:
|
|
125
|
+
self.logger.info("Install pixelgpu[notebook] for inline maps.")
|
|
126
|
+
|
|
127
|
+
def save(self, directory="pixelgpu_output", formats=("json", "csv", "txt")):
|
|
128
|
+
report = self._require_report()
|
|
129
|
+
out = Path(directory); out.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
if "json" in formats:
|
|
131
|
+
payload = {"metadata": report.metadata, "summary": report.summary, "top_colors": report.color_counts}
|
|
132
|
+
(out / "analysis.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
133
|
+
if "csv" in formats:
|
|
134
|
+
with (out / "pixels.csv").open("w", newline="", encoding="utf-8") as f:
|
|
135
|
+
writer = csv.writer(f); writer.writerow(["x", "y", "r", "g", "b", "hex"])
|
|
136
|
+
h, w, _ = report.pixels.shape
|
|
137
|
+
for y in range(h):
|
|
138
|
+
for x in range(w):
|
|
139
|
+
r, g, b = map(int, report.pixels[y, x])
|
|
140
|
+
writer.writerow([x, y, r, g, b, f"#{r:02X}{g:02X}{b:02X}"])
|
|
141
|
+
if "txt" in formats:
|
|
142
|
+
(out / "analysis.txt").write_text(
|
|
143
|
+
"PIXELGPU IMAGE ANALYSIS\\n\\nMETADATA\\n" +
|
|
144
|
+
json.dumps(report.metadata, indent=2) + "\\n\\nSUMMARY\\n" +
|
|
145
|
+
json.dumps(report.summary, indent=2) + "\\n\\nTOP COLORS\\n" +
|
|
146
|
+
json.dumps(report.color_counts, indent=2), encoding="utf-8")
|
|
147
|
+
self.logger.info("Saved reports to %s", out.resolve())
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
def save_visualizations(self, directory="pixelgpu_output/maps"):
|
|
151
|
+
report = self._require_report()
|
|
152
|
+
out = Path(directory); out.mkdir(parents=True, exist_ok=True)
|
|
153
|
+
Image.fromarray(report.pixels).save(out / "rgb.png")
|
|
154
|
+
Image.fromarray(report.grayscale, mode="L").save(out / "grayscale.png")
|
|
155
|
+
Image.fromarray(report.quantized).save(out / "quantized.png")
|
|
156
|
+
Image.fromarray(report.block_map).resize((report.pixels.shape[1], report.pixels.shape[0]), Image.Resampling.NEAREST).save(out / "block_average_map.png")
|
|
157
|
+
self.logger.info("Saved visualization maps to %s", out.resolve())
|
|
158
|
+
return out
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
log = logging.getLogger("pixelgpu")
|
|
5
|
+
|
|
6
|
+
def choose_backend(requested):
|
|
7
|
+
requested = (requested or "auto").lower()
|
|
8
|
+
if requested == "auto":
|
|
9
|
+
try:
|
|
10
|
+
import cupy # noqa: F401
|
|
11
|
+
log.info("CUDA/CuPy detected; selecting CUDA backend.")
|
|
12
|
+
return "cuda"
|
|
13
|
+
except Exception:
|
|
14
|
+
log.info("CUDA not detected; selecting Python/NumPy backend.")
|
|
15
|
+
return "python"
|
|
16
|
+
if requested not in {"python", "cuda", "sycl", "cpp"}:
|
|
17
|
+
raise ValueError(f"Unknown backend: {requested}")
|
|
18
|
+
return requested
|
|
19
|
+
|
|
20
|
+
def process_arrays(rgb, backend, levels):
|
|
21
|
+
"""Return grayscale and quantized arrays as NumPy arrays."""
|
|
22
|
+
if backend == "cuda":
|
|
23
|
+
try:
|
|
24
|
+
import cupy as cp
|
|
25
|
+
x = cp.asarray(rgb, dtype=cp.float32)
|
|
26
|
+
gray = cp.rint(0.299*x[..., 0] + 0.587*x[..., 1] + 0.114*x[..., 2])
|
|
27
|
+
q = cp.floor(x / 256.0 * levels) * (256.0 / levels)
|
|
28
|
+
return cp.asnumpy(gray.astype(cp.uint8)), cp.asnumpy(cp.clip(q, 0, 255).astype(cp.uint8))
|
|
29
|
+
except Exception as exc:
|
|
30
|
+
raise RuntimeError("CUDA backend requested but CuPy/CUDA execution failed. Install a matching CuPy build and CUDA runtime.") from exc
|
|
31
|
+
|
|
32
|
+
if backend == "sycl":
|
|
33
|
+
try:
|
|
34
|
+
import dpctl.tensor as dpt
|
|
35
|
+
import dpnp as dp
|
|
36
|
+
x = dp.asarray(rgb, dtype=dp.float32)
|
|
37
|
+
gray = dp.rint(0.299*x[..., 0] + 0.587*x[..., 1] + 0.114*x[..., 2])
|
|
38
|
+
q = dp.floor(x / 256.0 * levels) * (256.0 / levels)
|
|
39
|
+
return np.asarray(gray.astype(dp.uint8)), np.asarray(dp.clip(q, 0, 255).astype(dp.uint8))
|
|
40
|
+
except Exception as exc:
|
|
41
|
+
raise RuntimeError("SYCL backend requested but dpctl/dpnp or a compatible SYCL runtime is unavailable.") from exc
|
|
42
|
+
|
|
43
|
+
if backend == "cpp":
|
|
44
|
+
try:
|
|
45
|
+
from . import _pixelgpu_cpp
|
|
46
|
+
gray = _pixelgpu_cpp.grayscale(rgb)
|
|
47
|
+
quantized = _pixelgpu_cpp.quantize(rgb, int(levels))
|
|
48
|
+
return np.asarray(gray), np.asarray(quantized)
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
raise RuntimeError("C++ extension unavailable. Build the optional extension in the cpp/ directory.") from exc
|
|
51
|
+
|
|
52
|
+
x = rgb.astype(np.float32)
|
|
53
|
+
gray = np.rint(0.299*x[..., 0] + 0.587*x[..., 1] + 0.114*x[..., 2]).astype(np.uint8)
|
|
54
|
+
quantized = (np.floor(x / 256.0 * levels) * (256.0 / levels)).clip(0, 255).astype(np.uint8)
|
|
55
|
+
return gray, quantized
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from . import ImageAnalyzer
|
|
3
|
+
|
|
4
|
+
def main():
|
|
5
|
+
parser = argparse.ArgumentParser(description="Analyze image pixels with pixelgpu")
|
|
6
|
+
parser.add_argument("image")
|
|
7
|
+
parser.add_argument("--backend", default="auto", choices=["auto", "python", "cuda", "sycl", "cpp"])
|
|
8
|
+
parser.add_argument("--output", default="pixelgpu_output")
|
|
9
|
+
parser.add_argument("--block-size", type=int, default=16)
|
|
10
|
+
parser.add_argument("--levels", type=int, default=8)
|
|
11
|
+
parser.add_argument("--max-pixels", type=int, default=100)
|
|
12
|
+
args = parser.parse_args()
|
|
13
|
+
analyzer = ImageAnalyzer(args.image, backend=args.backend)
|
|
14
|
+
analyzer.analyze(block_size=args.block_size, quantize_levels=args.levels)
|
|
15
|
+
analyzer.display(max_pixels=args.max_pixels)
|
|
16
|
+
analyzer.save(args.output)
|
|
17
|
+
analyzer.save_visualizations(args.output + "/maps")
|
|
18
|
+
|
|
19
|
+
if __name__ == "__main__":
|
|
20
|
+
main()
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any, Dict
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class AnalysisReport:
|
|
7
|
+
metadata: Dict[str, Any]
|
|
8
|
+
summary: Dict[str, Any]
|
|
9
|
+
pixels: np.ndarray
|
|
10
|
+
grayscale: np.ndarray
|
|
11
|
+
quantized: np.ndarray
|
|
12
|
+
block_map: np.ndarray
|
|
13
|
+
color_counts: list
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pixelgpu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cross backend image and pixel analysis with Python, CUDA, C++ and SYCL adapters
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: numpy>=1.23
|
|
9
|
+
Requires-Dist: Pillow>=9.0
|
|
10
|
+
Provides-Extra: cuda
|
|
11
|
+
Requires-Dist: cupy-cuda12x>=12.0; extra == "cuda"
|
|
12
|
+
Provides-Extra: sycl
|
|
13
|
+
Requires-Dist: dpctl>=0.15; extra == "sycl"
|
|
14
|
+
Requires-Dist: dpnp>=0.14; extra == "sycl"
|
|
15
|
+
Provides-Extra: notebook
|
|
16
|
+
Requires-Dist: matplotlib>=3.6; extra == "notebook"
|
|
17
|
+
Requires-Dist: ipython>=8; extra == "notebook"
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
20
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
21
|
+
Requires-Dist: pybind11>=2.11; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# pixelgpu
|
|
25
|
+
|
|
26
|
+
A starter Python package for image metadata inspection, pixel classification,
|
|
27
|
+
RGB/HEX frequency counting, block grouping, grayscale, vector maps,
|
|
28
|
+
quantization, visualizations, exports and backend selection.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install -e .
|
|
34
|
+
# Optional NVIDIA CUDA adapter
|
|
35
|
+
pip install -e ".[cuda]"
|
|
36
|
+
# Optional SYCL adapter (requires a compatible oneAPI/SYCL runtime and drivers)
|
|
37
|
+
pip install -e ".[sycl]"
|
|
38
|
+
# Notebook display helpers
|
|
39
|
+
pip install -e ".[notebook]"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from pixelgpu import ImageAnalyzer
|
|
46
|
+
|
|
47
|
+
analyzer = ImageAnalyzer("photo.png", backend="auto")
|
|
48
|
+
report = analyzer.analyze(block_size=16, quantize_levels=8)
|
|
49
|
+
|
|
50
|
+
print(report.metadata)
|
|
51
|
+
print(report.summary)
|
|
52
|
+
analyzer.display(max_pixels=100)
|
|
53
|
+
analyzer.save("results", formats=("json", "csv", "txt"))
|
|
54
|
+
analyzer.save_visualizations("results/maps")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
In Jupyter, `analyzer.display()` uses rich notebook output when IPython is
|
|
58
|
+
available. The pixel table is deliberately capped by `max_pixels` so large
|
|
59
|
+
images do not overwhelm notebook output. Full data remains available in
|
|
60
|
+
`report.pixels` and export files.
|
|
61
|
+
|
|
62
|
+
## Backends
|
|
63
|
+
|
|
64
|
+
- `python`: NumPy reference implementation, always available.
|
|
65
|
+
- `cuda`: CuPy adapter, NVIDIA CUDA runtime required.
|
|
66
|
+
- `sycl`: dpctl/dpnp adapter, compatible SYCL runtime required.
|
|
67
|
+
- `cpp`: optional pybind11 extension source is in `cpp/`; build it with CMake.
|
|
68
|
+
- `auto`: currently prefers CUDA when available, otherwise Python. SYCL can be
|
|
69
|
+
selected explicitly with `backend="sycl"`.
|
|
70
|
+
|
|
71
|
+
This is a starter implementation, not a claim that one binary works on every
|
|
72
|
+
GPU. GPU support depends on vendor drivers, runtime versions, architecture,
|
|
73
|
+
and installed Python packages. The SYCL adapter currently performs grayscale
|
|
74
|
+
and quantization operations through dpnp; the rest of the analysis pipeline
|
|
75
|
+
uses the common NumPy path.
|
|
76
|
+
|
|
77
|
+
## C++ extension
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
cmake -S cpp -B cpp/build
|
|
81
|
+
cmake --build cpp/build --config Release
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The generated extension is optional. The package remains usable without it.
|
|
85
|
+
|
|
86
|
+
## Output
|
|
87
|
+
|
|
88
|
+
`save()` writes a JSON report, CSV pixel rows, and a human-readable TXT summary.
|
|
89
|
+
`save_visualizations()` writes grayscale, quantized, RGB-channel and block
|
|
90
|
+
average maps as PNG files.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
pixelgpu/__init__.py
|
|
5
|
+
pixelgpu/analyzer.py
|
|
6
|
+
pixelgpu/backends.py
|
|
7
|
+
pixelgpu/cli.py
|
|
8
|
+
pixelgpu/models.py
|
|
9
|
+
pixelgpu.egg-info/PKG-INFO
|
|
10
|
+
pixelgpu.egg-info/SOURCES.txt
|
|
11
|
+
pixelgpu.egg-info/dependency_links.txt
|
|
12
|
+
pixelgpu.egg-info/entry_points.txt
|
|
13
|
+
pixelgpu.egg-info/requires.txt
|
|
14
|
+
pixelgpu.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pixelgpu
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pixelgpu"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Cross backend image and pixel analysis with Python, CUDA, C++ and SYCL adapters"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = ["numpy>=1.23", "Pillow>=9.0"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
cuda = ["cupy-cuda12x>=12.0"]
|
|
15
|
+
sycl = ["dpctl>=0.15", "dpnp>=0.14"]
|
|
16
|
+
notebook = ["matplotlib>=3.6", "ipython>=8"]
|
|
17
|
+
dev = ["pytest>=7", "build>=1", "pybind11>=2.11"]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
pixelgpu = "pixelgpu.cli:main"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
where = ["."]
|
|
24
|
+
include = ["pixelgpu*"]
|
pixelgpu-0.1.0/setup.cfg
ADDED