DEV Community

petercour
petercour

Posted on

Blend images with python

Like images? You can use Python to play with images. PIL is the image library for Python. Sometimes its called Pillow or the Python Image Library.

You can do all kind of effects like blur, resize and others.
Did you know you can also blend two images? Wait.. What is blending?

Blend images

Think of mixing two images, on top of each other.
That must be hard to do right?

Not really. You need two images. In this case I've taken these two:

In code that becomes:

#!/usr/bin/python3
from PIL import Image

Im = Image.open("lena.jpg")
print(Im.mode,Im.size,Im.format)
Im.show()

newIm = Image.new ("RGBA", (640, 480), (255, 0, 0))
Im2 = Image.open("flower.jpg").convert(Im.mode)
Im2 = Im2.resize(Im.size)
Im2.show()

img = Image.blend(Im,Im2,0.2)
img.show()

Run it to see the blended image:

The image is not saved, it only shows with img.show(). Any two images can be blend, but they must be the same size of course. That is ensured by resizing:

Im2 = Im2.resize(Im.size)

So the blending is done with:

img = Image.blend(Im,Im2,0.2)

The first two parameters are the images. There are two ways to find out.

  • the boring way (read documentation)
  • changing the parameter

So you chose the third way? Reading more. Ok it's the alpha value.

alpha – The interpolation alpha factor. 
If alpha is 0.0, a copy of the first image is returned. 
If alpha is 1.0, a copy of the second image is returned. 

Related links:

Top comments (0)