change_contrast.py 838 B

1234567891011121314151617181920212223242526272829303132333435
  1. """
  2. Changing contrast with PIL
  3. This algorithm is used in
  4. https://noivce.pythonanywhere.com/ python web app.
  5. python/black: True
  6. flake8 : True
  7. """
  8. from PIL import Image
  9. def change_contrast(img: Image, level: float) -> Image:
  10. """
  11. Function to change contrast
  12. """
  13. factor = (259 * (level + 255)) / (255 * (259 - level))
  14. def contrast(c: int) -> float:
  15. """
  16. Fundamental Transformation/Operation that'll be performed on
  17. every bit.
  18. """
  19. return 128 + factor * (c - 128)
  20. return img.point(contrast)
  21. if __name__ == "__main__":
  22. # Load image
  23. with Image.open("image_data/lena.jpg") as img:
  24. # Change contrast to 170
  25. cont_img = change_contrast(img, 170)
  26. cont_img.save("image_data/lena_high_contrast.png", format="png")