简介:拍摄一个端面的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()
效果图: