测试环境:
pycolmap==3.11.1
测试代码:
import os
import numpy as np
import pycolmap
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def reconstruct_and_visualize(image_dir, output_dir):
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
# 1. 设置数据库路径
database_path = os.path.join(output_dir, "database.db")
if os.path.exists(database_path):
os.remove(database_path)
# 2. 运行特征提取
pycolmap.extract_features(database_path, image_dir)
# 3. 运行特征匹配
pycolmap.match_exhaustive(database_path)
# 4. 运行增量式重建
maps = pycolmap.incremental_mapping(
database_path=database_path,
image_path=image_dir,
output_path=output_dir,
)
# 5. 检查重建结果
if not maps:
print("重建失败!")
return None
# 获取第一个重建结果
reconstruction = maps[0]
# 6. 检查是否有3D点
if not reconstruction.points3D:
print("重建成功,但没有生成3D点云。")
return reconstruction
# 7. 提取点云数据
points3D = reconstruction.points3D
xyz = np.array([p.xyz for p in points3D.values()])
rgb = np.array([p.color for p in points3D.values()]) / 255.0
# 8. 可视化点云
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection="3d")
ax.scatter(
xyz[:, 0], xyz[:, 1], xyz[:, 2],
c=rgb,
s=1,
alpha=0.8,
marker="."
)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D Reconstruction Point Cloud")
plt.tight_layout()
plt.show()
return reconstruction
# 使用示例
image_dir = r"D:\images"
output_dir = r"D:\output"
reconstruction = reconstruct_and_visualize(image_dir, output_dir)
结果: