1

How can I adjust the contrast and brightness of an image to match GIMP's Colours > Brightness-Contrast dialogue?

enter image description here

A brightness of -110 and a contrast of 127 is what I want achieve.

I found this function from this answer:

def change_contrast(img, level):
    factor = (259 * (level + 255)) / (255 * (259 - level))
    def contrast(c):
        value = 128 + factor * (c - 128)
        return max(0, min(255, value))
    return img.point(contrast)

This function reproduces the contrast with the values I want, but I can not find an equivalent for brightness.

I know that the ImageEnhance module exists, but that has an unbounded float as a parameter, how do I convert the values I use in gimp to this format? Or is there another solution that I can plug these values into. The ImageEnhance docs don't explain how this parameter works.

from PIL import Image, ImageEnhance

img = Image.open(path)
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(0.2)
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(2.0)
Morgoth
  • 4,935
  • 8
  • 40
  • 66
  • Do you know how to make the Brightness and Contrast appear as integers like that? Mine show as small decimal numbers less than 1. Try creating a greyscale gradient from say 25..230 and applying your Brightness and Contrast so you can see how the file and histogram have been affected. – Mark Setchell Jun 24 '19 at 13:09

1 Answers1

0

The docs explain:

This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.

To match exactly the behaviour in GIMP you can map the range from 0.0 to 1.0 to the GIMP range, e.g. using the code found here:

def maprange( a, b, s):
    (a1, a2), (b1, b2) = a, b
    return  b1 + ((s - a1) * (b2 - b1) / (a2 - a1))

Or a good solution that uses the SciPy interpolation functions found here:

from scipy.interpolate import interp1d
m = interp1d([gimp_lower, gimp_upper],[0.0, 1.0])
print(m(50))
Joe
  • 6,758
  • 2
  • 26
  • 47