Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay polygon on top of image in Python

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).

like image 741
Amelio Vazquez-Reina Avatar asked Nov 26 '12 23:11

Amelio Vazquez-Reina


Video Answer


2 Answers

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
like image 63
unutbu Avatar answered Oct 02 '22 01:10

unutbu


To do that you can use Shapely and OpenCV like this:

import cv2
import numpy as np
from shapely.geometry import Polygon

x = [10, 30, 70]
y = [15, 45, 90]
alpha = 0.5 # that's your transparency factor
path = 'path_to_image.jpg'

polygon = Polygon([(x[0], y[0]), (x[1], y[1]), (x[2], y[2]), (x[0], y[2])])
int_coords = lambda x: np.array(x).round().astype(np.int32)
exterior = [int_coords(polygon.exterior.coords)]

image = cv2.imread(path)
overlay = image.copy()
cv2.fillPoly(overlay, exterior, color=(255, 255, 0))
cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image)
cv2.imshow("Polygon", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
like image 33
tsveti_iko Avatar answered Oct 01 '22 23:10

tsveti_iko