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

2024-04-25 23:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个程序,在给定一组种子点的情况下绘制voronoi细胞的图像

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

绘制完所有彩色单元格后,我想绘制一个以每个种子点坐标为中心的椭圆,这样它们就可以可视化了。我试过用图像绘制。绘制在我的图像上画椭圆,但它们没有被绘制在正确的位置,即使我偏移了矩形容器的角以便它应该正确居中。为了检查它们是否在错误的位置,我将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循环中,但运行程序需要所有代码。为了生成图像,我从一个维度(512,512,3)的numpy数组开始,其中前两个维度是图像的高度和宽度,最后一个维度是该点像素的RGB分量。你知道吗


Tags: in图像noneforindexplotnp绘制