Python沿着三角形的每条边反射图像

标签 python python-3.x python-imaging-library

我创建了一个位于屏幕中心的三角形。

enter image description here

from PIL import Image, ImageDraw
GRAY = (190, 190, 190)
im = Image.new('RGBA', (400, 400), WHITE)
points = (250, 250), (100, 250), (250, 100)
draw = ImageDraw.Draw(im)
draw.polygon(points, GRAY)

如何复制此图像并在不同的随机点沿着三角形的每条边反射它。例如...

enter image description here

最佳答案

计划:首先在大三角形的边缘找到一个随机点来放置较小的三角形,然后旋转它,使其正确贴合边缘。

假设我们可以用这样的方法访问三角形的点

triangle.edges[0].x, 
triangle.edges[0].y, 
triangle.edges[1].x,
etc

然后,我们可以通过首先选择一条边来找到任意点,然后“步行到下一条边的随机距离”:

r = randInt(3) # random integer between 0 and 2
first_edge = triangle.edges[r]
second_edge = r == 2 ? triangle.edges[0] : triangle.edges[r + 1]

## The next lines is kind of pseudo-code
r = randFloat(1)
random_point = (second_edge - first_edge)*r + first_edge 

我们的下一个问题是如何旋转三角形。如果您学过一些代数,您可能会认识到这一点:

def rotatePointAroundOrigin(point, angle):
    new_point = Point()
    new_point.x = cos(angle)*point.x - sin(angle)*point.y
    new_point.y = sin(angle).point.x + cos(angle)*point.y
    return new_point

(参见 https://en.wikipedia.org/wiki/Rotation_matrix )

除此之外,您还需要确定三角形的旋转程度,然后将上面的函数应用于所有点。

关于Python沿着三角形的每条边反射图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408797/

相关文章:

Python 和 numpy : subtracting line by line a 2-dim array from a 1-dim array

python - Python 中的 Alphavantage API - X 轴上没有日期

python - 如何在 PyQt5 中拥有动态字段?

python - 从python列表中删除元素

python - 使用 PIL 修剪空格

python - 使用 Python 的 email.mime.multipart 发送 HTML 邮件时命名内联图像

Python:获取列表顺序元素的所有组合

python - 如何使用不均匀子数组作为平铺来平铺一维 numpy 数组?

python - Tkinter 图像显示(使用 [converted] NumPy 数组)

python - 使用 Python 读取 16 位 PNG 图像文件