Examples

Filtering

This example shows how you can extract points from a file and write them into a new one. We use the classification field to filter points, but this can work with the other fields.

import laspy

las = laspy.read('tests/simple.las')

new_file = laspy.create(point_format=las.header.point_format_id, file_version=las.header.version)
new_file.points = las.points[las.classification == 1]

new_file.write('extracted_points.las')

Creating from scratch

This example shows how you can create a new LAS file from scratch.

import laspy
import numpy as np

my_data_xx, my_data_yy = np.meshgrid(np.linspace(-20, 20, 15), np.linspace(-20, 20, 15))
my_data_zz = my_data_xx ** 2 + 0.25 * my_data_yy ** 2

my_data = np.hstack((my_data_xx.reshape((-1, 1)), my_data_yy.reshape((-1, 1)), my_data_zz.reshape((-1, 1))))


las = laspy.create(file_version="1.2", point_format=3)

las.header.offsets = np.min(my_data, axis=0)
las.header.scales = [0.1, 0.1, 0.1]

las.x = my_data[:, 0]
las.y = my_data[:, 1]
las.z = my_data[:, 2]

las.write("new_file.las")

Using chunked reading & writing

This example shows how to use the ‘chunked’ reading and writing feature to split potentially large LAS/LAZ file into multiple smaller file.

import argparse
import sys
from pathlib import Path
from typing import List
from typing import Optional

import numpy as np

import laspy


def recursive_split(x_min, y_min, x_max, y_max, max_x_size, max_y_size):
    x_size = x_max - x_min
    y_size = y_max - y_min

    if x_size > max_x_size:
        left = recursive_split(x_min, y_min, x_min + (x_size // 2), y_max, max_x_size, max_y_size)
        right = recursive_split(x_min + (x_size // 2), y_min, x_max, y_max, max_x_size, max_y_size)
        return left + right
    elif y_size > max_y_size:
        up = recursive_split(x_min, y_min, x_max, y_min + (y_size // 2), max_x_size, max_y_size)
        down = recursive_split(x_min, y_min + (y_size // 2), x_max, y_max, max_x_size, max_y_size)
        return up + down
    else:
        return [(x_min, y_min, x_max, y_max)]


def tuple_size(string):
    try:
        return tuple(map(float, string.split("x")))
    except:
        raise ValueError("Size must be in the form of numberxnumber eg: 50.0x65.14")


def main():
    parser = argparse.ArgumentParser("LAS recursive splitter", description="Splits a las file bounds recursively")
    parser.add_argument("input_file")
    parser.add_argument("output_dir")
    parser.add_argument("size", type=tuple_size, help="eg: 50x64.17")
    parser.add_argument("--points-per-iter", default=10**6, type=int)

    args = parser.parse_args()

    with laspy.open(sys.argv[1]) as file:
        sub_bounds = recursive_split(
            file.header.x_min,
            file.header.y_min,
            file.header.x_max,
            file.header.y_max,
            args.size[0],
            args.size[1]
        )

        writers: List[Optional[laspy.LasWriter]] = [None] * len(sub_bounds)
        try:
            count = 0
            for points in file.chunk_iterator(args.points_per_iter):
                print(f"{count / file.header.point_count * 100}%")

                # For performance we need to use copy
                # so that the underlying arrays are contiguous
                x, y = points.x.copy(), points.y.copy()

                point_piped = 0

                for i, (x_min, y_min, x_max, y_max) in enumerate(sub_bounds):
                    mask = (x >= x_min) & (x <= x_max) & (y >= y_min) & (y <= y_max)

                    if np.any(mask):
                        if writers[i] is None:
                            output_path = Path(sys.argv[2]) / f"output_{i}.laz"
                            writers[i] = laspy.open(output_path,
                                                    mode='w',
                                                    header=file.header)
                        sub_points = points[mask]
                        writers[i].write_points(sub_points)

                    point_piped += np.sum(mask)
                    if point_piped == len(points):
                        break
                count += len(points)
            print(f"{count / file.header.point_count * 100}%")
        finally:
            for writer in writers:
                if writer is not None:
                    writer.close()


if __name__ == '__main__':
    main()