From 1b8f9d386b2dab07f04a8b2ef382f8b3095964d7 Mon Sep 17 00:00:00 2001 From: Andreas Florath Date: Fri, 1 Dec 2023 15:26:09 +0100 Subject: [PATCH 1/3] Optimize ImageStat.Stat._getextrema function The optimzed function improves the performance. The original function always runs through the complete historgram of length 256 even if it is possible to exit the loop early (break). Running some tests I found performance improvements of factor >10 depending on the image. Signed-off-by: Andreas Florath --- src/PIL/ImageStat.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index b7ebddf066a..7c8753a6396 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -53,17 +53,23 @@ def _getextrema(self): """Get min/max values for each band in the image""" def minmax(histogram): - n = 255 - x = 0 + res_min, res_max = 255, 0 for i in range(256): if histogram[i]: - n = min(n, i) - x = max(x, i) - return n, x # returns (255, 0) if there's no data in the histogram + res_min = i + break + for i in range(255, -1, -1): + if histogram[i]: + res_max = i + break + if res_max >= res_min: + return res_min, res_max + else: + return (255, 0) v = [] for i in range(0, len(self.h), 256): - v.append(minmax(self.h[i:])) + v.append(minmax(self.h[i:i+256])) return v def _getcount(self): From 7762dd382a783adc214643b9c7483eea967740bf Mon Sep 17 00:00:00 2001 From: Andreas Florath Date: Fri, 1 Dec 2023 16:21:29 +0100 Subject: [PATCH 2/3] Fixed spacing in _getextrema method Signed-off-by: Andreas Florath --- src/PIL/ImageStat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index 7c8753a6396..efef0802f4d 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -69,7 +69,7 @@ def minmax(histogram): v = [] for i in range(0, len(self.h), 256): - v.append(minmax(self.h[i:i+256])) + v.append(minmax(self.h[i : i + 256])) return v def _getcount(self): From ac47b75953fde2eb1e6e3c9c182c279a74e7b8c3 Mon Sep 17 00:00:00 2001 From: Andreas Florath Date: Mon, 4 Dec 2023 10:27:30 +0100 Subject: [PATCH 3/3] Update src/PIL/ImageStat.py Simplification of return statement Co-authored-by: Andrew Murray <3112309+radarhere@users.noreply.github.com> --- src/PIL/ImageStat.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index efef0802f4d..2de24b6c7ca 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -62,10 +62,7 @@ def minmax(histogram): if histogram[i]: res_max = i break - if res_max >= res_min: - return res_min, res_max - else: - return (255, 0) + return res_min, res_max v = [] for i in range(0, len(self.h), 256):