Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL: Blend transparent image onto another

I need to blend an image over another image using Pythons PIL Library.

As you can see in the image below, my two source images are A and B. When I do:

imageA.paste(imageB, (0, 0), imageB)

I get C as a result, but the part at the top of the gray background is now transparent. Image D is what I get when I put B over A in Photoshop and is what I need to achieve with PIL.

What am I doing wrong? How can I compose B over A in PIL to get D instead of C?

Example Image

like image 927
Daniela Avatar asked Jul 03 '14 03:07

Daniela


People also ask

How to create a transparent PNG with PiL?

To create a transparent png with PIL you can use this code, as example. In this particular example I joined 2 transparent png and pasting them side by side on a new transparent image of the same size of the two together. The process in the code is this: we create a new image (Image.new) with “RGBA” as first argument and (0,0,0,0) as third argument

How to blend two images in Python?

In this, we are going to use the Python Imaging Library (PIL), which is also known as ‘Pillow’. In Pillow, we are going to use the ‘Image’ Module as it consists of the ‘Blend’ method that blends two images. This function returns a new image by interpolating between two input images.

How to create a transparent PNG using Python3?

To create a transparent png using Python3, the Pillow library is used. The Pillow library comes with python itself. If python is unable to find Pillow library then open the command prompt and run this command:- Note: If you got any problem installing Pillow using pip, then install and setup pip first. For this check this article. 2.

What is the use of PIL in Photoshop?

It converts the image to its true color with a transparency mask. Paste Function – It is used to paste an image on another image. Syntax: PIL.Image.Image.paste (image_1, image_2, box=None, mask=None)


2 Answers

use RGBA for transparency mask

imageA.paste(imageB, (0, 0), imageB.convert('RGBA'))
like image 71
autopython Avatar answered Sep 20 '22 21:09

autopython


I can't comment for now (rep constraint).

But I think what you really need, according to your need, is to do this instead:

imageB.paste(imageA, (0, 0), imageA)

Basically, that is, make B the background image to get the desired results, because that's what I see in D.

EDIT: Looking around more, I found this: https://stackoverflow.com/a/15919897/4029893

I think you should definitely use the alpha_composite method, since paste doesn't work as expected for background images with transparency.

like image 36
bad_keypoints Avatar answered Sep 19 '22 21:09

bad_keypoints