Python随机生成2堆三维点云点,有固定的重复率并可视化
- 1. 效果图
- 2. 源码
这篇博客源于博友的提问,刚好电脑在旁边没啥事,那就开整吧。
-
np.random 生成随机点(提供了俩种方法,1. xyz限制都是0~MAX值,2. xyz分别限制最大值为0~MAXxyz)
-
第一堆生成完成后,第2堆确定的是重复的点,然后生成剩余的点,生成过程要注意判断不能生成已经有了的点
-
open3d可视化及计算验证重复率。
1. 效果图
随机生成俩堆点云10000点,重复率0.3,3000个重复点效果图如下:
xyz均为0~MAX:
第1堆点红色 VS 第2堆点绿色效果图如下:
xyz分别限定0~MAXxyz:
第1堆点红色 VS 第2堆点绿色效果图如下:
2. 源码
# 随机生成俩堆点云,具有固定的重复率
# gene_repeat_points.py
import random
import numpy as np
import open3d as o3d
# 点个数,重复率
total_cnt = 10000
rate = 0.3
# xyz 最大值范围
max = 10
MAXX, MAXY, MAXZ = 3, 4, 7
repeat_cnt = int(total_cnt * rate)
# 随机种子,以便复现结果
random.seed(10)
# flag=1 xyz均为0~max值
# flag=其他值 xyz分别为x~MAXX,y~MAXY,z~MAXZ
def gene_one_point(flag=1):
if flag == 1:
pts = np.array(np.random.random(size=(3,)) * max)
else:
x = np.random.random() * MAXX
y = np.random.random() * MAXY
z = np.random.random() * MAXZ
pts = np.array([x, y, z])
return pts
# 随机生成点云点points
def point_generator(total_cnt):
result = []
for i in range(total_cnt):
pts = gene_one_point(flag=1)
result.append(list(pts))
return result
origin_points = point_generator(total_cnt)
print(type(origin_points), len(origin_points), origin_points[:5])
def repeat_point_generator(origin_points, total_cnt):
result = []
set_points = set()
for x in origin_points:
set_points.add(str(x[0]) + '_' + str(x[1]) + '_' + str(x[2]))
result = [x for x in origin_points]
while (len(result) < total_cnt):
pts = pts = gene_one_point(flag=1)
key = str(pts[0]) + '_' + str(pts[1]) + '_' + str(pts[2])
if key in set_points:
continue
else:
set_points.add(key)
result.append(list(pts))
return result
points2 = repeat_point_generator(origin_points[:repeat_cnt], total_cnt)
print(type(points2), len(points2), points2[:5])
# 构造点云数据
pcd = o3d.geometry.PointCloud()
points = o3d.utility.Vector3dVector(origin_points)
pcd.points = points
pcd.paint_uniform_color([1, 0, 0]) # 把原始点渲染为红色
pcd2 = o3d.geometry.PointCloud()
pcd_points = o3d.utility.Vector3dVector(points2)
pcd2.points = pcd_points
pcd2.paint_uniform_color([0, 1, 0]) # 把原始点渲染为绿色
o3d.visualization.draw_geometries([pcd, pcd2], "Open3D origin VS repeatAfter",
width=800,
height=600, left=50,
top=50,
point_show_normal=False, mesh_show_wireframe=False,
mesh_show_back_face=False)
np_origin = np.array([str(x[0]) + '_' + str(x[1]) + '_' + str(x[2]) for x in origin_points])
np_origin2 = np.array([str(x[0]) + '_' + str(x[1]) + '_' + str(x[2]) for x in points2])
inters = np.intersect1d(np_origin, np_origin2)
print('inter: ', len(inters))