image-array-and-histogram 1.1.7__tar.gz → 2.0.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.
Files changed (40) hide show
  1. image_array_and_histogram-2.0.0/PKG-INFO +267 -0
  2. image_array_and_histogram-2.0.0/README.md +224 -0
  3. image_array_and_histogram-2.0.0/image_array_and_histogram/__init__.py +34 -0
  4. image_array_and_histogram-2.0.0/image_array_and_histogram/__main__.py +5 -0
  5. image_array_and_histogram-2.0.0/image_array_and_histogram/_accumulator.py +202 -0
  6. image_array_and_histogram-2.0.0/image_array_and_histogram/_compare.py +114 -0
  7. image_array_and_histogram-2.0.0/image_array_and_histogram/_convert.py +233 -0
  8. image_array_and_histogram-2.0.0/image_array_and_histogram/_histogram.py +168 -0
  9. image_array_and_histogram-2.0.0/image_array_and_histogram/_report.py +178 -0
  10. image_array_and_histogram-2.0.0/image_array_and_histogram/_stats.py +210 -0
  11. image_array_and_histogram-2.0.0/image_array_and_histogram/_types.py +16 -0
  12. image_array_and_histogram-2.0.0/image_array_and_histogram/cli.py +290 -0
  13. image_array_and_histogram-2.0.0/image_array_and_histogram/py.typed +0 -0
  14. image_array_and_histogram-2.0.0/image_array_and_histogram.egg-info/PKG-INFO +267 -0
  15. image_array_and_histogram-2.0.0/image_array_and_histogram.egg-info/SOURCES.txt +29 -0
  16. image_array_and_histogram-2.0.0/image_array_and_histogram.egg-info/entry_points.txt +2 -0
  17. image_array_and_histogram-2.0.0/image_array_and_histogram.egg-info/requires.txt +15 -0
  18. image_array_and_histogram-2.0.0/pyproject.toml +92 -0
  19. image_array_and_histogram-2.0.0/tests/test_accumulator.py +154 -0
  20. image_array_and_histogram-2.0.0/tests/test_cli.py +399 -0
  21. image_array_and_histogram-2.0.0/tests/test_compare.py +99 -0
  22. image_array_and_histogram-2.0.0/tests/test_convert.py +285 -0
  23. image_array_and_histogram-2.0.0/tests/test_histogram.py +218 -0
  24. image_array_and_histogram-2.0.0/tests/test_package.py +30 -0
  25. image_array_and_histogram-2.0.0/tests/test_properties.py +60 -0
  26. image_array_and_histogram-2.0.0/tests/test_readme_examples.py +23 -0
  27. image_array_and_histogram-2.0.0/tests/test_stats.py +129 -0
  28. image_array_and_histogram-1.1.7/PKG-INFO +0 -95
  29. image_array_and_histogram-1.1.7/README.md +0 -68
  30. image_array_and_histogram-1.1.7/image_array_and_histogram/__init__.py +0 -27
  31. image_array_and_histogram-1.1.7/image_array_and_histogram/main.py +0 -136
  32. image_array_and_histogram-1.1.7/image_array_and_histogram.egg-info/PKG-INFO +0 -95
  33. image_array_and_histogram-1.1.7/image_array_and_histogram.egg-info/SOURCES.txt +0 -11
  34. image_array_and_histogram-1.1.7/image_array_and_histogram.egg-info/requires.txt +0 -8
  35. image_array_and_histogram-1.1.7/pyproject.toml +0 -32
  36. image_array_and_histogram-1.1.7/tests/test_basic.py +0 -336
  37. {image_array_and_histogram-1.1.7 → image_array_and_histogram-2.0.0}/LICENSE +0 -0
  38. {image_array_and_histogram-1.1.7 → image_array_and_histogram-2.0.0}/image_array_and_histogram.egg-info/dependency_links.txt +0 -0
  39. {image_array_and_histogram-1.1.7 → image_array_and_histogram-2.0.0}/image_array_and_histogram.egg-info/top_level.txt +0 -0
  40. {image_array_and_histogram-1.1.7 → image_array_and_histogram-2.0.0}/setup.cfg +0 -0
