使用PIL将椭圆绘制到现有图像上

时间:2017-02-27 20:20:44

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

我编写了一个程序,根据一组种子点绘制了voronoi单元格的图像

https://en.wikipedia.org/wiki/Voronoi_diagram

在绘制了所有彩色单元格之后,我想绘制一个以每个种子点坐标为中心的椭圆,以便可以看到它们。我尝试使用ImageDraw.Draw在我的图像上制作椭圆,但它们并没有被绘制在正确的位置,即使我偏移矩形容器的角落以使它应该正确居中。为了检查它们是否在错误的位置,我将RGB数组中的种子点设置为白色,因此如果仔细观察,可以在每个色块中看到一个白色像素,椭圆应该居中。

Here is a plot with 5 seed points that you can see by the white pixels if you look closely. Two of the ellipses are centered properly around the point, but the others are not

import numpy as np
import math
from PIL import Image, ImageDraw
colors = np.array([[180, 0, 0], [0, 25, 200], [10, 150, 45], [100,100,100], [24,24,24]]) #colors to be mapped to each seed point
dim = 512
points = np.array([[50, 50], [150, 350], [400, 150],[256, 256],[300,200]])
metric = 'euclidean'

def closest_point_euclidean(point):
    minimum = float('inf')
    closest_point = None
    i = None

    for index, p in enumerate(points):
        distance = round(((point[0] - p[0])**2 + (point[1] - p[1])**2)**(1/2))
        if distance < minimum:
            minimum = distance
            closest_point = p
            i = index

    return i

def closest_point_manhattan(point):
    minimum = float('inf')
    closest_point = None
    i = None

    for index, p in enumerate(points):
        distance = abs(point[0] - p[0]) + abs(point[1] - p[1])
        if distance < minimum:
            minimum = distance
            closest_point = p
            i = index

    return i

def main():
    plot = np.zeros((dim, dim, 3), 'uint8')

    for i in range(plot.shape[0]):
        for j in range(plot.shape[1]):
            if metric == 'manhattan':
                closest_point_index = closest_point_manhattan([i,j])
            elif metric == 'euclidean':
                closest_point_index = closest_point_euclidean([i,j])
            plot[i][j] = colors[closest_point_index]

    for p in points:
        plot[p[0],p[1]] = [255,255,255] # set seed points to be white

    r = 4
    img = Image.fromarray(plot)
    draw = ImageDraw.Draw(img)
    for p in points:
        draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r])
    img.show()
    img.save('myPlot.jpeg')

if __name__ == "__main__":
    main()

有人可以帮我理解为什么有些省略号不在同一个地方吗?问题出现在最后一个for循环中,但是运行程序需要所有代码。为了生成图像,我从一个numpy维度数组(512,512,3)开始,其中前两个维度是图像的高度和宽度,最后一个维度是该点像素的RGB分量。

0 个答案:

没有答案