CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
ImageStat.py168 linesDownload Raw Back to PIL
1#
2# The Python Imaging Library.
3# $Id$
4#
5# global image statistics
6#
7# History:
8# 1996-04-05 fl   Created
9# 1997-05-21 fl   Added mask; added rms, var, stddev attributes
10# 1997-08-05 fl   Added median
11# 1998-07-05 hk   Fixed integer overflow error
12#
13# Notes:
14# This class shows how to implement delayed evaluation of attributes.
15# To get a certain value, simply access the corresponding attribute.
16# The __getattr__ dispatcher takes care of the rest.
17#
18# Copyright (c) Secret Labs AB 1997.
19# Copyright (c) Fredrik Lundh 1996-97.
20#
21# See the README file for information on usage and redistribution.
22#
23from __future__ import annotations
24
25import math
26from functools import cached_property
27
28from . import Image
29
30
31class Stat:
32    def __init__(
33        self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
34    ) -> None:
35        """
36        Calculate statistics for the given image. If a mask is included,
37        only the regions covered by that mask are included in the
38        statistics. You can also pass in a previously calculated histogram.
39
40        :param image: A PIL image, or a precalculated histogram.
41
42            .. note::
43
44                For a PIL image, calculations rely on the
45                :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
46                grouped into 256 bins, even if the image has more than 8 bits per
47                channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
48                ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
49                of more than 255.
50
51        :param mask: An optional mask.
52        """
53        if isinstance(image_or_list, Image.Image):
54            self.h = image_or_list.histogram(mask)
55        elif isinstance(image_or_list, list):
56            self.h = image_or_list
57        else:
58            msg = "first argument must be image or list"  # type: ignore[unreachable]
59            raise TypeError(msg)
60        self.bands = list(range(len(self.h) // 256))
61
62    @cached_property
63    def extrema(self) -> list[tuple[int, int]]:
64        """
65        Min/max values for each band in the image.
66
67        .. note::
68            This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
69            simply returns the low and high bins used. This is correct for
70            images with 8 bits per channel, but fails for other modes such as
71            ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
72            return per-band extrema for the image. This is more correct and
73            efficient because, for non-8-bit modes, the histogram method uses
74            :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
75        """
76
77        def minmax(histogram: list[int]) -> tuple[int, int]:
78            res_min, res_max = 255, 0
79            for i in range(256):
80                if histogram[i]:
81                    res_min = i
82                    break
83            for i in range(255, -1, -1):
84                if histogram[i]:
85                    res_max = i
86                    break
87            return res_min, res_max
88
89        return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
90
91    @cached_property
92    def count(self) -> list[int]:
93        """Total number of pixels for each band in the image."""
94        return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
95
96    @cached_property
97    def sum(self) -> list[float]:
98        """Sum of all pixels for each band in the image."""
99
100        v = []
101        for i in range(0, len(self.h), 256):
102            layer_sum = 0.0
103            for j in range(256):
104                layer_sum += j * self.h[i + j]
105            v.append(layer_sum)
106        return v
107
108    @cached_property
109    def sum2(self) -> list[float]:
110        """Squared sum of all pixels for each band in the image."""
111
112        v = []
113        for i in range(0, len(self.h), 256):
114            sum2 = 0.0
115            for j in range(256):
116                sum2 += (j**2) * float(self.h[i + j])
117            v.append(sum2)
118        return v
119
120    @cached_property
121    def mean(self) -> list[float]:
122        """Average (arithmetic mean) pixel level for each band in the image."""
123        return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands]
124
125    @cached_property
126    def median(self) -> list[int]:
127        """Median pixel level for each band in the image."""
128
129        v = []
130        for i in self.bands:
131            s = 0
132            half = self.count[i] // 2
133            b = i * 256
134            for j in range(256):
135                s = s + self.h[b + j]
136                if s > half:
137                    break
138            v.append(j)
139        return v
140
141    @cached_property
142    def rms(self) -> list[float]:
143        """RMS (root-mean-square) for each band in the image."""
144        return [
145            math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0
146            for i in self.bands
147        ]
148
149    @cached_property
150    def var(self) -> list[float]:
151        """Variance for each band in the image."""
152        return [
153            (
154                (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
155                if self.count[i]
156                else 0
157            )
158            for i in self.bands
159        ]
160
161    @cached_property
162    def stddev(self) -> list[float]:
163        """Standard deviation for each band in the image."""
164        return [math.sqrt(self.var[i]) for i in self.bands]
165
166
167Global = Stat  # compatibility
168 
Aluode/PerceptionLabPortable · CoolFace