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:
JavaScript
x
10
10
1
im = Image.open(image.jpg)
2
enhancer = ImageEnhance.Contrast(im)
3
im_output = enhancer.enhance(factor)
4
im_output.save(image.jpg)
5
6
im = Image.open(image.jpg)
7
enhancer = ImageEnhance.Sharpness(im)
8
im_output = enhancer.enhance(factor)
9
im_output.save(updated image.jpg)
10
Advertisement
Answer
You can do it without saving to disk like this:
JavaScript
1
17
17
1
#!/usr/bin/env python3
2
from PIL import Image, ImageEnhance
3
4
# Open a miserable, low-contrast image
5
im = Image.open('low-contrast.jpg')
6
7
# Sharpen
8
enhancer = ImageEnhance.Sharpness(im)
9
res = enhancer.enhance(4)
10
11
# Improve contrast
12
enhancer = ImageEnhance.Contrast(res)
13
res = enhancer.enhance(2)
14
15
# Save to disk
16
res.save('result.jpg')
17
Transforms this:
into this: