通过这个代码生成mask,获取相机坐标,图片信息,投影的过程,写个代码,让照片中的class为wall的pixel和相机中心形成一条射线,以相机中心为顶点延伸至无限长,然后这条射线会与0.793553x + -0.040436y + 0.607156z + -2.950997 = 0有个交点,把这个交点生成新的点云的点,然后和之前的ply模型中的点云的点融合形成新的点云模型,记住,相机不要000,要通过参数计算出相机中心的坐标!!!!选取的pixel必须是wall范围里的,选取的点要足够多,最好能覆盖wall区!!!必要时可以在open3d输出时标出射线情况和新的点的位置,最后再原有的点云模型上标注出新点,总而言之,从XML文件中读取相机的外参(即相机的变换矩阵)和标定数据,并使用这些信息生成投影,形成射线并与给定的平面相交,然后将交点作为新的点云点与原始点云融合!!!每一步加上步骤和运行进度同时能调整输入图片的数量,然后优化open3d显示,别让显示太卡,新点标注出来让我看一下,import os
import numpy as np
import xml.etree.ElementTree as ET
from pycocotools.coco import COCO
import cv2
import open3d as o3d
from numpy.linalg import inv
import math
Function to read camera transformations from XML
def read_camera_transforms(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
camera_info = []
for camera in root.iter('camera'):
camera_id = camera.attrib.get('id')
sensor_id = camera.attrib.get('sensor_id', 'default')
label = camera.attrib.get('label', 'No Label')
transform_text = camera.find('transform').text if camera.find('transform') is not None else "N/A"
camera_info.append({
'camera_id': camera_id,
'label': label,
'sensor_id': sensor_id,
'transform': transform_text
})
return camera_info
Function to read camera calibrations from XML
def read_camera_calibrations(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
sensor_calibrations = {}
for calibration in root.iter('calibration'):
try:
f = float(calibration.find('f').text) if calibration.find('f') is not None and calibration.find('f').text else 0
cx = float(calibration.find('cx').text) if calibration.find('cx') is not None and calibration.find('cx').text else 0
cy = float(calibration.find('cy').text) if calibration.find('cy') is not None and calibration.find('cy').text else 0
k1 = float(calibration.find('k1').text) if calibration.find('k1') is not None and calibration.find('k1').text else 0
k2 = float(calibration.find('k2').text) if calibration.find('k2') is not None and calibration.find('k2').text else 0
k3 = float(calibration.find('k3').text) if calibration.find('k3') is not None and calibration.find('k3').text else 0
k4 = float(calibration.find('k4').text) if calibration.find('k4') is not None and calibration.find('k4').text else 0
p1 = float(calibration.find('p1').text) if calibration.find('p1') is not None and calibration.find('p1').text else 0
p2 = float(calibration.find('p2').text) if calibration.find('p2') is not None and calibration.find('p2').text else 0
b1 = float(calibration.find('b1').text) if calibration.find('b1') is not None and calibration.find('b1').text else 0
b2 = float(calibration.find('b2').text) if calibration.find('b2') is not None and calibration.find('b2').text else 0
import numpy as np
import xml.etree.ElementTree as ET
from pycocotools.coco import COCO
import cv2
import open3d as o3d
from numpy.linalg import inv
import math
# Function to read camera transformations from XML
def read_camera_transforms(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
camera_info = []
for camera in root.iter('camera'):
camera_id = camera.attrib.get('id')
sensor_id = camera.attrib.get('sensor_id', 'default')
label = camera.attrib.get('label', 'No Label')
transform_text = camera.find('transform').text if camera.find('transform') is not None else "N/A"
camera_info.append({
'camera_id': camera_id,
'label': label,
'sensor_id': sensor_id,
'transform': transform_text
})
return camera_info
# Function to read camera calibrations from XML
def read_camera_calibrations(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
sensor_calibrations = {}
for calibration in root.iter('calibration'):
try:
f = float(calibration.find('f').text) if calibration.find('f') is not None and calibration.find('f').text else 0
cx = float(calibration.find('cx').text) if calibration.find('cx') is not None and calibration.find('cx').text else 0
cy = float(calibration.find('cy').text) if calibration.find('cy') is not None and calibration.find('cy').text else 0
k1 = float(calibration.find('k1').text) if calibration.find('k1') is not None and calibration.find('k1').text else 0
k2 = float(calibration.find('k2').text) if calibration.find('k2') is not None and calibration.find('k2').text else 0
k3 = float(calibration.find('k3').text) if calibration.find('k3') is not None and calibration.find('k3').text else 0
k4 = float(calibration.find('k4').text) if calibration.find('k4') is not None and calibration.find('k4').text else 0
p1 = float(calibration.find('p1').text) if calibration.find('p1') is not None and calibration.find('p1').text else 0
p2 = float(calibration.find('p2').text) if calibration.find('p2') is not None and calibration.find('p2').text else 0
b1 = float(calibration.find('b1').text) if calibration.find('b1') is not None and calibration.find('b1').text else 0
b2 = float(calibration.find('b2').text) if calibration.find('b2') is not None and calibration.find('b2').text else 0
sensor_calibrations = {
'f': f,
'cx': cx,
'cy': cy,
'k1': k1,
'k2': k2,
'k3': k3,
'k4': k4,
'p1': p1,
'p2': p2,
'b1': b1,
'b2': b2
}
print(f"Camera calibrations loaded successfully: {sensor_calibrations}")
except Exception as e:
print(f"Error processing calibration data: {e}")
sensor_calibrations = {}
if not sensor_calibrations:
print("Warning: No valid camera calibrations found.")
return sensor_calibrations
# Function to generate mask for given image
def generate_mask(coco, img_info, anns_class, anns_maskbound):
img_width, img_height = img_info['width'], img_info['height']
mask = np.zeros((img_height, img_width), dtype=np.uint8)
class_priority = {'Wall': 1, 'Window': 2}
class_index = {'Wall': 1, 'Window': 2}
anns_combined = list(zip(anns_class, anns_maskbound))
filtered_anns = [(cls, boundaries) for cls, boundaries in anns_combined if cls in class_priority]
anns_sorted = sorted(filtered_anns, key=lambda x: class_priority[x[0]])
for cls, boundaries in anns_sorted:
for boundary in boundaries:
pts = np.array(boundary, np.int32).reshape((-1, 1, 2))
cv2.fillPoly(mask, [pts], class_index[cls])
return mask
# Function to calculate the intersection of a line with the plane
def calculate_intersection(ray_origin, ray_direction, plane_normal, plane_point):
ray_direction /= np.linalg.norm(ray_direction)
plane_normal /= np.linalg.norm(plane_normal)
d = np.dot(plane_normal, plane_point)
t = (d - np.dot(plane_normal, ray_origin)) / np.dot(plane_normal, ray_direction)
intersection_point = ray_origin + t * ray_direction
return intersection_point
# Function to process each image and generate new point cloud
def process_each_image(img_info, coco, camera_info, camera_para, origin_point, point_cloud):
img_id = img_info['id']
img_name = img_info['file_name']
img_height = img_info['height']
img_width = img_info['width']
annIds = coco.getAnnIds(imgIds=img_id, iscrowd=None)
anns = coco.loadAnns(annIds)
anns_class = [coco.loadCats(ann['category_id'])[0]['name'] for ann in anns]
anns_maskbound = [ann['segmentation'] for ann in anns]
mask = generate_mask(coco, img_info, anns_class, anns_maskbound)
for v in range(img_height):
for u in range(img_width):
if mask[v, u] == 1: # If the pixel belongs to wall
# Normalized device coordinate
x_ndc = (u - camera_para['cx']) / camera_para['f']
y_ndc = (v - camera_para['cy']) / camera_para['f']
z_ndc = 1 # Assume depth is 1
# Calculate ray direction in world space
pixel_coords = np.array([x_ndc, y_ndc, z_ndc, 1.0]) # Homogeneous coordinate
for cam in camera_info:
if cam['label'] == img_name.split('.')[0]:
transform_list = list(map(float, cam['transform'].split()))
transform_matrix = np.array(transform_list).reshape(4, 4)
pixel_coords_world = inv(transform_matrix) @ pixel_coords
ray_direction = pixel_coords_world[:3] / np.linalg.norm(pixel_coords_world[:3])
break
# Calculate intersection with the plane
plane_normal = np.array([0.793553, -0.040436, 0.607156])
plane_point = np.array([0, 0, 2.950997 / 0.607156])
intersection_point = calculate_intersection(origin_point, ray_direction, plane_normal, plane_point)
# Append the intersection point to the new point cloud
point_cloud.append(intersection_point)
return point_cloud
def main():
# Initialize COCO API
annotation_file = './all_objects1.json'
coco = COCO(annotation_file)
# Read camera information
file_path = './camera2.xml'
camera_info = read_camera_transforms(file_path)
camera_para = read_camera_calibrations(file_path)
# Set a known point as the camera origin
origin_point = np.array([0, 0, 0]) # This should be calculated using camera extrinsics
# Read the point cloud
original_point_cloud = o3d.io.read_point_cloud('./room3.ply')
original_points = np.asarray(original_point_cloud.points)
# Combine new points with the original point cloud
new_points = []
imgIds = coco.getImgIds()
for img_id in imgIds:
img_info = coco.loadImgs(img_id)[0]
new_points = process_each_image(img_info, coco, camera_info, camera_para, origin_point, new_points)
# Create new point cloud from both original and new points
combined_points = np.vstack((original_points, new_points))
new_cloud = o3d.geometry.PointCloud()
new_cloud.points = o3d.utility.Vector3dVector(combined_points)
# Visualize the point cloud
o3d.visualization.draw_geometries([new_cloud])
if __name__ == "__main__":
main()