当前位置:   article > 正文

open3d python 学习笔记_python open3d

python open3d

目录

安装及示例

显示obj对象,设置一种颜色:

读取转换txt

 draw和draw_geometries区别

可视化完整demo

保存png


安装及示例

pip install open3d

插播:mayavi也可以可视化点云。

conda install mayavi

示例demo:

GitHub - isl-org/Open3D: Open3D: A Modern Library for 3D Data Processing

添加物体:

examples/python/gui/add-geometry.py

显示obj对象,设置一种颜色:

  1. import copy
  2. import numpy as np
  3. import open3d as o3d
  4. if __name__ == '__main__':
  5. print("Testing mesh in open3d ...")
  6. mesh = o3d.io.read_triangle_mesh("../mesh.obj")
  7. print(mesh)
  8. print(np.asarray(mesh.vertices))
  9. print(np.asarray(mesh.triangles))
  10. verts = np.asarray(mesh.vertices)
  11. mesh.vertices = o3d.utility.Vector3dVector(verts)
  12. mesh.compute_vertex_normals()
  13. mesh.paint_uniform_color([0.6, 0.1, 0.5])
  14. cords = o3d.geometry.TriangleMesh.create_coordinate_frame()
  15. o3d.visualization.draw_geometries([mesh])

读取转换txt

  1. import open3d as o3d
  2. source = o3d.io.read_point_cloud('semantic3d/birdfountain_station1_xyz_intensity_rgb.txt' ,format="xyz")
  3. source.paint_uniform_color([0, 255, 0])
  4. o3d.visualization.draw_geometries([source])

保存:

  1. 3.直接读取、写pcd、mesh文件
  2. pcd = open3d.io.read_point_cloud(pcd_file_path)
  3. open3d.io.write_point_cloud("filename.pcd",pcd)
  4. open3d.io.write_point_cloud("aaaa.ply",pcd)

 draw和draw_geometries区别

draw PointCloud,会出现菜单,按钮,但是点云不能旋转平移。

  1. pc =open3d.geometry.PointCloud()
  2. # pc = open3d.PointCloud()
  3. pc.points = open3d.utility.Vector3dVector(pc_xyzrgb[:, 0:3])
  4. #pc.points = open3d.Vector3dVector(pc_xyzrgb[:, 0:3])
  5. if pc_xyzrgb.shape[1] == 3:
  6. open3d.draw_geometries([pc])
  7. return 0
  8. if np.max(pc_xyzrgb[:, 3:6]) > 20: ## 0-255
  9. pc.colors =[255,0,0]# open3d.utility.Vector3dVector(pc_xyzrgb[:, 3:6] *255/ 255.)
  10. else:
  11. pc.colors =open3d.utility.Vector3dVector(pc_xyzrgb[:, 3:6])
  12. # open3d.visualization.draw_geometries([pc])
  13. open3d.visualization.draw([pc])

可视化完整demo

