From 1b8f9d386b2dab07f04a8b2ef382f8b3095964d7 Mon Sep 17 00:00:00 2001 From: Andreas Florath Date: Fri, 1 Dec 2023 15:26:09 +0100 Subject: [PATCH] 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):