DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to change an image with Python
Deotyma
Deotyma

Posted on

How to change an image with Python

Today I would like to play a little bit with Python and Pillow library. I will test some possibilities of PIL.

I open PyCharm and I create in a directory PycharmProjects a project imagePython.
Normally PyCharm creates it automatically

I want to work with pictures so I install pillow for mac:

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow
Enter fullscreen mode Exit fullscreen mode

When I create a directory images and download a picture that I want to modify from Pixabay. It is better to chose a little image so it will take less time to transform it.

Now I change a main.py file:

from PIL import Image

tulips = Image.open("./images/tulips.jpeg")
tulips.show()
Enter fullscreen mode Exit fullscreen mode

and I run this code and this is a result:
tulips

That you see the image change a name and format.

Now I can rotate my image:

rotateImage = tulips.rotate(180)
rotateImage.show()
Enter fullscreen mode Exit fullscreen mode

tulips rotate 180Β°

I can also resize it:

little = tulips.resize((128, 128))
little.show()
Enter fullscreen mode Exit fullscreen mode

little tulips

Now I change colors to white and black:

# all is black and white
im = tulips.convert("L")
im.show()
Enter fullscreen mode Exit fullscreen mode

tulips white and black

I can also change the colors of the image like this:

r, g, b = tulips.split()
r = r.point(lambda i: i * 2)
g = g.point(lambda i: i / 2)
b = b.point(lambda i: i + 50)
img = Image.merge("RGB", (r, g, b))
img.getextrema()
img.show()
Enter fullscreen mode Exit fullscreen mode

changing colors of tulips

There is possible to use also some filters like blur or contour and much more than you can find in documentation:

from PIL import ImageFilter

im1 = tulips.filter(ImageFilter.BLUR)
im1.show()

im2 = tulips.filter(ImageFilter.CONTOUR)
im2.show()
Enter fullscreen mode Exit fullscreen mode

blur tulipes

contour tulipes

I can also regulate the contrast of my image:


from PIL import ImageEnhance

# contrast of 50%
contrastedImg = ImageEnhance.Contrast(tulips)
contrastedImg.enhance(1.5).show()

Enter fullscreen mode Exit fullscreen mode

contrasted img

These are only some examples of Pillow possibilities so don't hesitate to test them and use them in your projects.

Top comments (0)

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.