python - 如何通过移动中心坐标从2D切片生成弯曲管?

标签 python numpy opencv

我正在尝试通过管结构生成3D矩阵。我可以通过复制一个2D numpy数组(其中的圆以内部(x,y)为中心)来使管变直,并且可以通过在生成的每个 slice 的x或y轴上添加一个int来使管倾斜。我的问题是,如何移动(x,y)坐标以使其形成曲线?我不能将诸如正弦和余弦之类的曲线函数的步长添加到坐标中,因为要索引numpy数组,它必须是整数。通过移动中心坐标从2D slice 生成弯曲管的聪明方法是什么?

这是我用来生成直管作为3D矩阵的代码:

import numpy as np 
import cv2
import matplotlib.pyplot as plt

slice_2d = np.zeros((128,128))
circle_center = (50,50)
radius=10

slice_2d = cv2.circle(slice_2d, circle_center, radius, color=1, thickness=-1)
plt.imshow(slice_2d)

# then we repeat the slice 128 times to create a straight tube in a 3D matrix of 128,128,128
tube_matrix = []
for i in range(0,128):
    tube_matrix.append(slice_2d)

tube_matrix = np.array(tube_matrix)

最佳答案

您可以根据需要使用任何曲线,缩放比例并添加偏移量,并且舍入到中心坐标为整数。

我将曲线用于this post

这是添加 slice 的循环:

tube_matrix = []
for i in range(128):    
    circle_center = np.round(curve[i]*12 + 15).astype(int)
    slice_2d = cv2.circle(np.zeros((128,128)), tuple(circle_center), radius, color=1, thickness=-1)
    tube_matrix.append(slice_2d)

每次迭代,圆心都会根据curve[i]的值而变化。
请注意,curve[i]已缩放和四舍五入(并转换为int)。

这是完整的代码(带有一些测试代码):
import numpy as np
import cv2
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

# https://stackoverflow.com/questions/52014197/how-to-interpolate-a-2d-curve-in-python
# Define some points:
points = np.array([[0, 1, 8, 2, 2],
                   [1, 0, 6, 7, 2]]).T  # a (nbre_points x nbre_dim) array

# Linear length along the line:
distance = np.cumsum( np.sqrt(np.sum( np.diff(points, axis=0)**2, axis=1 )) )
distance = np.insert(distance, 0, 0)/distance[-1]

alpha = np.linspace(0, 1, 128)

method = 'cubic'   
interpolator =  interp1d(distance, points, kind=method, axis=0)
curve = interpolator(alpha)

#slice_2d = np.zeros((128,128))
#circle_center = (30, 30)
img = np.zeros((128, 128, 3), np.uint8) + 255
radius = 10

tube_matrix = []
for i in range(128):    
    circle_center = np.round(curve[i]*12 + 15).astype(int)
    slice_2d = cv2.circle(np.zeros((128,128)), tuple(circle_center), radius, color=1, thickness=-1)
    tube_matrix.append(slice_2d)

    #Draw cicle on image - for testing
    img = cv2.circle(img, tuple(circle_center), radius, color=(i*10 % 255, i*20 % 255, i*30 % 255), thickness=2)

# Graph:
plt.figure(figsize=(7,7))
plt.plot(*curve.T, 'o')
plt.axis('equal'); plt.legend(); plt.xlabel('x'); plt.ylabel('y')

plt.figure(figsize=(7,7))
plt.imshow(img)
plt.show()

测试图片(img):
enter image description here

关于python - 如何通过移动中心坐标从2D切片生成弯曲管?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60659978/

相关文章:

python - NumPy 中的多轴均值

python - 按值拆分为等份

python - `solve` 相当于 `pinv` 吗?

python - 使用SSIM尝试比较图像并尝试分别获取亮度,对比度和结构

带有 Windows 共享文件夹的 Python3

python - python中如何高效地将同一个模块导入到多个子包中

python - 如何从图像中删除方括号?

matlab - 什么是最好的相机校准方法?

python - Scrapy可以用pyspider代替吗?

python - Django 的两个字段之一不能为空