拟合圆,确定圆心及半径

简介:拍摄一个端面的pcd点云文件,把下面的点云通过深度信息截掉了,过滤的大部分噪点。拍摄的端面圆不完整,仅有1/3左右

方法一:拟合最小外接圆#######这个效果不好,因为没有拍到完整的圆,不准确



####拟合最小外接圆#######这个效果不好,因为没有拍到完整的圆,不准确####
import open3d as o3d
import numpy as np
import cv2
import matplotlib.pyplot as plt

# 读取PCD文件
file_path = 'F:/Desktop/test/duanmian/point_cloud_00007 - Cloud.pcd'
# file_path = 'F:\Desktop\test\duanmian\point_cloud_00000.ply'
pcd = o3d.io.read_point_cloud(file_path)

# 将点云转换为numpy数组
points = np.asarray(pcd.points)

# 假设端面在Z轴上,你可以选择投影到XY平面
points_2d = points[:, :2]

# 仅选取一定范围内的点,或根据需要进行过滤
points_2d = np.float32(points_2d)

# 使用OpenCV拟合最小外接圆
(center, radius) = cv2.minEnclosingCircle(points_2d)
center = (round(center[0], 8), round(center[1], 8))
radius = round(radius, 8)

# 打印结果,精确到小数点后8位
print(f'圆心坐标: ({center[0]:.8f}, {center[1]:.8f})')
print(f'圆半径: {radius:.8f}')

# 可选:在点云上绘制拟合结果(可视化)
plt.scatter(points_2d[:, 0], points_2d[:, 1], s=1)
circle = plt.Circle(center, radius, color='r', fill=False)
plt.gca().add_patch(circle)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

效果图:

这种方法适合用于拍摄完整的端面圆

方法二:使用最小二乘法拟合圆




# 使用最小二乘法拟合圆
import numpy as np
import open3d as o3d
import matplotlib.pyplot as plt

def fit_circle_least_squares(points):
    A = np.c_[2*points[:,0], 2*points[:,1], np.ones(points.shape[0])]
    B = np.sum(points**2, axis=1)
    C, _, _, _ = np.linalg.lstsq(A, B, rcond=None)
    a, b, c = C
    center = np.array([a, b])
    radius = np.sqrt(center[0]**2 + center[1]**2 + c)
    return center, radius

# 读取PCD文件
file_path = 'F:/Desktop/test/duanmian/point_cloud_00007 - Cloud.pcd'
pcd = o3d.io.read_point_cloud(file_path)

# 将点云转换为numpy数组
points = np.asarray(pcd.points)

# 假设端面在Z轴上,你可以选择投影到XY平面
points_2d = points[:, :2]
points_2d = np.float32(points_2d)

# 拟合圆
center, radius = fit_circle_least_squares(points_2d)
center = (round(center[0], 8), round(center[1], 8))
radius = round(radius, 8)

print(f'圆心坐标: ({center[0]:.8f}, {center[1]:.8f})')
print(f'圆半径: {radius:.8f}')

# 可选:在点云上绘制拟合结果(可视化)
plt.scatter(points_2d[:, 0], points_2d[:, 1], s=1)
circle = plt.Circle(center, radius, color='r', fill=False)
plt.gca().add_patch(circle)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值