{"id":19784473,"url":"https://github.com/pdal/python","last_synced_at":"2025-04-08T09:13:20.010Z","repository":{"id":39737682,"uuid":"125232078","full_name":"PDAL/python","owner":"PDAL","description":"PDAL's Python Support","archived":false,"fork":false,"pushed_at":"2024-12-17T20:51:10.000Z","size":1332,"stargazers_count":125,"open_issues_count":9,"forks_count":37,"subscribers_count":12,"default_branch":"main","last_synced_at":"2025-04-01T08:42:09.124Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PDAL.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGES.txt","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-03-14T15:13:38.000Z","updated_at":"2025-03-28T17:27:17.000Z","dependencies_parsed_at":"2024-01-03T02:42:11.675Z","dependency_job_id":"caaa44cd-38e1-4e72-bb8b-fa622c2a01ae","html_url":"https://github.com/PDAL/python","commit_stats":null,"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PDAL%2Fpython","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PDAL%2Fpython/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PDAL%2Fpython/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PDAL%2Fpython/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PDAL","download_url":"https://codeload.github.com/PDAL/python/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247809964,"owners_count":20999816,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-12T06:11:36.466Z","updated_at":"2025-04-08T09:13:19.991Z","avatar_url":"https://github.com/PDAL.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"================================================================================\nPDAL\n================================================================================\n\nPDAL Python support allows you to process data with PDAL into `Numpy`_ arrays.\nIt provides a PDAL extension module to control Python interaction with PDAL.\nAdditionally, you can use it to fetch `schema`_ and `metadata`_ from PDAL operations.\n\nInstallation\n--------------------------------------------------------------------------------\n\n**Note** The PDAL Python bindings require the PDAL base library installed. Source code can be found at https://pdal.io and `GitHub \u003chttps://github.com/PDAL/PDAL\u003e`__.\n\nPyPI\n................................................................................\n\nPDAL Python support is installable via PyPI:\n\n.. code-block::\n\n    pip install PDAL\n\n\nDevelopers can control many settings including debug builds and where the libraries are installed\nusing `scikit-build-core \u003chttps://scikit-build-core.readthedocs.io\u003e`_ settings:\n\n.. code-block::\n\n    python -m pip install \\\n        -Cbuild-dir=build \\\n        -e \\\n        . \\\n        --config-settings=cmake.build-type=\"Debug\" \\\n        -vv \\\n        --no-deps \\\n        --no-build-isolation\n\nGitHub\n................................................................................\n\nThe repository for PDAL's Python extension is available at https://github.com/PDAL/python\n\nPython support released independently from PDAL itself as of PDAL 1.7.\n\nUsage\n--------------------------------------------------------------------------------\n\nSimple\n................................................................................\n\nGiven the following pipeline, which simply reads an `ASPRS LAS`_ file and\nsorts it by the ``X`` dimension:\n\n.. _`ASPRS LAS`: https://www.asprs.org/committee-general/laser-las-file-format-exchange-activities.html\n\n.. code-block:: python\n\n\n    json = \"\"\"\n    {\n      \"pipeline\": [\n        \"1.2-with-color.las\",\n        {\n            \"type\": \"filters.sort\",\n            \"dimension\": \"X\"\n        }\n      ]\n    }\"\"\"\n\n    import pdal\n    pipeline = pdal.Pipeline(json)\n    count = pipeline.execute()\n    arrays = pipeline.arrays\n    metadata = pipeline.metadata\n    log = pipeline.log\n\nProgrammatic Pipeline Construction\n................................................................................\n\nThe previous example specified the pipeline as a JSON string. Alternatively, a\npipeline can be constructed by creating ``Stage`` instances and piping them\ntogether. For example, the previous pipeline can be specified as:\n\n.. code-block:: python\n\n    pipeline = pdal.Reader(\"1.2-with-color.las\") | pdal.Filter.sort(dimension=\"X\")\n\nStage Objects\n=============\n\n- A stage is an instance of ``pdal.Reader``, ``pdal.Filter`` or ``pdal.Writer``.\n- A stage can be instantiated by passing as keyword arguments the options\n  applicable to the respective PDAL stage. For more on PDAL stages and their\n  options, check the PDAL documentation on `Stage Objects \u003chttps://pdal.io/pipeline.html#stage-objects\u003e`__.\n\n  - The ``filename`` option of ``Readers`` and ``Writers`` as well as the ``type``\n    option of ``Filters`` can be passed positionally as the first argument.\n  - The ``inputs`` option specifies a sequence of stages to be set as input to the\n    current stage. Each input can be either the string tag of another stage, or\n    the ``Stage`` instance itself.\n- The ``Reader``, ``Filter`` and ``Writer`` classes come with static methods for\n  all the respective PDAL drivers. For example, ``pdal.Filter.head()`` is a\n  shortcut for ``pdal.Filter(type=\"filters.head\")``. These methods are\n  auto-generated by introspecting ``pdal`` and the available options are\n  included in each method's docstring:\n\n.. code-block::\n\n    \u003e\u003e\u003e help(pdal.Filter.head)\n    Help on function head in module pdal.pipeline:\n\n    head(**kwargs)\n        Return N points from beginning of the point cloud.\n\n        user_data: User JSON\n        log: Debug output filename\n        option_file: File from which to read additional options\n        where: Expression describing points to be passed to this filter\n        where_merge='auto': If 'where' option is set, describes how skipped points should be merged with kept points in standard mode.\n        count='10': Number of points to return from beginning.  If 'invert' is true, number of points to drop from the beginning.\n        invert='false': If true, 'count' specifies the number of points to skip from the beginning.\n\nPipeline Objects\n================\n\nA ``pdal.Pipeline`` instance can be created from:\n\n- a JSON string: ``Pipeline(json_string)``\n- a sequence of ``Stage`` instances: ``Pipeline([stage1, stage2])``\n- a single ``Stage`` with the ``Stage.pipeline`` method: ``stage.pipeline()``\n- nothing: ``Pipeline()`` creates a pipeline with no stages.\n- joining ``Stage`` and/or other ``Pipeline`` instances together with the pipe\n  operator (``|``):\n\n  - ``stage1 | stage2``\n  - ``stage1 | pipeline1``\n  - ``pipeline1 | stage1``\n  - ``pipeline1 | pipeline2``\n\nEvery application of the pipe operator creates a new ``Pipeline`` instance. To\nupdate an existing ``Pipeline`` use the respective in-place pipe operator (``|=``):\n\n.. code-block:: python\n\n    # update pipeline in-place\n    pipeline = pdal.Pipeline()\n    pipeline |= stage\n    pipeline |= pipeline2\n\nReading using Numpy Arrays\n................................................................................\n\nThe following more complex scenario demonstrates the full cycling between\nPDAL and Python:\n\n* Read a small testfile from GitHub into a Numpy array\n* Filters the array with Numpy for Intensity\n* Pass the filtered array to PDAL to be filtered again\n* Write the final filtered array to a LAS file and a TileDB_ array\n  via the `TileDB-PDAL integration`_ using the `TileDB writer plugin`_\n\n.. code-block:: python\n\n    import pdal\n\n    data = \"https://github.com/PDAL/PDAL/blob/master/test/data/las/1.2-with-color.las?raw=true\"\n\n    pipeline = pdal.Reader.las(filename=data).pipeline()\n    print(pipeline.execute())  # 1065 points\n\n    # Get the data from the first array\n    # [array([(637012.24, 849028.31, 431.66, 143, 1,\n    # 1, 1, 0, 1,  -9., 132, 7326, 245380.78254963,  68,  77,  88),\n    # dtype=[('X', '\u003cf8'), ('Y', '\u003cf8'), ('Z', '\u003cf8'), ('Intensity', '\u003cu2'),\n    # ('ReturnNumber', 'u1'), ('NumberOfReturns', 'u1'), ('ScanDirectionFlag', 'u1'),\n    # ('EdgeOfFlightLine', 'u1'), ('Classification', 'u1'), ('ScanAngleRank', '\u003cf4'),\n    # ('UserData', 'u1'), ('PointSourceId', '\u003cu2'),\n    # ('GpsTime', '\u003cf8'), ('Red', '\u003cu2'), ('Green', '\u003cu2'), ('Blue', '\u003cu2')])\n    arr = pipeline.arrays[0]\n\n    # Filter out entries that have intensity \u003c 50\n    intensity = arr[arr[\"Intensity\"] \u003e 30]\n    print(len(intensity))  # 704 points\n\n    # Now use pdal to clamp points that have intensity 100 \u003c= v \u003c 300\n    pipeline = pdal.Filter.expression(expression=\"Intensity \u003e= 100 \u0026\u0026 Intensity \u003c 300\").pipeline(intensity)\n    print(pipeline.execute())  # 387 points\n    clamped = pipeline.arrays[0]\n\n    # Write our intensity data to a LAS file and a TileDB array. For TileDB it is\n    # recommended to use Hilbert ordering by default with geospatial point cloud data,\n    # which requires specifying a domain extent. This can be determined automatically\n    # from a stats filter that computes statistics about each dimension (min, max, etc.).\n    pipeline = pdal.Writer.las(\n        filename=\"clamped.las\",\n        offset_x=\"auto\",\n        offset_y=\"auto\",\n        offset_z=\"auto\",\n        scale_x=0.01,\n        scale_y=0.01,\n        scale_z=0.01,\n    ).pipeline(clamped)\n    pipeline |= pdal.Filter.stats() | pdal.Writer.tiledb(array_name=\"clamped\")\n    print(pipeline.execute())  # 387 points\n\n    # Dump the TileDB array schema\n    import tiledb\n    with tiledb.open(\"clamped\") as a:\n        print(a.schema)\n\nReading using Numpy Arrays as buffers (advanced)\n................................................................................\n\nIt's also possible to treat the Numpy arrays passed to PDAL as buffers that are iteratively populated through\ncustom python functions during the execution of the pipeline.\n\nThis may be useful in cases where you want the reading of the input data to be handled in a streamable fashion,\nlike for example:\n\n* When the total Numpy array data wouldn't fit into memory.\n* To initiate execution of a streamable PDAL pipeline while the input data is still being read.\n\nTo enable this mode, you just need to include the python populate function along with each corresponding Numpy array.\n\n.. code-block:: python\n\n    # Numpy array to be used as buffer\n    in_buffer = np.zeros(max_chunk_size, dtype=[(\"X\", float), (\"Y\", float), (\"Z\", float)])\n\n    # The function to populate the buffer iteratively\n    def load_next_chunk() -\u003e int:\n    \"\"\"\n    Function called by PDAL before reading the data from the buffer.\n\n    IMPORTANT: must return the total number of items to be read from the buffer.\n    The Pipeline execution will keep calling this function in a loop until 0 is returned.\n    \"\"\"\n        #\n        # Replace here with your code that populates the buffer and returns the number of elements to read\n        #\n        chunk_size = next_chunk.size\n        in_buffer[:chunk_size][\"X\"] = next_chunk[:][\"X\"]\n        in_buffer[:chunk_size][\"Y\"] = next_chunk[:][\"Y\"]\n        in_buffer[:chunk_size][\"Z\"] = next_chunk[:][\"Z\"]\n\n        return chunk_size\n\n    # Configure input array and handler during Pipeline initialization...\n    p = pdal.Pipeline(pipeline_json, arrays=[in_buffer], stream_handlers=[load_next_chunk])\n\n    # ...alternatively you can use the setter on an existing Pipeline\n    # p.inputs = [(in_buffer, load_next_chunk)]\n\nThe following snippet provides a simple example of how to use a Numpy array as buffer to support writing through PDAL\nwith total control over the maximum amount of memory to use.\n\n.. raw:: html\n\n   \u003cdetails\u003e\n   \u003csummary\u003eExample: Streaming the read and write of a very large LAZ file with low memory footprint\u003c/summary\u003e\n\n.. code-block:: python\n\n    import numpy as np\n    import pdal\n\n    in_chunk_size = 10_000_000\n    in_pipeline = pdal.Reader.las(**{\n        \"filename\": \"in_test.laz\"\n    }).pipeline()\n\n    in_pipeline_it = in_pipeline.iterator(in_chunk_size).__iter__()\n\n    out_chunk_size = 50_000_000\n    out_file = \"out_test.laz\"\n    out_pipeline = pdal.Writer.las(\n        filename=out_file\n    ).pipeline()\n\n    out_buffer = np.zeros(in_chunk_size, dtype=[(\"X\", float), (\"Y\", float), (\"Z\", float)])\n\n    def load_next_chunk():\n        try:\n            next_chunk = next(in_pipeline_it)\n        except StopIteration:\n            # Stops the streaming\n            return 0\n\n        chunk_size = next_chunk.size\n        out_buffer[:chunk_size][\"X\"] = next_chunk[:][\"X\"]\n        out_buffer[:chunk_size][\"Y\"] = next_chunk[:][\"Y\"]\n        out_buffer[:chunk_size][\"Z\"] = next_chunk[:][\"Z\"]\n\n        print(f\"Loaded next chunk -\u003e {chunk_size}\")\n\n        return chunk_size\n\n    out_pipeline.inputs = [(out_buffer, load_next_chunk)]\n\n    out_pipeline.loglevel = 20 # INFO\n    count = out_pipeline.execute_streaming(out_chunk_size)\n\n    print(f\"\\nWROTE - {count}\")\n\n.. raw:: html\n\n   \u003c/details\u003e\n\nExecuting Streamable Pipelines\n................................................................................\nStreamable pipelines (pipelines that consist exclusively of streamable PDAL\nstages) can be executed in streaming mode via ``Pipeline.iterator()``. This\nreturns an iterator object that yields Numpy arrays of up to ``chunk_size`` size\n(default=10000) at a time.\n\n.. code-block:: python\n\n    import pdal\n    pipeline = pdal.Reader(\"test/data/autzen-utm.las\") | pdal.Filter.expression(expression=\"Intensity \u003e 80 \u0026\u0026 Intensity \u003c 120)\")\n    for array in pipeline.iterator(chunk_size=500):\n        print(len(array))\n    # or to concatenate all arrays into one\n    # full_array = np.concatenate(list(pipeline))\n\n``Pipeline.iterator()`` also takes an optional ``prefetch`` parameter (default=0)\nto allow prefetching up to to this number of arrays in parallel and buffering\nthem until they are yielded to the caller.\n\nIf you just want to execute a streamable pipeline in streaming mode and don't\nneed to access the data points (typically when the pipeline has Writer stage(s)),\nyou can use the ``Pipeline.execute_streaming(chunk_size)`` method instead. This\nis functionally equivalent to ``sum(map(len, pipeline.iterator(chunk_size)))``\nbut more efficient as it avoids allocating and filling any arrays in memory.\n\nAccessing Mesh Data\n................................................................................\n\nSome PDAL stages (for instance ``filters.delaunay``) create TIN type mesh data.\n\nThis data can be accessed in Python using the ``Pipeline.meshes`` property, which returns a ``numpy.ndarray``\nof shape (1,n) where n is the number of Triangles in the mesh.\n\nIf the PointView contains no mesh data, then n = 0.\n\nEach Triangle is a tuple ``(A,B,C)`` where A, B and C are indices into the PointView identifying the point that is the vertex for the Triangle.\n\nMeshio Integration\n................................................................................\n\nThe meshes property provides the face data but is not easy to use as a mesh. Therefore, we have provided optional Integration\ninto the `Meshio \u003chttps://github.com/nschloe/meshio\u003e`__ library.\n\nThe ``pdal.Pipeline`` class provides the ``get_meshio(idx: int) -\u003e meshio.Mesh`` method. This\nmethod creates a `Mesh` object from the `PointView` array and mesh properties.\n\n.. note:: The meshio integration requires that meshio is installed (e.g. ``pip install meshio``). If it is not, then the method fails with an informative RuntimeError.\n\nSimple use of the functionality could be as follows:\n\n.. code-block:: python\n\n    import pdal\n\n    ...\n    pl = pdal.Pipeline(pipeline)\n    pl.execute()\n\n    mesh = pl.get_meshio(0)\n    mesh.write('test.obj')\n\nAdvanced Mesh Use Case\n................................................................................\n\nUSE-CASE : Take a LiDAR map, create a mesh from the ground points, split into tiles and store the tiles in PostGIS.\n\n.. note:: Like ``Pipeline.arrays``, ``Pipeline.meshes`` returns a list of ``numpy.ndarray`` to provide for the case where the output from a Pipeline is multiple PointViews\n\n(example using 1.2-with-color.las and not doing the ground classification for clarity)\n\n.. code-block:: python\n\n    import pdal\n    import psycopg2\n    import io\n\n    pl = (\n        pdal.Reader(\".../python/test/data/1.2-with-color.las\")\n        | pdal.Filter.splitter(length=1000)\n        | pdal.Filter.delaunay()\n    )\n    pl.execute()\n\n    conn = psycopg(%CONNNECTION_STRING%)\n    buffer = io.StringIO\n\n    for idx in range(len(pl.meshes)):\n        m =  pl.get_meshio(idx)\n        if m:\n            m.write(buffer,  file_format = \"wkt\")\n            with conn.cursor() as curr:\n              curr.execute(\n                  \"INSERT INTO %table-name% (mesh) VALUES (ST_GeomFromEWKT(%(ewkt)s)\",\n                  { \"ewkt\": buffer.getvalue()}\n              )\n\n    conn.commit()\n    conn.close()\n    buffer.close()\n\n\n\n.. _`Numpy`: http://www.numpy.org/\n.. _`schema`: http://www.pdal.io/dimensions.html\n.. _`metadata`: http://www.pdal.io/development/metadata.html\n.. _`TileDB`: https://tiledb.com/\n.. _`TileDB-PDAL integration`: https://docs.tiledb.com/geospatial/pdal\n.. _`TileDB writer plugin`: https://pdal.io/stages/writers.tiledb.html\n\n.. image:: https://github.com/PDAL/python/workflows/Build/badge.svg\n   :target: https://github.com/PDAL/python/actions?query=workflow%3ABuild\n\nRequirements\n================================================================================\n\n* PDAL 2.6+\n* Python \u003e=3.9\n* Pybind11 (eg :code:`pip install pybind11[global]`)\n* Numpy \u003e= 1.22 (eg :code:`pip install numpy`)\n* scikit-build-core (eg :code:`pip install scikit-build-core`)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpdal%2Fpython","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpdal%2Fpython","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpdal%2Fpython/lists"}