切出三角形并混合

时间:2019-01-23 16:37:28

标签: python image python-imaging-library

您好,请给我一些有关如何从图像中切出4个三角形并将它们混合在一起的技巧,以便它们看起来像这样:

enter image description here

我想使用python来实现此目的。

1 个答案:

答案 0 :(得分:0)

从这张图片(dog.jpg)开始:

enter image description here

您可以执行以下操作:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Open image, generate a copy and rotate copy 180 degrees
im1 = Image.open('dog.jpg')
im2 = im1.copy().rotate(180)
# DEBUG: im2.save('im2.png')

# Get dimensions of image
w, h = im1.size

# Create an alpha layer same size as our image filled with black
alpha = Image.new('L',(w,h))

# Draw 2 white (i.e. transparent) triangles on the alpha layer
draw  = ImageDraw.Draw(alpha)
draw.polygon([(0, 0), (w, 0), (w/2, h/2)], fill = (255))
draw.polygon([(0, h), (w, h), (w/2, h/2)], fill = (255))
# DEBUG: alpha.save('alpha.png')

# Composite rotated image over initial image while respecting alpha
result = Image.composite(im1, im2, alpha)
result.save('result.png')

enter image description here

中间步骤(在代码中带有#DEBUG:的注释)如下:

im2.png

enter image description here

alpha.png

enter image description here