Overlay polygon on top of image in Python
image-processing, overlay, python
Solution
PIL is a fine tool for this:
import Image
import ImageDraw
img = Image.open(...).convert('RGBA')
x = ['10', '30', '70']
y = ['15', '45', '90']
# convert values to ints
x = map(int, x)
y = map(int, y)
img2 = img.copy()
draw = ImageDraw.Draw(img2)
draw.polygon(zip(x,y), fill = "wheat")
img3 = Image.blend(img, img2, 0.5)
img3.save('/tmp/out.png')
The call signature for `draw.polygon` is:
def polygon(self, xy, fill=None, outline=None):
so the only options are `fill` and `outline`. I looked at the source code to find this information.
IPython told me:
In [38]: draw.polygon?
...
File: /usr/lib/python2.7/dist-packages/PIL/ImageDraw.py
which showed me where to look.
To draw a semi-transparent polygon on top of `img`, make a copy of the image. One the copy, draw the polygon in full color without alpha. Then use Image.blend to combine the original image with the copy with a set level of `alpha`. For each pixel:
out = image1 * (1.0 - alpha) + image2 * alpha
Problem
Say I have an image in PIL ``` from PIL import Image Image.open(path_to_my_image) ``` and two lists of `x` points and `y` points ``` x = ['10', '30', '70'] y = ['15', '45', '90'] ``` Is there a way to overlay my polygon with transparency on this image? Also, is PIL a good library for this? Or should I use a different one? (e.g. `scikits.image`, or render in an image with pylab).