说我在PIL中有一个图像
from PIL import Image
Image.open(path_to_my_image)
以及两个x
点和y
点
x = ['10', '30', '70']
y = ['15', '45', '90']
有没有办法在此图片上叠加我的多边形透明度?
另外,PIL是一个很好的库吗?或者我应该使用另一个? (例如scikits.image
,或使用pylab在图像中渲染)。
答案 0 :(得分:3)
PIL是一个很好的工具:
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')
draw.polygon
的来电签名是:
def polygon(self, xy, fill=None, outline=None):
所以唯一的选项是fill
和outline
。我查看了源代码以查找此信息。
IPython告诉我:
In [38]: draw.polygon?
...
File: /usr/lib/python2.7/dist-packages/PIL/ImageDraw.py
告诉我在哪里看。
要在img
之上绘制半透明多边形,请复制图像。一个副本,在没有alpha的情况下绘制全彩色多边形。然后使用Image.blend将原始图片与设置级别alpha
的副本合并。对于每个像素:
out = image1 * (1.0 - alpha) + image2 * alpha
答案 1 :(得分:2)
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()