I’m new to coding, some my code isn’t the cleanest (as evidenced below). Is there a more efficent way to change both the sharpness and contrast with Pillow in python without having to save and open the file twice?
My horrible code:
        im = Image.open(image.jpg)
        enhancer = ImageEnhance.Contrast(im)
        im_output = enhancer.enhance(factor)
        im_output.save(image.jpg)
        im = Image.open(image.jpg)
        enhancer = ImageEnhance.Sharpness(im)
        im_output = enhancer.enhance(factor)
        im_output.save(updated image.jpg)
Advertisement
Answer
You can do it without saving to disk like this:
#!/usr/bin/env python3
from PIL import Image, ImageEnhance                                                                
# Open a miserable, low-contrast image
im = Image.open('low-contrast.jpg')
# Sharpen 
enhancer = ImageEnhance.Sharpness(im)
res = enhancer.enhance(4) 
# Improve contrast
enhancer = ImageEnhance.Contrast(res)
res = enhancer.enhance(2)
# Save to disk
res.save('result.jpg')
Transforms this:
into this:

