适合平滑曲线的点

时间:2016-08-26 08:54:45

标签: python opencv matplotlib computer-vision scikit-image

我想在python中使用 smooth 曲线在图像上拟合一组点。曲线可以是打开的或关闭的。此外,我想将在图像上绘制的曲线绘制为与图像具有相同大小的蒙版。我可以参考哪些模块或功能?感谢。

1 个答案:

答案 0 :(得分:0)

这通常称为参数插值。有一个scipy函数可以执行名为splprep的函数。您要求的步骤是:

1)平滑形状(使用有序点构建,如果不首先使用convex hull,请检查this question)。

注意: 了解有关如何在图片检查上创建形状的更多信息 this question

2)使用平滑的形状在图像上构建遮罩(比方说2D阵列)。

以下食谱可以做到:

import numpy as np
from scipy.interpolate import splprep, splev
import matplotlib.pyplot as plt
from matplotlib import path

# Building a shape with scattered points.
x = np.array([10, 10, 0, 0, 10, 10, 20, 20, 30, 30, 20, 20, 10]) + 10
y = np.array([0, 10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]) + 10
image = np.random.randint(0, 10, (50, 50))

# Smoothing the shape.
# spline parameters
s = 3.0 # smoothness parameter
k = 2 # spline order
nest = -1 # estimate of number of knots needed (-1 = maximal)
t, u = splprep([x, y], s=s, k=k, nest=-1)
xn, yn = splev(np.linspace(0, 1, 500), t)

# Showing the original shape
plt.imshow(image.T, origin='lower', interpolation='nearest', cmap='gray')
plt.plot(x, y, color='b', linewidth=3)
plt.xlim(0, 50)
plt.ylim(0, 50)
plt.show()

# Showing the original shape vs smooth shape
plt.imshow(image.T, origin='lower', interpolation='nearest', cmap='gray')
plt.plot(x, y, color='b', linewidth=3)
plt.plot(xn, yn, color='r', linewidth=3)
plt.xlim(0, 50)
plt.ylim(0, 50)
plt.show()

# Changing values inside the shape (and outside). Building a boolean mask.
image1 = image.copy()
image2 = image.copy()
mask = np.zeros(image.shape)
xx, yy = np.meshgrid(range(image.shape[0]),range(image.shape[1]))
shapes = np.hstack((xn[:, np.newaxis], yn[:, np.newaxis]))
p = path.Path(shapes)
for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        if not p.contains_point((i, j)):
            image1[i, j] = 0
            mask[i, j] = True
        else:
            image2[i, j] = 0

# Showing changes in image for values outside shape.
plt.imshow(image1.T, origin='lower', interpolation='nearest', cmap='gray')
plt.plot(xn, yn, color='r', linewidth=3)
plt.xlim(0, 50)
plt.ylim(0, 50)
plt.show()

# Showing changes in image for values inside shape.
plt.imshow(image2.T, origin='lower', interpolation='nearest', cmap='gray')
plt.plot(xn, yn, color='r', linewidth=3)
plt.xlim(0, 50)
plt.ylim(0, 50)
plt.show()

对代码进行了评论,以便您了解每个结果图中发生的情况:

Simple Shape over image 1. 图像上的简单形状

Simple vs Smooth shape over image 2. 图像上的简单与平滑形状

Use values inside shape 3. 使用形状内的值

Use values outside shape 4. 使用形状外的值