Loading files
976d2b9ddThis file is pinned to the selected release. Download the original to open it in your design tool.
#!/usr/bin/env python3
import argparse
import yaml
import numpy as np
import cv2
from plyfile import PlyData
from PIL import Image
import sys
def inpaint_black_pixels(img, radius):
# Kernel for inpainting
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2 * radius + 1, 2 * radius + 1))
# Blur the og image
valid_mask = np.any(img != 0, axis=2).astype(np.uint8)
sum_img = cv2.filter2D(
img.astype(np.float32), -1, kernel, borderType=cv2.BORDER_CONSTANT
)
valid_counts = cv2.filter2D(
valid_mask.astype(np.float32), -1, kernel, borderType=cv2.BORDER_CONSTANT
)
blurred_img = sum_img / np.maximum(valid_counts[:, :, np.newaxis], 1)
# Replace the black pixels with the inpainted pixels
img[valid_mask == 0] = blurred_img[valid_mask == 0]
return img
def main():
# Parse command line arguments
parser = argparse.ArgumentParser(
description="Rasterize point cloud to top-view image"
)
parser.add_argument("--ply", required=True, help="Input PLY file")
parser.add_argument("--yaml", required=True, help="Input YAML configuration")
parser.add_argument("--out", required=True, help="Output image path")
parser.add_argument(
"--scale", type=float, default=1.0, help="Scale-up output image"
)
parser.add_argument(
"--fill-holes", type=int, default=0, help="Radius for hole filling"
)
parser.add_argument(
"--depth", action="store_true", help="Store depth in alpha channel"
)
args = parser.parse_args()
print("Loading configuration...", file=sys.stderr)
# Load YAML configuration
with open(args.yaml, "r") as f:
config = yaml.safe_load(f)
# Apply scaling factor
config["width_px"] = int(config["width_px"] * args.scale)
config["height_px"] = int(config["height_px"] * args.scale)
config["origin_px"] = [
int(config["origin_px"][0] * args.scale),
int(config["origin_px"][1] * args.scale),
]
print("Loading point cloud...", file=sys.stderr)
# Load PLY file
plydata = PlyData.read(args.ply)
vertex = plydata["vertex"]
points = np.vstack([vertex["x"], vertex["y"], vertex["z"]]).T
colors = np.vstack([vertex["red"], vertex["green"], vertex["blue"]]).T
print(f"Loaded {len(points)} points", file=sys.stderr)
# Calculate height range for alpha channel
min_height = np.min(points[:, 2])
max_height = np.max(points[:, 2])
height_range = max_height - min_height
# Create output image
if args.depth:
img = np.zeros((config["height_px"], config["width_px"], 4), dtype=np.uint8)
else:
img = np.zeros((config["height_px"], config["width_px"], 3), dtype=np.uint8)
# Convert points to image coordinates
img_points = np.zeros_like(points)
scale = config["width_px"] / config["width_m"]
img_points[:, 0] = config["origin_px"][1] - points[:, 0] * scale
img_points[:, 1] = config["origin_px"][0] - points[:, 1] * scale
img_points = img_points.astype(np.int32)
print("Filtering points...", file=sys.stderr)
# Filter points within image bounds
mask = (
(img_points[:, 0] >= 0)
& (img_points[:, 0] < config["height_px"])
& (img_points[:, 1] >= 0)
& (img_points[:, 1] < config["width_px"])
)
img_points = img_points[mask]
colors = colors[mask]
heights = points[mask, 2]
print(f"Binning {len(img_points)} points...", file=sys.stderr)
# Create accumulation arrays for colors and heights
color_sums = np.zeros(
(config["height_px"], config["width_px"], 3), dtype=np.float32
)
height_maxes = np.zeros((config["height_px"], config["width_px"]), dtype=np.float32)
point_counts = np.zeros((config["height_px"], config["width_px"]), dtype=np.int32)
# Accumulate colors and track maximum heights
for point, color, height in zip(img_points, colors, heights):
color_sums[point[0], point[1]] += color
height_maxes[point[0], point[1]] = max(height_maxes[point[0], point[1]], height)
point_counts[point[0], point[1]] += 1
# Avoid division by zero
mask = point_counts > 0
# Calculate average colors
img[mask, :3] = (color_sums[mask] / point_counts[mask, np.newaxis]).astype(np.uint8)
# Calculate alpha values (0-255) based on maximum height
height_range = max_height - min_height
alpha_channel = np.zeros((config["height_px"], config["width_px"]), dtype=np.uint8)
alpha_channel[mask] = (
(height_maxes[mask] - min_height) / height_range * 255
).astype(np.uint8)
if args.depth:
img[..., 3] = alpha_channel
# Fill holes in the output image
if args.fill_holes > 0:
print("Filling holes...", file=sys.stderr)
img = inpaint_black_pixels(img, radius=args.fill_holes)
print(f"Saving image to {args.out}...", file=sys.stderr)
# Save image
Image.fromarray(img).save(args.out)
print("Done!", file=sys.stderr)
if __name__ == "__main__":
main()