同时显示两个物体,设置不同颜色

  1. import math
  2. import numpy as np
  3. import open3d as o3d
  4. import open3d.visualization as vis
  5. import os
  6. import random
  7. import sys
  8. sys.path.insert(1, os.path.join(sys.path[0], '..'))
  9. import open3d_tutorial as o3dtut
  10. SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
  11. def normalize(v):
  12. a = 1.0 / math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
  13. return (a * v[0], a * v[1], a * v[2])
  14. def make_point_cloud(npts, center, radius, colorize):
  15. pts = np.random.uniform(-radius, radius, size=[npts, 3]) + center
  16. cloud = o3d.geometry.PointCloud()
  17. cloud.points = o3d.utility.Vector3dVector(pts)
  18. if colorize:
  19. colors = np.random.uniform(0.0, 1.0, size=[npts, 3])
  20. cloud.colors = o3d.utility.Vector3dVector(colors)
  21. return cloud
  22. def single_object():
  23. # No colors, no normals, should appear unlit black
  24. cube = o3d.geometry.TriangleMesh.create_box(1, 2, 1)
  25. vis.draw(cube)
  26. def multi_objects():
  27. pc_rad = 1.0
  28. pc_nocolor = make_point_cloud(100, (0, -2, 0), pc_rad, False)
  29. pc_color = make_point_cloud(100, (3, -2, 0), pc_rad, True)
  30. r = 0.4
  31. sphere_unlit = o3d.geometry.TriangleMesh.create_sphere(r)
  32. sphere_unlit.paint_uniform_color((0.5, 0.5, 0.0)) #颜色 rgb
  33. sphere_unlit.translate((0, 1, 0)) #位置格子
  34. sphere_colored_unlit = o3d.geometry.TriangleMesh.create_sphere(r)
  35. sphere_colored_unlit.paint_uniform_color((1.0, 0.0, 0.0))
  36. sphere_colored_unlit.translate((2, 1, 0))
  37. sphere_lit = o3d.geometry.TriangleMesh.create_sphere(r)
  38. sphere_lit.compute_vertex_normals()
  39. sphere_lit.translate((4, 1, 0))
  40. sphere_colored_lit = o3d.geometry.TriangleMesh.create_sphere(r)
  41. sphere_colored_lit.compute_vertex_normals()
  42. sphere_colored_lit.paint_uniform_color((0.0, 1.0, 0.0))
  43. sphere_colored_lit.translate((6, 1, 0))
  44. big_bbox = o3d.geometry.AxisAlignedBoundingBox((-pc_rad, -3, -pc_rad),
  45. (6.0 + r, 1.0 + r, pc_rad))
  46. sphere_bbox = sphere_unlit.get_axis_aligned_bounding_box()
  47. sphere_bbox.color = (1.0, 0.5, 0.0)
  48. lines = o3d.geometry.LineSet.create_from_axis_aligned_bounding_box(
  49. sphere_lit.get_axis_aligned_bounding_box())
  50. lines_colored = o3d.geometry.LineSet.create_from_axis_aligned_bounding_box(
  51. sphere_colored_lit.get_axis_aligned_bounding_box())
  52. lines_colored.paint_uniform_color((0.0, 0.0, 1.0))
  53. vis.draw([
  54. pc_nocolor, pc_color, sphere_unlit, sphere_colored_unlit, sphere_lit,
  55. sphere_colored_lit, big_bbox, sphere_bbox, lines, lines_colored
  56. ])
  57. def actions():
  58. SOURCE_NAME = "Source"
  59. RESULT_NAME = "Result (Poisson reconstruction)"
  60. TRUTH_NAME = "Ground truth"
  61. bunny = o3dtut.get_bunny_mesh()
  62. bunny.paint_uniform_color((1, 0.75, 0))
  63. bunny.compute_vertex_normals()
  64. cloud = o3d.geometry.PointCloud()
  65. cloud.points = bunny.vertices
  66. cloud.normals = bunny.vertex_normals
  67. def make_mesh(o3dvis):
  68. # TODO: call o3dvis.get_geometry instead of using bunny
  69. mesh, _ = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
  70. cloud)
  71. mesh.paint_uniform_color((1, 1, 1))
  72. mesh.compute_vertex_normals()
  73. o3dvis.add_geometry({"name": RESULT_NAME, "geometry": mesh})
  74. o3dvis.show_geometry(SOURCE_NAME, False)
  75. def toggle_result(o3dvis):
  76. truth_vis = o3dvis.get_geometry(TRUTH_NAME).is_visible
  77. o3dvis.show_geometry(TRUTH_NAME, not truth_vis)
  78. o3dvis.show_geometry(RESULT_NAME, truth_vis)
  79. vis.draw([{
  80. "name": SOURCE_NAME,
  81. "geometry": cloud
  82. }, {
  83. "name": TRUTH_NAME,
  84. "geometry": bunny,
  85. "is_visible": False
  86. }],
  87. actions=[("Create Mesh", make_mesh),
  88. ("Toggle truth/result", toggle_result)])
  89. def get_icp_transform(source, target, source_indices, target_indices):
  90. corr = np.zeros((len(source_indices), 2))
  91. corr[:, 0] = source_indices
  92. corr[:, 1] = target_indices
  93. # Estimate rough transformation using correspondences
  94. p2p = o3d.pipelines.registration.TransformationEstimationPointToPoint()
  95. trans_init = p2p.compute_transformation(source, target,
  96. o3d.utility.Vector2iVector(corr))
  97. # Point-to-point ICP for refinement
  98. threshold = 0.03 # 3cm distance threshold
  99. reg_p2p = o3d.pipelines.registration.registration_icp(
  100. source, target, threshold, trans_init,
  101. o3d.pipelines.registration.TransformationEstimationPointToPoint())
  102. return reg_p2p.transformation
  103. def selections():
  104. source = o3d.io.read_point_cloud(SCRIPTDIR +
  105. "/../../test_data/ICP/cloud_bin_0.pcd")
  106. target = o3d.io.read_point_cloud(SCRIPTDIR +
  107. "/../../test_data/ICP/cloud_bin_2.pcd")
  108. source.paint_uniform_color([1, 0.706, 0])
  109. target.paint_uniform_color([0, 0.651, 0.929])
  110. source_name = "Source (yellow)"
  111. target_name = "Target (blue)"
  112. def do_icp_one_set(o3dvis):
  113. # sets: [name: [{ "index": int, "order": int, "point": (x, y, z)}, ...],
  114. # ...]
  115. sets = o3dvis.get_selection_sets()
  116. source_picked = sorted(list(sets[0][source_name]),
  117. key=lambda x: x.order)
  118. target_picked = sorted(list(sets[0][target_name]),
  119. key=lambda x: x.order)
  120. source_indices = [idx.index for idx in source_picked]
  121. target_indices = [idx.index for idx in target_picked]
  122. t = get_icp_transform(source, target, source_indices, target_indices)
  123. source.transform(t)
  124. # Update the source geometry
  125. o3dvis.remove_geometry(source_name)
  126. o3dvis.add_geometry({"name": source_name, "geometry": source})
  127. def do_icp_two_sets(o3dvis):
  128. sets = o3dvis.get_selection_sets()
  129. source_set = sets[0][source_name]
  130. target_set = sets[1][target_name]
  131. source_picked = sorted(list(source_set), key=lambda x: x.order)
  132. target_picked = sorted(list(target_set), key=lambda x: x.order)
  133. source_indices = [idx.index for idx in source_picked]
  134. target_indices = [idx.index for idx in target_picked]
  135. t = get_icp_transform(source, target, source_indices, target_indices)
  136. source.transform(t)
  137. # Update the source geometry
  138. o3dvis.remove_geometry(source_name)
  139. o3dvis.add_geometry({"name": source_name, "geometry": source})
  140. vis.draw([{
  141. "name": source_name,
  142. "geometry": source
  143. }, {
  144. "name": target_name,
  145. "geometry": target
  146. }],)
  147. # actions=[("ICP Registration (one set)", do_icp_one_set),
  148. # ("ICP Registration (two sets)", do_icp_two_sets)],
  149. # show_ui=True)
  150. def time_animation():
  151. orig = make_point_cloud(200, (0, 0, 0), 1.0, True)
  152. clouds = [{"name": "t=0", "geometry": orig, "time": 0}]
  153. drift_dir = (1.0, 0.0, 0.0)
  154. expand = 1.0
  155. n = 20
  156. for i in range(1, n):
  157. amount = float(i) / float(n - 1)
  158. cloud = o3d.geometry.PointCloud()
  159. pts = np.asarray(orig.points)
  160. pts = pts * (1.0 + amount * expand) + [amount * v for v in drift_dir]
  161. cloud.points = o3d.utility.Vector3dVector(pts)
  162. cloud.colors = orig.colors
  163. clouds.append({
  164. "name": "points at t=" + str(i),
  165. "geometry": cloud,
  166. "time": i
  167. })
  168. vis.draw(clouds)
  169. def groups():
  170. building_mat = vis.rendering.Material()
  171. building_mat.shader = "defaultLit"
  172. building_mat.base_color = (1.0, .90, .75, 1.0)
  173. building_mat.base_reflectance = 0.1
  174. midrise_mat = vis.rendering.Material()
  175. midrise_mat.shader = "defaultLit"
  176. midrise_mat.base_color = (.475, .450, .425, 1.0)
  177. midrise_mat.base_reflectance = 0.1
  178. skyscraper_mat = vis.rendering.Material()
  179. skyscraper_mat.shader = "defaultLit"
  180. skyscraper_mat.base_color = (.05, .20, .55, 1.0)
  181. skyscraper_mat.base_reflectance = 0.9
  182. skyscraper_mat.base_roughness = 0.01
  183. buildings = []
  184. size = 10.0
  185. half = size / 2.0
  186. min_height = 1.0
  187. max_height = 20.0
  188. for z in range(0, 10):
  189. for x in range(0, 10):
  190. max_h = max_height * (1.0 - abs(half - x) / half) * (
  191. 1.0 - abs(half - z) / half)
  192. h = random.uniform(min_height, max(max_h, min_height + 1.0))
  193. box = o3d.geometry.TriangleMesh.create_box(0.9, h, 0.9)
  194. box.compute_triangle_normals()
  195. box.translate((x + 0.05, 0.0, z + 0.05))
  196. if h > 0.333 * max_height:
  197. mat = skyscraper_mat
  198. elif h > 0.1 * max_height:
  199. mat = midrise_mat
  200. else:
  201. mat = building_mat
  202. buildings.append({
  203. "name": "building_" + str(x) + "_" + str(z),
  204. "geometry": box,
  205. "material": mat,
  206. "group": "buildings"
  207. })
  208. haze = make_point_cloud(5000, (half, 0.333 * max_height, half),
  209. 1.414 * half, False)
  210. haze.paint_uniform_color((0.8, 0.8, 0.8))
  211. smog = make_point_cloud(10000, (half, 0.25 * max_height, half), 1.2 * half,
  212. False)
  213. smog.paint_uniform_color((0.95, 0.85, 0.75))
  214. vis.draw(buildings + [{
  215. "name": "haze",
  216. "geometry": haze,
  217. "group": "haze"
  218. }, {
  219. "name": "smog",
  220. "geometry": smog,
  221. "group": "smog"
  222. }])
  223. def remove():
  224. def make_sphere(name, center, color, group, time):
  225. sphere = o3d.geometry.TriangleMesh.create_sphere(0.5)
  226. sphere.compute_vertex_normals()
  227. sphere.translate(center)
  228. mat = vis.rendering.Material()
  229. mat.shader = "defaultLit"
  230. mat.base_color = color
  231. return {
  232. "name": name,
  233. "geometry": sphere,
  234. "material": mat,
  235. "group": group,
  236. "time": time
  237. }
  238. red = make_sphere("red", (0, 0, 0), (1.0, 0.0, 0.0, 1.0), "spheres", 0)
  239. green = make_sphere("green", (2, 0, 0), (0.0, 1.0, 0.0, 1.0), "spheres", 0)
  240. blue = make_sphere("blue", (4, 0, 0), (0.0, 0.0, 1.0, 1.0), "spheres", 0)
  241. yellow = make_sphere("yellow", (0, 0, 0), (1.0, 1.0, 0.0, 1.0), "spheres",
  242. 1)
  243. bbox = {
  244. "name": "bbox",
  245. "geometry": red["geometry"].get_axis_aligned_bounding_box()
  246. }
  247. def remove_green(visdraw):
  248. visdraw.remove_geometry("green")
  249. def remove_yellow(visdraw):
  250. visdraw.remove_geometry("yellow")
  251. def remove_bbox(visdraw):
  252. visdraw.remove_geometry("bbox")
  253. vis.draw([red, green, blue, yellow, bbox],
  254. actions=[("Remove Green", remove_green),
  255. ("Remove Yellow", remove_yellow),
  256. ("Remove Bounds", remove_bbox)])
  257. if __name__ == "__main__":
  258. # single_object()
  259. # multi_objects()
  260. # actions()
  261. selections()

