使用matplotlib创建随机形状/轮廓

kla*_*aus 7 python bezier matplotlib shapes contour

我试图使用python生成随机轮廓的图像,但我找不到一个简单的方法来做到这一点.

这是我想要的一个例子:

在此输入图像描述

最初我尝试使用matplotlib和高斯函数来做它,但我甚至无法接近我展示的图像.

有一个简单的方法吗?

我感谢任何帮助

小智 8

要回答您的问题,没有简单的方法。生成看起来和感觉自然的随机事物是一个比乍看起来要困难得多的问题 - 这就是为什么像柏林噪声这样的技术是重要的技术。

任何传统的编程方法(不涉及神经网络)可能最终都会成为一个涉及选择随机点、放置形状、绘制线条等的多步骤过程,并进行微调,直到它看起来像您想要的那样。使用这种方法,从头开始获得任何能够可靠地生成像示例一样具有动态和有机外观的形状将非常困难。

如果您对结果比实现更感兴趣,您可以尝试找到一个能够生成令人信服的平滑随机纹理的库,并从中剪切轮廓线。这是目前想到的唯一“简单”的方法。这是柏林噪声示例。注意由灰度形成的形状。柏林噪声,量化颜色。


Imp*_*est 8

问题是问题中显示的随机形状并不是真正随机的.它们以某种方式平滑,有序,看似随机的形状.虽然使用计算机可以轻松创建真正随机的形状,但使用笔和纸可以更轻松地创建这些伪随机形状.

因此,一种选择是交互地创建这样的形状.这在Python中使用Interactive BSpline拟合的问题中显示.

如果您想以编程方式创建随机形状,我们可以使用立方贝塞尔曲线将解决方案调整为如何连接点,同时考虑每个点的位置和方向.

我们的想法是通过创建一组随机点get_random_pointsget_bezier_curve使用这些点调用函数.这创建了一组贝塞尔曲线,它们在输入点处平滑地相互连接.我们还确保它们是循环的,即起点和终点之间的过渡也是平滑的.

import numpy as np
from scipy.special import binom
import matplotlib.pyplot as plt


bernstein = lambda n, k, t: binom(n,k)* t**k * (1.-t)**(n-k)

def bezier(points, num=200):
    N = len(points)
    t = np.linspace(0, 1, num=num)
    curve = np.zeros((num, 2))
    for i in range(N):
        curve += np.outer(bernstein(N - 1, i, t), points[i])
    return curve

class Segment():
    def __init__(self, p1, p2, angle1, angle2, **kw):
        self.p1 = p1; self.p2 = p2
        self.angle1 = angle1; self.angle2 = angle2
        self.numpoints = kw.get("numpoints", 100)
        r = kw.get("r", 0.3)
        d = np.sqrt(np.sum((self.p2-self.p1)**2))
        self.r = r*d
        self.p = np.zeros((4,2))
        self.p[0,:] = self.p1[:]
        self.p[3,:] = self.p2[:]
        self.calc_intermediate_points(self.r)

    def calc_intermediate_points(self,r):
        self.p[1,:] = self.p1 + np.array([self.r*np.cos(self.angle1),
                                    self.r*np.sin(self.angle1)])
        self.p[2,:] = self.p2 + np.array([self.r*np.cos(self.angle2+np.pi),
                                    self.r*np.sin(self.angle2+np.pi)])
        self.curve = bezier(self.p,self.numpoints)


def get_curve(points, **kw):
    segments = []
    for i in range(len(points)-1):
        seg = Segment(points[i,:2], points[i+1,:2], points[i,2],points[i+1,2],**kw)
        segments.append(seg)
    curve = np.concatenate([s.curve for s in segments])
    return segments, curve

def ccw_sort(p):
    d = p-np.mean(p,axis=0)
    s = np.arctan2(d[:,0], d[:,1])
    return p[np.argsort(s),:]

def get_bezier_curve(a, rad=0.2, edgy=0):
    """ given an array of points *a*, create a curve through
    those points. 
    *rad* is a number between 0 and 1 to steer the distance of
          control points.
    *edgy* is a parameter which controls how "edgy" the curve is,
           edgy=0 is smoothest."""
    p = np.arctan(edgy)/np.pi+.5
    a = ccw_sort(a)
    a = np.append(a, np.atleast_2d(a[0,:]), axis=0)
    d = np.diff(a, axis=0)
    ang = np.arctan2(d[:,1],d[:,0])
    f = lambda ang : (ang>=0)*ang + (ang<0)*(ang+2*np.pi)
    ang = f(ang)
    ang1 = ang
    ang2 = np.roll(ang,1)
    ang = p*ang1 + (1-p)*ang2 + (np.abs(ang2-ang1) > np.pi )*np.pi
    ang = np.append(ang, [ang[0]])
    a = np.append(a, np.atleast_2d(ang).T, axis=1)
    s, c = get_curve(a, r=rad, method="var")
    x,y = c.T
    return x,y, a


def get_random_points(n=5, scale=0.8, mindst=None, rec=0):
    """ create n random points in the unit square, which are *mindst*
    apart, then scale them."""
    mindst = mindst or .7/n
    a = np.random.rand(n,2)
    d = np.sqrt(np.sum(np.diff(ccw_sort(a), axis=0), axis=1)**2)
    if np.all(d >= mindst) or rec>=200:
        return a*scale
    else:
        return get_random_points(n=n, scale=scale, mindst=mindst, rec=rec+1)
Run Code Online (Sandbox Code Playgroud)

您可以使用这些功能,例如

fig, ax = plt.subplots()
ax.set_aspect("equal")

rad = 0.2
edgy = 0.05

for c in np.array([[0,0], [0,1], [1,0], [1,1]]):

    a = get_random_points(n=7, scale=1) + c
    x,y, _ = get_bezier_curve(a,rad=rad, edgy=edgy)
    plt.plot(x,y)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我们可以检查参数如何影响结果.这里基本上有3个参数:

  • rad,贝塞尔曲线控制点所在点周围的半径.该数字相对于相邻点之间的距离,因此应在0和1之间.半径越大,曲线的特征越清晰.
  • edgy,一个确定曲线平滑度的参数.如果为0,则通过每个点的曲线角度将是相邻点的方向之间的平均值.它越大,角度将仅由一个相邻点确定.因此曲线变得"更加锐利".
  • n要使用的随机点数.当然最小点数是3.你使用的点数越多,形状就越丰富; 冒着在曲线中产生重叠或循环的风险.

在此输入图像描述 在此输入图像描述 在此输入图像描述

  • 基于这个优秀的答案,我编写了一个小项目,允许使用贝塞尔曲线做一些事情(生成随机形状,生成随机形状的数据集,网格形状,形状为孔的网格域等)。阅读此页面的人可能对此感兴趣:https://github.com/jviquerat/bezier_shapes (2认同)

Ori*_*ril 6

matplotlib路径

一种简单的方法来获得随机且相当平滑的形状是使用matplotlib.path模块。

使用三次贝塞尔曲线,将对大多数线条进行平滑处理,并且锐边的数量将成为要调整的参数之一。

步骤如下。首先定义形状的参数,这些参数是锐边的数量n和相对于单位圆中默认位置的最大摄动r。在这个例子中,点从单位圆的径向修正,其修正为1〜之间的随机数半径方向移动1-r1+r

这就是为什么将顶点定义为相应角度的正弦或余弦乘以半径因子,以便将点放置在圆中,然后修改其半径以引入随机分量的原因。的stack.T转置和[:,None]仅仅是对阵列转换成由matplotlib接受的输入。

下面是使用这种径向校正的示例:

from matplotlib.path import Path
import matplotlib.patches as patches

n = 8 # Number of possibly sharp edges
r = .7 # magnitude of the perturbation from the unit circle, 
# should be between 0 and 1
N = n*3+1 # number of points in the Path
# There is the initial point and 3 points per cubic bezier curve. Thus, the curve will only pass though n points, which will be the sharp edges, the other 2 modify the shape of the bezier curve

angles = np.linspace(0,2*np.pi,N)
codes = np.full(N,Path.CURVE4)
codes[0] = Path.MOVETO

verts = np.stack((np.cos(angles),np.sin(angles))).T*(2*r*np.random.random(N)+1-r)[:,None]
verts[-1,:] = verts[0,:] # Using this instad of Path.CLOSEPOLY avoids an innecessary straight line
path = Path(verts, codes)

fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='none', lw=2)
ax.add_patch(patch)

ax.set_xlim(np.min(verts)*1.1, np.max(verts)*1.1)
ax.set_ylim(np.min(verts)*1.1, np.max(verts)*1.1)
ax.axis('off') # removes the axis to leave only the shape
Run Code Online (Sandbox Code Playgroud)

用于n=8r=0.7产生如下形状:

形状


高斯滤波的matplotlib路径

还可以选择使用上面的代码为单个形状生成形状,然后使用scipy对生成的图像执行高斯滤波

执行高斯滤波器并检索平滑形状的主要思想是创建填充形状。将图像保存为2d数组(其值将在0到1之间,因为它将是灰度图像);然后应用高斯滤波器;最终获得平滑的形状作为过滤后的数组的0.5轮廓。

因此,第二个版本看起来像:

# additional imports
from skimage import color as skolor # see the docs at scikit-image.org/
from skimage import measure
from scipy.ndimage import gaussian_filter

sigma = 7 # smoothing parameter
# ...
path = Path(verts, codes)

ax = fig.add_axes([0,0,1,1]) # create the subplot filling the whole figure
patch = patches.PathPatch(path, facecolor='k', lw=2) # Fill the shape in black
# ...
ax.axis('off')

fig.canvas.draw()

##### Smoothing ####
# get the image as an array of values between 0 and 1
data = data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
gray_image = skolor.rgb2gray(data)

# filter the image
smoothed_image = gaussian_filter(gray_image,sigma)

# Retrive smoothed shape as 0.5 contour
smooth_contour = measure.find_contours(smoothed_image[::-1,:], 0.5)[0] 
# Note, the values of the contour will range from 0 to smoothed_image.shape[0] 
# and likewise for the second dimension, if desired, 
# they should be rescaled to go between 0,1 afterwards

# compare smoothed ans original shape
fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(1,2,1)
patch = patches.PathPatch(path, facecolor='none', lw=2)
ax1.add_patch(patch)
ax1.set_xlim(np.min(verts)*1.1, np.max(verts)*1.1)
ax1.set_ylim(np.min(verts)*1.1, np.max(verts)*1.1)
ax1.axis('off') # removes the axis to leave only the shape
ax2 = fig.add_subplot(1,2,2)
ax2.plot(smooth_contour[:, 1], smooth_contour[:, 0], linewidth=2, c='k')
ax2.axis('off')
Run Code Online (Sandbox Code Playgroud)

光滑的形状