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