如何在Python中将图像划分为n个不同的多边形

2024-05-17 23:10:53 发布

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

我是python新手,正在尝试使用python将图像分割成不同的多边形。我的目标是将一个图像转换成n个随机多边形形状的图像。我试过Voronoi算法,但有点混乱。我真的很感激任何帮助。任何其他分割方法等

我以前的代码:

import random
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d

img = plt.imread("abc.jpg")
fig, ax = plt.subplots()
ax.imshow(img)

def points(radius,rangeX,rangeY,qty):
    deltas = set()
    for x in range(-radius, radius+1):
        for y in range(-radius, radius+1):
            if x*x + y*y <= radius*radius:
                deltas.add((x,y))

    randPoints = []
    excluded = set()
    i = 0
    while i<qty:
        x = random.randrange(*rangeX)
        y = random.randrange(*rangeY)
        if (x,y) in excluded: continue
        randPoints.append((x,y))
        i += 1
        excluded.update((x+dx, y+dy) for (dx,dy) in deltas)
    return randPoints



def plot1(randPoints,fig):
    points = np.array(randPoints)
    vor = Voronoi(points)
    print vor.vertices
    voronoi_plot_2d(vor,ax = fig.gca())
    #plt.savefig('abc.png')
    plt.show()

radius = 20
rangeX = (0, 960)
rangeY = (0, 480)
qty = 9

points = points(radius, rangeX, rangeY, qty)
plot1(points,fig)

我的意见: enter image description here

我的输出: enter image description here

这是为n=9我将感谢任何帮助,我可以得到。你知道吗


Tags: in图像importdeltasfigpltrandomax