Search code examples
pythonimagemagickwand

Python Wand vs imagemagick brightness-contrast command


I try to use Wand and can't find any mappings for brightness-contrast command.

source img

  • Tried to use modulate for changing brightness:

    value = 100 + value # no changes = 0 in console and 100 in wand img.modulate(brightness=value)

and I got some strange artefacts with white pixels: brightness change attempt

  • For working with contrast Wand has just contrast_stretch() and I can't understand how to do something like this

    convert '-brightness-contrast 0x%d'


Solution

  • Luckily, -brightness-contrast just calls -function Polynomial methods which is implemented in . Some very simple math is needed to translate the brightness x contrast arguments into slop x intercept.

    import math
    from wand.image import Image
    
    class MyImage(Image):
        def brightness_contrast(self, brightness=0.0, contrast=0.0):
            slope=math.tan((math.pi * (contrast/100.0+1.0)/4.0))
            if slope < 0.0:
              slope=0.0
            intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope)
            self.function("polynomial", [slope, intercept])
    
    with MyImage(filename="rose:") as img:
        img.brightness_contrast(0.0, 10.0)
        img.save(filename="rose.png")
    

    rose.png