Merge pull request #4749 from millionhz/autocontrast

This commit is contained in:
Hugo van Kemenade 2020-07-05 12:10:23 +03:00 committed by GitHub
commit ec6f2d41f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 4 deletions

View File

@ -300,3 +300,14 @@ def test_exif_transpose():
"Tests/images/hopper_orientation_" + str(i) + ext "Tests/images/hopper_orientation_" + str(i) + ext
) as orientation_im: ) as orientation_im:
check(orientation_im) check(orientation_im)
def test_autocontrast_cutoff():
# Test the cutoff argument of autocontrast
with Image.open("Tests/images/bw_gradient.png") as img:
def autocontrast(cutoff):
return ImageOps.autocontrast(img, cutoff).histogram()
assert autocontrast(10) == autocontrast((10, 10))
assert autocontrast(10) != autocontrast((1, 10))

View File

@ -70,7 +70,9 @@ def autocontrast(image, cutoff=0, ignore=None):
becomes white (255). becomes white (255).
:param image: The image to process. :param image: The image to process.
:param cutoff: How many percent to cut off from the histogram. :param cutoff: The percent to cut off from the histogram on the low and
high ends. Either a tuple of (low, high), or a single
number for both.
:param ignore: The background pixel value (use None for no background). :param ignore: The background pixel value (use None for no background).
:return: An image. :return: An image.
""" """
@ -88,12 +90,14 @@ def autocontrast(image, cutoff=0, ignore=None):
h[ix] = 0 h[ix] = 0
if cutoff: if cutoff:
# cut off pixels from both ends of the histogram # cut off pixels from both ends of the histogram
if not isinstance(cutoff, tuple):
cutoff = (cutoff, cutoff)
# get number of pixels # get number of pixels
n = 0 n = 0
for ix in range(256): for ix in range(256):
n = n + h[ix] n = n + h[ix]
# remove cutoff% pixels from the low end # remove cutoff% pixels from the low end
cut = n * cutoff // 100 cut = n * cutoff[0] // 100
for lo in range(256): for lo in range(256):
if cut > h[lo]: if cut > h[lo]:
cut = cut - h[lo] cut = cut - h[lo]
@ -103,8 +107,8 @@ def autocontrast(image, cutoff=0, ignore=None):
cut = 0 cut = 0
if cut <= 0: if cut <= 0:
break break
# remove cutoff% samples from the hi end # remove cutoff% samples from the high end
cut = n * cutoff // 100 cut = n * cutoff[1] // 100
for hi in range(255, -1, -1): for hi in range(255, -1, -1):
if cut > h[hi]: if cut > h[hi]:
cut = cut - h[hi] cut = cut - h[hi]