@@ -0,0 +1,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: image_array_and_histogram
3
+ Version: 2.0.0
4
+ Summary: Fast image histograms, exposure statistics and histogram comparison for NumPy/Pillow, with a CLI.
5
+ Author: Rishi Raj Singh Chauhan
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rishi-chauhan/my-packages
8
+ Project-URL: Issue Tracker, https://github.com/rishi-chauhan/my-packages/issues
9
+ Project-URL: Changelog, https://github.com/rishi-chauhan/my-packages/blob/master/CHANGELOG.md
10
+ Keywords: image,histogram,numpy,pillow,grayscale,statistics,exposure,dataset,cli
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Environment :: Console
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Topic :: Multimedia :: Graphics
24
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: numpy>=1.23
30
+ Requires-Dist: Pillow>=10.0
31
+ Provides-Extra: plot
32
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=8; extra == "dev"
35
+ Requires-Dist: pytest-cov>=5; extra == "dev"
36
+ Requires-Dist: hypothesis>=6.100; extra == "dev"
37
+ Requires-Dist: build; extra == "dev"
38
+ Requires-Dist: twine; extra == "dev"
39
+ Requires-Dist: ruff>=0.6; extra == "dev"
40
+ Requires-Dist: mypy>=1.10; extra == "dev"
41
+ Requires-Dist: matplotlib>=3.7; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # image-array-and-histogram
45
+
46
+ [![CI](https://github.com/rishi-chauhan/my-packages/actions/workflows/ci.yml/badge.svg)](https://github.com/rishi-chauhan/my-packages/actions/workflows/ci.yml)
47
+ [![PyPI version](https://img.shields.io/pypi/v/image-array-and-histogram.svg)](https://pypi.org/project/image-array-and-histogram/)
48
+ [![Python versions](https://img.shields.io/pypi/pyversions/image-array-and-histogram.svg)](https://pypi.org/project/image-array-and-histogram/)
49
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
50
+
51
+ Fast image histograms, exposure statistics and histogram comparison for NumPy and Pillow,
52
+ with a command-line tool.
53
+
54
+ If you just need a 256-bin histogram of one image, `img.convert("L").histogram()` is enough.
55
+ This library adds what the built-ins don't: per-channel and 16-bit/float histograms, exposure
56
+ statistics (percentiles, clipping, entropy), histogram comparison, streaming accumulation over
57
+ whole datasets, and the `imghist` CLI. It depends only on NumPy and Pillow, and the hot paths
58
+ are vectorised (`np.bincount` and Pillow's C code, never Python loops).
59
+
60
+ ## Installation
61
+
62
+ ```sh
63
+ pip install image-array-and-histogram
64
+ # with plotting support for `imghist --plot`:
65
+ pip install "image-array-and-histogram[plot]"
66
+ ```
67
+
68
+ Requires Python 3.10+, NumPy 1.23+ and Pillow 10+. The package ships type hints.
69
+
70
+ ## Quick start
71
+
72
+ ```python
73
+ from PIL import Image
74
+
75
+ from image_array_and_histogram import HistAccumulator, compare_hist, get_hist, hist_stats
76
+
77
+ img = Image.open("photo.jpg")
78
+
79
+ # Histograms: 256 gray bins, or one row per RGB channel
80
+ gray = get_hist(img) # ndarray, shape (256,), int64
81
+ rgb = get_hist(img, channels="rgb") # shape (3, 256)
82
+ coarse = get_hist(img, bins=16, density=True) # 16 bins summing to 1.0
83
+
84
+ # Exposure statistics, computed from the histogram
85
+ stats = hist_stats(img)
86
+ print(f"mean {stats.mean:.1f}, median {stats.median}, p99 {stats.percentiles[99]}")
87
+ print(f"blown highlights: {stats.clipped_high:.2%}")
88
+
89
+ # Compare two images (1.0 = identical for intersection)
90
+ other = img.rotate(90)
91
+ print(compare_hist(get_hist(img), get_hist(other), method="intersection"))
92
+
93
+ # Accumulate one histogram over many images without holding them in memory
94
+ acc = HistAccumulator(channels="rgb")
95
+ for path in ["photo.jpg", "photo.jpg"]:
96
+ with Image.open(path) as im:
97
+ acc.update(im)
98
+ print(acc.n_images, acc.stats()["r"].mean)
99
+ ```
100
+
101
+ 16-bit images keep their full precision:
102
+
103
+ ```python
104
+ import numpy as np
105
+
106
+ from image_array_and_histogram import get_hist, hist_stats
107
+
108
+ deep = np.random.default_rng(0).integers(0, 65536, size=(480, 640), dtype=np.uint16)
109
+ counts = get_hist(deep, bins=1024) # range defaults to (0, 65536) for uint16
110
+ print(hist_stats(deep, bins=65536).median)
111
+ ```
112
+
113
+ ## Command line
114
+
115
+ ```bash
116
+ imghist stats photo.jpg
117
+ imghist stats ./dataset -r --channels rgb -j 0
118
+ imghist stats ./dataset -r --format csv --per-file -o report.csv
119
+ imghist compare day.jpg night.jpg --method bhattacharyya
120
+ pip install "image-array-and-histogram[plot]" && imghist stats ./dataset -r --plot hist.png
121
+ ```
122
+
123
+ Example output:
124
+
125
+ ```text
126
+ imghist: 1,204 images (3 skipped) · channel: gray · 256 bins
127
+
128
+ count 14,412,000,000
129
+ mean 118.42 std 61.07
130
+ min 0 max 255
131
+ median 112 p1 3 p5 14 p25 69 p75 167 p95 228 p99 249
132
+ entropy 7.62 bits
133
+ clipped low 0.41% high 1.87%
134
+
135
+ ▁▁▂▃▄▅▆▇██▇▆▅▅▄▄▃▃▃▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂
136
+ 0 255
137
+ ```
138
+
139
+ `imghist stats PATH [PATH ...]` options:
140
+
141
+ | Option | Default | Meaning |
142
+ |---|---|---|
143
+ | `-r, --recursive` | off | recurse into directories |
144
+ | `--ext` | `.png,.jpg,.jpeg,.tif,.tiff,.bmp,.webp,.gif` | extensions to include (case-insensitive) |
145
+ | `--channels` | `gray` | `gray` or `rgb` |
146
+ | `--bins` | `256` | number of bins |
147
+ | `--range LO HI` | dtype default | histogram range; required for float images and to mix 8/16-bit images |
148
+ | `--per-file` | off | also report each file |
149
+ | `--format` | `text` | `text`, `json` or `csv` |
150
+ | `--width` | `64` | width of the text histogram |
151
+ | `--plot FILE` | none | save a plot (needs the `[plot]` extra) |
152
+ | `-j, --jobs` | `1` | worker processes; `0` = one per CPU |
153
+ | `--strict` | off | stop at the first unreadable file instead of skipping it |
154
+ | `-o, --output FILE` | stdout | write the report to a file |
155
+
156
+ `imghist compare A B` accepts files or directories (a directory is accumulated into one
157
+ histogram) and the same discovery options, plus `--method` and `--format text|json`.
158
+
159
+ Hidden files and directories are skipped. Unreadable files are reported on stderr and skipped.
160
+ Exit codes: `0` success, `1` no images found / none readable / `--strict` failure, `2` usage
161
+ error. `python -m image_array_and_histogram` works too.
162
+
163
+ ## API reference
164
+
165
+ All functions accept a `PIL.Image.Image` or an array: `(H, W)` grayscale, or `(H, W, 3)` /
166
+ `(H, W, 4)` RGB(A) (alpha is ignored). 8-bit, 16-bit, other integer and float data are
167
+ supported. Booleans are treated as 0/255. NaN/inf values raise `ValueError`.
168
+
169
+ ### `get_hist(image, *, channels="gray", bins=256, value_range=None, density=False)`
170
+
171
+ Returns int64 counts (float64 with `density=True`) of shape `(bins,)` for `"gray"` or
172
+ `(3, bins)` for `"rgb"` (rows R, G, B).
173
+
174
+ - `value_range` defaults by dtype: uint8 `(0, 256)`, uint16 `(0, 65536)`, other integers
175
+ `(min, max + 1)`, floats `(0, 1)` if all data is in [0, 1], otherwise `(min, max)`.
176
+ - Bin edges are `np.linspace(low, high, bins + 1)`. Bins are half-open except the last, which
177
+ includes `high`, and values outside the range are ignored (same as `np.histogram`).
178
+ - Grayscale conversion uses ITU-R 601-2 luma (`0.299 R + 0.587 G + 0.114 B`), via Pillow for
179
+ 8-bit data, so arrays and PIL images give identical results.
180
+
181
+ ### `hist_stats(image, *, channels="gray", bins=256, value_range=None, percentiles=(1, 5, 25, 50, 75, 95, 99))`
182
+
183
+ Returns a `HistStats` (or `{"r": ..., "g": ..., "b": ...}` for `"rgb"`) with `count`, `mean`,
184
+ `std` (population), `min`, `max`, `median`, `percentiles`, `entropy` (bits), `clipped_low` and
185
+ `clipped_high` (fraction of pixels in the first and last bin). `HistStats.to_dict()` gives a
186
+ JSON-ready dict with percentile keys like `"p5"`.
187
+
188
+ Statistics are computed from the histogram in O(bins). They are exact for integer data with
189
+ bin width 1 (the uint8 default) and approximate to bin resolution otherwise. Percentiles use
190
+ the nearest-rank (inverted CDF) method.
191
+
192
+ ### `stats_from_counts(counts, edges, percentiles=...)`
193
+
194
+ The same statistics for a histogram you already have (`counts` of shape `(bins,)`, `edges` of
195
+ shape `(bins + 1,)`).
196
+
197
+ ### `compare_hist(h1, h2, *, method="intersection")`
198
+
199
+ Compares two histograms of the same shape and returns a float. Histograms are normalised to
200
+ sum to 1 first (except for `correlation`), so images of different sizes compare fairly. For
201
+ `(channels, bins)` input the per-channel scores are averaged.
202
+
203
+ | method | range | identical | definition |
204
+ |---|---|---|---|
205
+ | `intersection` | [0, 1] | 1 | `sum(min(p, q))` |
206
+ | `chi2` | [0, 1] | 0 | `0.5 * sum((p - q)² / (p + q))` |
207
+ | `bhattacharyya` | [0, 1] | 0 | `sqrt(1 - sum(sqrt(p * q)))` (Hellinger form) |
208
+ | `correlation` | [-1, 1] | 1 | Pearson r of the raw counts |
209
+ | `emd` | [0, bins - 1] | 0 | `sum(abs(cumsum(p) - cumsum(q)))`, Earth Mover's distance in bins |
210
+
211
+ ### `HistAccumulator(*, channels="gray", bins=256, value_range=None)`
212
+
213
+ Streams images into one histogram: `update(image)`, `merge(other)` (for multiprocessing),
214
+ `counts` (read-only), `edges`, `n_images` and `stats(percentiles)`. Without `value_range`, the
215
+ range comes from the first image's dtype (uint8 or uint16); float and other integer images
216
+ need an explicit `value_range` so bins line up across images.
217
+
218
+ ### `get_image_array(image, *, mode="gray")`
219
+
220
+ Returns a PIL image as an array: `"gray"` gives `(H, W)`, `"rgb"` gives `(H, W, 3)`, `"keep"`
221
+ gives `np.asarray(image)` unchanged. The native bit depth is kept (16-bit images give uint16).
222
+
223
+ ### `array_to_image(arr, width=None, height=None, *, clip=True)`
224
+
225
+ Builds a PIL image from a 1-D array (with `width` and `height`), an `(H, W)` array (mode `L`, or
226
+ lossless `I;16` for uint16) or an `(H, W, 3/4)` array (`RGB`/`RGBA`). Other dtypes are converted
227
+ to 8 bits: floats are rounded (not truncated); values outside [0, 255] are clipped with a
228
+ `RuntimeWarning` when `clip=True`, or raise `ValueError` when `clip=False`.
229
+
230
+ ## Migrating from 1.x
231
+
232
+ | 1.x | 2.0 |
233
+ |---|---|
234
+ | `getImageArray(img)`, `getHist(x)`, `getImageFromArray(a, w, h)` | removed; use `get_image_array`, `get_hist`, `array_to_image` |
235
+ | `get_hist(x)` returns a `list` | returns an `np.ndarray`; call `.tolist()` if you need a list |
236
+ | `get_hist(x, as_density=True)` | `get_hist(x, density=True)` |
237
+ | `get_image_array(img, ensure_grayscale=True)` | `get_image_array(img)` (`mode="gray"`) |
238
+ | `get_image_array(img, ensure_grayscale=False)` | `get_image_array(img, mode="keep")` |
239
+ | `array_to_image(a, validate_range=False)` | `array_to_image(a, clip=False)` |
240
+ | `from image_array_and_histogram.main import ...` | `from image_array_and_histogram import ...` |
241
+
242
+ Behaviour changes to watch for:
243
+
244
+ - 16-bit images are no longer reduced to 8 bits: `get_image_array` returns uint16 and
245
+ `get_hist` uses the range `(0, 65536)`. If you relied on 8-bit output, convert first with
246
+ `img.convert("L")`.
247
+ - `array_to_image` now accepts `(H, W, 3/4)` arrays (RGB/RGBA) instead of raising, and keeps 2-D
248
+ uint16 arrays as 16-bit images.
249
+
250
+ ## Development
251
+
252
+ ```sh
253
+ git clone https://github.com/rishi-chauhan/my-packages.git
254
+ cd my-packages
255
+ pip install -e ".[dev]"
256
+ ruff check . && ruff format --check . && mypy
257
+ pytest --cov=image_array_and_histogram --cov-fail-under=95
258
+ python benchmarks/bench_hist.py # optional performance check
259
+ ```
260
+
261
+ ## Contributing
262
+
263
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
264
+
265
+ ## License
266
+
267
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,224 @@
1
+ # image-array-and-histogram
2
+
3
+ [![CI](https://github.com/rishi-chauhan/my-packages/actions/workflows/ci.yml/badge.svg)](https://github.com/rishi-chauhan/my-packages/actions/workflows/ci.yml)
4
+ [![PyPI version](https://img.shields.io/pypi/v/image-array-and-histogram.svg)](https://pypi.org/project/image-array-and-histogram/)
5
+ [![Python versions](https://img.shields.io/pypi/pyversions/image-array-and-histogram.svg)](https://pypi.org/project/image-array-and-histogram/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Fast image histograms, exposure statistics and histogram comparison for NumPy and Pillow,
9
+ with a command-line tool.
10
+
11
+ If you just need a 256-bin histogram of one image, `img.convert("L").histogram()` is enough.
12
+ This library adds what the built-ins don't: per-channel and 16-bit/float histograms, exposure
13
+ statistics (percentiles, clipping, entropy), histogram comparison, streaming accumulation over
14
+ whole datasets, and the `imghist` CLI. It depends only on NumPy and Pillow, and the hot paths
15
+ are vectorised (`np.bincount` and Pillow's C code, never Python loops).
16
+
17
+ ## Installation
18
+
19
+ ```sh
20
+ pip install image-array-and-histogram
21
+ # with plotting support for `imghist --plot`:
22
+ pip install "image-array-and-histogram[plot]"
23
+ ```
24
+
25
+ Requires Python 3.10+, NumPy 1.23+ and Pillow 10+. The package ships type hints.
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ from PIL import Image
31
+
32
+ from image_array_and_histogram import HistAccumulator, compare_hist, get_hist, hist_stats
33
+
34
+ img = Image.open("photo.jpg")
35
+
36
+ # Histograms: 256 gray bins, or one row per RGB channel
37
+ gray = get_hist(img) # ndarray, shape (256,), int64
38
+ rgb = get_hist(img, channels="rgb") # shape (3, 256)
39
+ coarse = get_hist(img, bins=16, density=True) # 16 bins summing to 1.0
40
+
41
+ # Exposure statistics, computed from the histogram
42
+ stats = hist_stats(img)
43
+ print(f"mean {stats.mean:.1f}, median {stats.median}, p99 {stats.percentiles[99]}")
44
+ print(f"blown highlights: {stats.clipped_high:.2%}")
45
+
46
+ # Compare two images (1.0 = identical for intersection)
47
+ other = img.rotate(90)
48
+ print(compare_hist(get_hist(img), get_hist(other), method="intersection"))
49
+
50
+ # Accumulate one histogram over many images without holding them in memory
51
+ acc = HistAccumulator(channels="rgb")
52
+ for path in ["photo.jpg", "photo.jpg"]:
53
+ with Image.open(path) as im:
54
+ acc.update(im)
55
+ print(acc.n_images, acc.stats()["r"].mean)
56
+ ```
57
+
58
+ 16-bit images keep their full precision:
59
+
60
+ ```python
61
+ import numpy as np
62
+
63
+ from image_array_and_histogram import get_hist, hist_stats
64
+
65
+ deep = np.random.default_rng(0).integers(0, 65536, size=(480, 640), dtype=np.uint16)
66
+ counts = get_hist(deep, bins=1024) # range defaults to (0, 65536) for uint16
67
+ print(hist_stats(deep, bins=65536).median)
68
+ ```
69
+
70
+ ## Command line
71
+
72
+ ```bash
73
+ imghist stats photo.jpg
74
+ imghist stats ./dataset -r --channels rgb -j 0
75
+ imghist stats ./dataset -r --format csv --per-file -o report.csv
76
+ imghist compare day.jpg night.jpg --method bhattacharyya
77
+ pip install "image-array-and-histogram[plot]" && imghist stats ./dataset -r --plot hist.png
78
+ ```
79
+
80
+ Example output:
81
+
82
+ ```text
83
+ imghist: 1,204 images (3 skipped) · channel: gray · 256 bins
84
+
85
+ count 14,412,000,000
86
+ mean 118.42 std 61.07
87
+ min 0 max 255
88
+ median 112 p1 3 p5 14 p25 69 p75 167 p95 228 p99 249
89
+ entropy 7.62 bits
90
+ clipped low 0.41% high 1.87%
91
+
92
+ ▁▁▂▃▄▅▆▇██▇▆▅▅▄▄▃▃▃▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂
93
+ 0 255
94
+ ```
95
+
96
+ `imghist stats PATH [PATH ...]` options:
97
+
98
+ | Option | Default | Meaning |
99
+ |---|---|---|
100
+ | `-r, --recursive` | off | recurse into directories |
101
+ | `--ext` | `.png,.jpg,.jpeg,.tif,.tiff,.bmp,.webp,.gif` | extensions to include (case-insensitive) |
102
+ | `--channels` | `gray` | `gray` or `rgb` |
103
+ | `--bins` | `256` | number of bins |
104
+ | `--range LO HI` | dtype default | histogram range; required for float images and to mix 8/16-bit images |
105
+ | `--per-file` | off | also report each file |
106
+ | `--format` | `text` | `text`, `json` or `csv` |
107
+ | `--width` | `64` | width of the text histogram |
108
+ | `--plot FILE` | none | save a plot (needs the `[plot]` extra) |
109
+ | `-j, --jobs` | `1` | worker processes; `0` = one per CPU |
110
+ | `--strict` | off | stop at the first unreadable file instead of skipping it |
111
+ | `-o, --output FILE` | stdout | write the report to a file |
112
+
113
+ `imghist compare A B` accepts files or directories (a directory is accumulated into one
114
+ histogram) and the same discovery options, plus `--method` and `--format text|json`.
115
+
116
+ Hidden files and directories are skipped. Unreadable files are reported on stderr and skipped.
117
+ Exit codes: `0` success, `1` no images found / none readable / `--strict` failure, `2` usage
118
+ error. `python -m image_array_and_histogram` works too.
119
+
120
+ ## API reference
121
+
122
+ All functions accept a `PIL.Image.Image` or an array: `(H, W)` grayscale, or `(H, W, 3)` /
123
+ `(H, W, 4)` RGB(A) (alpha is ignored). 8-bit, 16-bit, other integer and float data are
124
+ supported. Booleans are treated as 0/255. NaN/inf values raise `ValueError`.
125
+
126
+ ### `get_hist(image, *, channels="gray", bins=256, value_range=None, density=False)`
127
+
128
+ Returns int64 counts (float64 with `density=True`) of shape `(bins,)` for `"gray"` or
129
+ `(3, bins)` for `"rgb"` (rows R, G, B).
130
+
131
+ - `value_range` defaults by dtype: uint8 `(0, 256)`, uint16 `(0, 65536)`, other integers
132
+ `(min, max + 1)`, floats `(0, 1)` if all data is in [0, 1], otherwise `(min, max)`.
133
+ - Bin edges are `np.linspace(low, high, bins + 1)`. Bins are half-open except the last, which
134
+ includes `high`, and values outside the range are ignored (same as `np.histogram`).
135
+ - Grayscale conversion uses ITU-R 601-2 luma (`0.299 R + 0.587 G + 0.114 B`), via Pillow for
136
+ 8-bit data, so arrays and PIL images give identical results.
137
+
138
+ ### `hist_stats(image, *, channels="gray", bins=256, value_range=None, percentiles=(1, 5, 25, 50, 75, 95, 99))`
139
+
140
+ Returns a `HistStats` (or `{"r": ..., "g": ..., "b": ...}` for `"rgb"`) with `count`, `mean`,
141
+ `std` (population), `min`, `max`, `median`, `percentiles`, `entropy` (bits), `clipped_low` and
142
+ `clipped_high` (fraction of pixels in the first and last bin). `HistStats.to_dict()` gives a
143
+ JSON-ready dict with percentile keys like `"p5"`.
144
+
145
+ Statistics are computed from the histogram in O(bins). They are exact for integer data with
146
+ bin width 1 (the uint8 default) and approximate to bin resolution otherwise. Percentiles use
147
+ the nearest-rank (inverted CDF) method.
148
+
149
+ ### `stats_from_counts(counts, edges, percentiles=...)`
150
+
151
+ The same statistics for a histogram you already have (`counts` of shape `(bins,)`, `edges` of
152
+ shape `(bins + 1,)`).
153
+
154
+ ### `compare_hist(h1, h2, *, method="intersection")`
155
+
156
+ Compares two histograms of the same shape and returns a float. Histograms are normalised to
157
+ sum to 1 first (except for `correlation`), so images of different sizes compare fairly. For
158
+ `(channels, bins)` input the per-channel scores are averaged.
159
+
160
+ | method | range | identical | definition |
161
+ |---|---|---|---|
162
+ | `intersection` | [0, 1] | 1 | `sum(min(p, q))` |
163
+ | `chi2` | [0, 1] | 0 | `0.5 * sum((p - q)² / (p + q))` |
164
+ | `bhattacharyya` | [0, 1] | 0 | `sqrt(1 - sum(sqrt(p * q)))` (Hellinger form) |
165
+ | `correlation` | [-1, 1] | 1 | Pearson r of the raw counts |
166
+ | `emd` | [0, bins - 1] | 0 | `sum(abs(cumsum(p) - cumsum(q)))`, Earth Mover's distance in bins |
167
+
168
+ ### `HistAccumulator(*, channels="gray", bins=256, value_range=None)`
169
+
170
+ Streams images into one histogram: `update(image)`, `merge(other)` (for multiprocessing),
171
+ `counts` (read-only), `edges`, `n_images` and `stats(percentiles)`. Without `value_range`, the
172
+ range comes from the first image's dtype (uint8 or uint16); float and other integer images
173
+ need an explicit `value_range` so bins line up across images.
174
+
175
+ ### `get_image_array(image, *, mode="gray")`
176
+
177
+ Returns a PIL image as an array: `"gray"` gives `(H, W)`, `"rgb"` gives `(H, W, 3)`, `"keep"`
178
+ gives `np.asarray(image)` unchanged. The native bit depth is kept (16-bit images give uint16).
179
+
180
+ ### `array_to_image(arr, width=None, height=None, *, clip=True)`
181
+
182
+ Builds a PIL image from a 1-D array (with `width` and `height`), an `(H, W)` array (mode `L`, or
183
+ lossless `I;16` for uint16) or an `(H, W, 3/4)` array (`RGB`/`RGBA`). Other dtypes are converted
184
+ to 8 bits: floats are rounded (not truncated); values outside [0, 255] are clipped with a
185
+ `RuntimeWarning` when `clip=True`, or raise `ValueError` when `clip=False`.
186
+
187
+ ## Migrating from 1.x
188
+
189
+ | 1.x | 2.0 |
190
+ |---|---|
191
+ | `getImageArray(img)`, `getHist(x)`, `getImageFromArray(a, w, h)` | removed; use `get_image_array`, `get_hist`, `array_to_image` |
192
+ | `get_hist(x)` returns a `list` | returns an `np.ndarray`; call `.tolist()` if you need a list |
193
+ | `get_hist(x, as_density=True)` | `get_hist(x, density=True)` |
194
+ | `get_image_array(img, ensure_grayscale=True)` | `get_image_array(img)` (`mode="gray"`) |
195
+ | `get_image_array(img, ensure_grayscale=False)` | `get_image_array(img, mode="keep")` |
196
+ | `array_to_image(a, validate_range=False)` | `array_to_image(a, clip=False)` |
197
+ | `from image_array_and_histogram.main import ...` | `from image_array_and_histogram import ...` |
198
+
199
+ Behaviour changes to watch for:
200
+
201
+ - 16-bit images are no longer reduced to 8 bits: `get_image_array` returns uint16 and
202
+ `get_hist` uses the range `(0, 65536)`. If you relied on 8-bit output, convert first with
203
+ `img.convert("L")`.
204
+ - `array_to_image` now accepts `(H, W, 3/4)` arrays (RGB/RGBA) instead of raising, and keeps 2-D
205
+ uint16 arrays as 16-bit images.
206
+
207
+ ## Development
208
+
209
+ ```sh
210
+ git clone https://github.com/rishi-chauhan/my-packages.git
211
+ cd my-packages
212
+ pip install -e ".[dev]"
213
+ ruff check . && ruff format --check . && mypy
214
+ pytest --cov=image_array_and_histogram --cov-fail-under=95
215
+ python benchmarks/bench_hist.py # optional performance check
216
+ ```
217
+
218
+ ## Contributing
219
+
220
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
221
+
222
+ ## License
223
+
224
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,34 @@
1
+ """Fast image histograms, exposure statistics and histogram comparison for NumPy/Pillow.
2
+
3
+ Works with PIL images and NumPy arrays: 8-bit, 16-bit and float data, grayscale
4
+ or per RGB channel. See :func:`get_hist`, :func:`hist_stats`,
5
+ :func:`compare_hist` and :class:`HistAccumulator`.
6
+ """
7
+
8
+ from importlib.metadata import PackageNotFoundError
9
+ from importlib.metadata import version as _version
10
+
11
+ from ._accumulator import HistAccumulator
12
+ from ._compare import compare_hist
13
+ from ._convert import array_to_image, get_image_array
14
+ from ._histogram import get_hist
15
+ from ._stats import HistStats, hist_stats, stats_from_counts
16
+
17
+ try:
18
+ __version__ = _version("image_array_and_histogram")
19
+ except PackageNotFoundError: # pragma: no cover - running from a source tree without installation
20
+ __version__ = "0+unknown"
21
+
22
+ __author__ = "Rishi Raj Singh Chauhan"
23
+
24
+ __all__ = [
25
+ "HistAccumulator",
26
+ "HistStats",
27
+ "__version__",
28
+ "array_to_image",
29
+ "compare_hist",
30
+ "get_hist",
31
+ "get_image_array",
32
+ "hist_stats",
33
+ "stats_from_counts",
34
+ ]
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m image_array_and_histogram``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())