I'm using PIL (Python Imaging Library). I'd like to draw transparent polygons. It seems that specifying a fill color that includes alpha level does not work. Are their workarounds?
If it can't be done using PIL I'm willing to use something else.
If there is more than one solution, then performance should be factored in. The drawing needs to be as fast as possible.
This is for Pillow, a more maintained fork of PIL. http://pillow.readthedocs.org/
If you want to draw polygons that are transparent, relative to each other, the base Image has to be of type RGB, not RGBA, and the ImageDraw has to be of type RGBA. Example:
from PIL import Image, ImageDraw img = Image.new('RGB', (100, 100)) drw = ImageDraw.Draw(img, 'RGBA') drw.polygon(xy=[(50, 0), (100, 100), (0, 100)], fill=(255, 0, 0, 125)) drw.polygon(xy=[(50, 100), (100, 0), (0, 0)], fill=(0, 255, 0, 125)) del drw img.save('out.png', 'PNG')
This will draw two triangles overlapping with their two colors blending. This a lot faster than having to composite multiple 'layers' for each polygon.
What I've had to do when using PIL to draw transparent images is create a color layer, an opacity layer with the polygon drawn on it, and composited them with the base layer as so:
color_layer = Image.new('RGBA', base_layer.size, fill_rgb) alpha_mask = Image.new('L', base_layer.size, 0) alpha_mask_draw = ImageDraw.Draw(alpha_mask) alpha_mask_draw.polygon(self.outline, fill=fill_alpha) base_layer = Image.composite(color_layer, base_layer, alpha_mask)
When using Image.Blend I had issues with strange outlining behaviors on the drawn polygons.
The only issue with this approach is that the performance is abysmal when drawing a large number of reasonably sized polygons. A much faster solution would be something like "manually" drawing the polygon on a numpy array representation of the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With