7

假设我在 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 渲染图像)。

4

2 回答 2

9

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

所以唯一的选择是filland 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
于 2012-11-26T23:14:48.027 回答
8

为此,您可以像这样使用ShapelyOpenCV

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()
于 2020-05-28T13:57:29.067 回答