假设我在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渲染图像)。
发布于 2012-11-26 23:14:48
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上绘制半透明多边形,请复制图像.一份拷贝,在没有字母的情况下绘制全彩色的多边形。然后使用Image.blend将原始图像与具有设置级别的alpha的副本相结合。对于每个像素:
out = image1 * (1.0 - alpha) + image2 * alpha发布于 2020-05-28 13:57:29
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()https://stackoverflow.com/questions/13574751
复制相似问题