保存png

  1. import open3d as o3d
  2. import open3d.visualization.rendering as rendering
  3. def main():
  4. render = rendering.OffscreenRenderer(640, 480)
  5. yellow = rendering.Material()
  6. yellow.base_color = [1.0, 0.75, 0.0, 1.0]
  7. yellow.shader = "defaultLit"
  8. green = rendering.Material()
  9. green.base_color = [0.0, 0.5, 0.0, 1.0]
  10. green.shader = "defaultLit"
  11. grey = rendering.Material()
  12. grey.base_color = [0.7, 0.7, 0.7, 1.0]
  13. grey.shader = "defaultLit"
  14. white = rendering.Material()
  15. white.base_color = [1.0, 1.0, 1.0, 1.0]
  16. white.shader = "defaultLit"
  17. cyl = o3d.geometry.TriangleMesh.create_cylinder(.05, 3)
  18. cyl.compute_vertex_normals()
  19. cyl.translate([-2, 0, 1.5])
  20. sphere = o3d.geometry.TriangleMesh.create_sphere(.2)
  21. sphere.compute_vertex_normals()
  22. sphere.translate([-2, 0, 3])
  23. box = o3d.geometry.TriangleMesh.create_box(2, 2, 1)
  24. box.compute_vertex_normals()
  25. box.translate([-1, -1, 0])
  26. solid = o3d.geometry.TriangleMesh.create_icosahedron(0.5)
  27. solid.compute_triangle_normals()
  28. solid.compute_vertex_normals()
  29. solid.translate([0, 0, 1.75])
  30. render.scene.add_geometry("cyl", cyl, green)
  31. render.scene.add_geometry("sphere", sphere, yellow)
  32. render.scene.add_geometry("box", box, grey)
  33. render.scene.add_geometry("solid", solid, white)
  34. render.setup_camera(60.0, [0, 0, 0], [0, 10, 0], [0, 0, 1])
  35. render.scene.scene.set_sun_light([0.707, 0.0, -.707], [1.0, 1.0, 1.0],
  36. 75000)
  37. render.scene.scene.enable_sun_light(True)
  38. render.scene.show_axes(True)
  39. img = render.render_to_image()
  40. o3d.io.write_image("test.png", img, 9)
  41. render.setup_camera(60.0, [0, 0, 0], [0, 10, 0], [0, 0, 1])
  42. img = render.render_to_image()
  43. o3d.io.write_image("test2.png", img, 9)
  44. if __name__ == "__main__":
  45. main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/894303
推荐阅读
相关标签
  

闽ICP备14008679号