酷代码 AI
菜单
服务商

Python实现心形点云生成算法并进行优化:附完整代码示例

```python import numpy as np import random import math from PIL import Image import os def genRandPoints(pointCount, heartScales, maxVar, ratio): """ 生成随机心形点云 Args: pointCount: 需要生成的点数 heartScales: 心形尺度参数 [scale1, scale2] maxVar: 最大变异系数 ratio: 缩放比例 """ result = np.empty((pointCount, 3)) index = 0 while index < pointCount: # 生成随机点 x = random.random() y = random.random() z = random.random() # 检查中间区域 mheartValue = heart_func(x, 0.5, z, heartScales[1]) mid_ignore = random.random() # 跳过中间区域 if mheartValue < 0 and mid_ignore < mid_point_ignore: continue # 检查心形边界 heartValue = heart_func(x, y, z, heartScales[0]) z_shrink = 0.01 sz = z - z_shrink sheartValue = heart_func(x, y, sz, heartScales[1]) # 保留边界点 if heartValue < 0 and sheartValue > 0: # 转换为中心坐标系 result[index] = [x - 0.5, y - 0.5, z - 0.5] # 应用随机变异 var = random.uniform(-maxVar, maxVar) result[index] = result[index] * (1 + var) # 应用缩放 result[index] = result[index] * ratio index += 1 # 进度显示 if index % 1000 == 0: progress = (index / pointCount) * 100 print(f"Generated {index} points ({progress:.1f}%)") return result[:index] # 返回实际生成的点 def save_points_to_file(points, filename): """ 保存点云数据到文件 Args: points: 点云数组 filename: 输出文件名 """ np.savetxt(filename, points, fmt='%.6f', delimiter=',') print(f"Points saved to {filename}") def load_points_from_file(filename): """ 从文件加载点云数据 Args: filename: 输入文件名 Returns: 点云数组 """ if os.path.exists(filename): points = np.loadtxt(filename, delimiter=',') print(f"Loaded {len(points)} points from {filename}") return points return None # 使用示例 if __name__ == "__main__": # 生成随机心形点云 heart_scales = [3.5, 3.9] random_points = genRandPoints( pointCount=10000, heartScales=heart_scales, maxVar=0.2, ratio=0.8 ) # 保存点云 save_points_to_file(random_points, "random_heart_points.txt") # 加载点云 loaded_points = load_points_from_file("random_heart_points.txt") ``` [2026-02-12 13:06:00 | AI写代码神器 | 745点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]