From 83fafaa30d2f51226533e83281e7f0966a81ae4c Mon Sep 17 00:00:00 2001 From: Valin Date: Wed, 20 Mar 2024 15:51:18 +0100 Subject: [PATCH] processing file to change point clouds to 2 classes, street lights and the rest. + addition of everything needed for the cookiecutter --- .flake8 | 28 ++++ .flake8_nb | 26 ++++ .github/workflows/flake_workflow.yml | 32 ++++ .gitignore | 221 +++++++++++++++++++++++++++ .pre-commit-config.yaml | 38 +++++ LICENSE | 206 +++++++++++++++++++++++++ README.md | 75 ++++++++- config.py | 1 + config_azure.py | 1 + environment.yml | 10 ++ src/preprocessing_sara_data.py | 135 ++++++++++++++++ 11 files changed, 772 insertions(+), 1 deletion(-) create mode 100644 .flake8 create mode 100644 .flake8_nb create mode 100644 .github/workflows/flake_workflow.yml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 LICENSE create mode 100644 config.py create mode 100644 config_azure.py create mode 100644 environment.yml create mode 100644 src/preprocessing_sara_data.py diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..259ade1 --- /dev/null +++ b/.flake8 @@ -0,0 +1,28 @@ +[flake8] +exclude = + .git, + .github, + .idea, + env/*, + venv/*, + __pycache__, + */.ipynb_checkpoints/* + +extend-ignore = + # D103 Missing docstring in public function + D103, + # D07 Missing docstring in __init__ + D107 + # D205 1 blank line required between summary line and description + D205, + # D400 First line should end with a period + D400, + # D401 First line should be in imperative mood + D401 + +# Example of excluding errors per file +#per-file-ignores = __init__.py:F401 + +max-complexity = 8 +max-line-length = 99 +statistics=True diff --git a/.flake8_nb b/.flake8_nb new file mode 100644 index 0000000..ce9c4c0 --- /dev/null +++ b/.flake8_nb @@ -0,0 +1,26 @@ +[flake8_nb] +exclude = + .git, + env/*, + venv/*, + __pycache__, + */.ipynb_checkpoints/* + *.py + +extend-ignore = + # D100 Missing docstring in public module + D100, + # D103 Missing docstring in public function + D103, + # D07 Missing docstring in __init__ + D107 + # D205 1 blank line required between summary line and description + D205, + # D400 First line should end with a period + D400, + # D401 First line should be in imperative mood + D401 + +max-complexity = 8 +max-line-length = 99 +statistics=True diff --git a/.github/workflows/flake_workflow.yml b/.github/workflows/flake_workflow.yml new file mode 100644 index 0000000..0077d0a --- /dev/null +++ b/.github/workflows/flake_workflow.yml @@ -0,0 +1,32 @@ +name: Install Python packages and flake all + +on: + push: + pull_request: + + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + python-version: [3.8, 3.9] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install flake8 flake8-bugbear flake8-comprehensions flake8-docstrings flake8-fixme mccabe pep8-naming + + - name: flake + run: | + flake8 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..483b22b --- /dev/null +++ b/.gitignore @@ -0,0 +1,221 @@ +# Adapt to your needs. This version includes typical data files we work with, along with the default python template. + +# Text / html +*.csv +*.txt +*.html + +# Geo data +*.gml +*.shp +*.cpg +*.dbf +*.shx +*.prj +*.gpkg +*.tfw +*.TIF +*.tif + +# Pointcloud data +*.laz +*.las +*.LAZ +*.ply + +# Images +*.png +*.jpg +*.bmp + +# Numpy compressed +*.npz + +# QGIS projects +*.qgz + +# Mac OS +*.DS_Store + + +### Default .gitignore for python ### +# see https://github.com/github/gitignore/blob/main/Python.gitignore + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# AzureML +*.amlignore +*.amltmp +*.ipynb_aml_checkpoints + +Data/ +test_results/ +log/jobs_outputs/ +wandb/ + +data/ + +/dataset/full_pc +/dataset/bb_pc +dataset/blend_files +dataset/dae +dataset/point_clouds diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ef73021 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,38 @@ +repos: + - repo: https://github.com/timothycrosley/isort + rev: 5.12.0 + hooks: + - id: isort + - repo: https://github.com/psf/black + rev: 23.3.0 + hooks: + - id: black + args: + - "--line-length=99" + - repo: https://github.com/s-weigand/flake8-nb + rev: v0.5.3 + hooks: + - id: flake8-nb + additional_dependencies: [ + 'flake8-bugbear', + 'flake8-comprehensions', + 'flake8-docstrings', + 'flake8-fixme', + 'mccabe', + 'pep8-naming', + ] + - repo: https://github.com/PYCQA/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + additional_dependencies: [ + 'flake8-bugbear==23.3.23', + 'flake8-comprehensions==3.12.0', + 'flake8-docstrings==1.7.0', + 'flake8-fixme==1.1.1', + 'flake8-string-format==0.3.0', + 'mccabe==0.7.0', + 'pep8-naming==0.13.3', + ] +default_language_version: + python: python3.9 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c1bfb05 --- /dev/null +++ b/LICENSE @@ -0,0 +1,206 @@ +Copyright © City of Amsterdam Licensed under the EUPL + + +EUROPEAN UNION PUBLIC LICENCE v. 1.2 +EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the +terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following +notice immediately following the copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions +In this Licence, the following terms have the following meaning: +— ‘The Licence’: this Licence. +— ‘The Original Work’: the work or software distributed or communicated by the Licensor under this Licence, available +as Source Code and also as Executable Code as the case may be. +— ‘Derivative Works’: the works or software that could be created by the Licensee, based upon the Original Work or +modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work +required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in +the country mentioned in Article 15. +— ‘The Work’: the Original Work or its Derivative Works. +— ‘The Source Code’: the human-readable form of the Work which is the most convenient for people to study and +modify. +— ‘The Executable Code’: any code which has generally been compiled and which is meant to be interpreted by +a computer as a program. +— ‘The Licensor’: the natural or legal person that distributes or communicates the Work under the Licence. +— ‘Contributor(s)’: any natural or legal person who modifies the Work under the Licence, or otherwise contributes to +the creation of a Derivative Work. +— ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of the Work under the terms of the +Licence. +— ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, renting, distributing, communicating, +transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential +functionalities at the disposal of any other natural or legal person. + +2. Scope of the rights granted by the Licence +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for +the duration of copyright vested in the Original Work: +— use the Work in any circumstance and for all usage, +— reproduce the Work, +— modify the Work, and make Derivative Works based upon the Work, +— communicate to the public, including the right to make available or display the Work or copies thereof to the public +and perform publicly, as the case may be, the Work, +— distribute the Work or copies thereof, +— lend and rent the Work or copies thereof, +— sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the +applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed +by law in order to make effective the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the +extent necessary to make use of the rights granted on the Work under this Licence. + +3. Communication of the Source Code +The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as +Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with +each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to +the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to +distribute or communicate the Work. + +4. Limitations on copyright +Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the +exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee +The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those +obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to +the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the +Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work +to carry prominent notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this +Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless +the Original Work is expressly distributed only under this version of the Licence — for example by communicating +‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the +Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both +the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done +under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed +in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide +a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available +for as long as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names +of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship +The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or +licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or +licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions to the Work, under the terms of this Licence. + +7. Disclaimer of Warranty +The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work +and may therefore contain defects or ‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind +concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or +errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this +Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. + +8. Disclaimer of Liability +Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be +liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the +Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss +of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However, +the Licensor will be liable under statutory product liability laws as far such laws apply to the Work. + +9. Additional agreements +While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services +consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window +displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms +and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You +by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution +or Communication by You of the Work or copies thereof. + +11. Information to the public +In case of any Distribution or Communication of the Work by means of electronic communication by You (for example, +by offering to download the Work from a remote location) the distribution channel or media (for example, a website) +must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence +and the way it may be accessible, concluded, stored and reproduced by the Licensee. + +12. Termination of the Licence +The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms +of the Licence. + +Such a termination will not terminate the licences of any person who has received the Work from the Licensee under +the Licence, provided such persons remain in full compliance with the Licence. + +13. Miscellaneous +Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the +Work. + +If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or +enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid +and enforceable. + +The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of +the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. +New versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take +advantage of the linguistic version of their choice. + +14. Jurisdiction +Without prejudice to specific agreement between parties, +— any litigation resulting from the interpretation of this License, arising between the European Union institutions, +bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice +of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union, +— any litigation arising between other parties and resulting from the interpretation of this License, will be subject to +the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. + +15. Applicable Law +Without prejudice to specific agreement between parties, +— this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat, +resides or has his registered office, +— this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside +a European Union Member State. + +Appendix +‘Compatible Licences’ according to Article 5 EUPL are: +— GNU General Public License (GPL) v. 2, v. 3 +— GNU Affero General Public License (AGPL) v. 3 +— Open Software License (OSL) v. 2.1, v. 3.0 +— Eclipse Public License (EPL) v. 1.0 +— CeCILL v. 2.0, v. 2.1 +— Mozilla Public Licence (MPL) v. 2 +— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software +— European Union Public Licence (EUPL) v. 1.1, v. 1.2 +— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+) + +— The European Commission may update this Appendix to later versions of the above licences without producing +a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the +covered Source Code from exclusive appropriation. +— All other changes or additions to this Appendix require the production of a new EUPL version. diff --git a/README.md b/README.md index 3631f7c..3f4143e 100644 --- a/README.md +++ b/README.md @@ -1 +1,74 @@ -# IID_Ilum_Mod \ No newline at end of file +# PC_BB: Pole Detection in Point Clouds +Welcome to the PC_BB repository! This project is part of an internship with the City of Amsterdam, with a primary goal of modelling light illumination in a 3D model of Amsterdam! + +## Getting Started with Python and Blender API + +### Installation of Blender Software +1. **Download Blender**: Visit [Blender's official website](https://www.blender.org/) and download Blender 4.0. + +### Configuring Blender in System Path +2. **Set Blender as a PATH variable**: + - Navigate to the Blender Foundation folder, typically located in "Program Files" or your chosen installation directory. + - Find the `blender.exe` executable, usually found at a path similar to `C://...//Blender Foundation\Blender 4.0`. + - Add this path to your system's PATH environment variable for easy access. + +### Collada File Preparation +3. **Download Collada Cube**: + - Visit [3D Amsterdam](https://3d.amsterdam.nl/) and download a Collada cube. + - Move the downloaded cube into the `dataset/dae` folder in your project directory. + +### Installing Pandas in Blender +4. **Integrate Pandas with Blender**: + - Launch Blender and navigate to the Scripting menu. + - Run the following script in the Python Console: + ```python + import sys + print(sys.executable) + ``` + - Open a command prompt or terminal. + - Use the Blender Python executable path obtained from the previous step to install Pandas: + ```bash + "C:\path\to\blender\python.exe" -m ensurepip + "C:\path\to\blender\python.exe" -m pip install pandas + "C:\path\to\blender\python.exe" -m pip install openpyxl + ``` + +### Running the Processing Script +5. **Execute Processing Script**: + - Now you can run the `blender_functions/processing_blender.py` script. + - Open a command prompt and run : + ```bash + blender --background --python blender_functions/processing_blender.py + ``` + - Ensure all dependencies and paths are correctly set for a smooth execution. + +## Getting Started with Intrinsic Image Decomposition on Point Cloud + +1. **Model Selection for Fine-Tuning** + - Begin by choosing a model to fine-tune from the `pretrained_models` folder. + - You can then fine-tune this model using three distinct loss functions, each controlled by its coefficient. + - Configure the training settings using the `train.py` script. Adjust the loss coefficients and other parameters according to your needs. Here's an example command to get started: + + ```bash + python train.py --include_loss_alb_smoothness True \ + --loss_alb_smoothness_coeff $loss_alb_coeff \ + --include_chroma_weights True \ + --include_loss_shading True --loss_shading_coeff $loss_shd_coeff \ + --include_loss_lid True --loss_lid_coeff $loss_lid_coeff \ + --lr 0.00000001 --wandb True --epochs 300 + ``` + +2. **Testing the Trained Model** + - Once training is complete, the model will be saved in the `pre_trained_models` directory. + - To test the model, use the `test.py` script. Make sure to specify the correct paths for the test point cloud and normal maps. + - Below is an example command for testing: + + ```bash + python test.py --path_to_model "$model_file" \ + --path_to_test_pc './Data/pcd/pcd_split_clean_0.5_test/' \ + --path_to_test_nm './Data/gts/nm_split_clean_0.5_test/' + ``` + + +## Acknowledgements +Special thanks to the City of Amsterdam for their support and collaboration in this internship project. diff --git a/config.py b/config.py new file mode 100644 index 0000000..845dd32 --- /dev/null +++ b/config.py @@ -0,0 +1 @@ +"""Paths when running locally""" diff --git a/config_azure.py b/config_azure.py new file mode 100644 index 0000000..8037a86 --- /dev/null +++ b/config_azure.py @@ -0,0 +1 @@ +"""Paths when running on Azure (AML)""" diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000..63491d0 --- /dev/null +++ b/environment.yml @@ -0,0 +1,10 @@ +# name: env-name +channels: + # - conda-forge + - defaults +dependencies: + # - python=3.9 + # - pip + # - pip: + # - laspy[lazrs]~=2.0 + # - open3d~=0.16.0 \ No newline at end of file diff --git a/src/preprocessing_sara_data.py b/src/preprocessing_sara_data.py new file mode 100644 index 0000000..d47f229 --- /dev/null +++ b/src/preprocessing_sara_data.py @@ -0,0 +1,135 @@ +import os +import numpy as np +import open3d as o3d +import laspy + +from pyntcloud import PyntCloud +from plyfile import PlyData, PlyElement + + +""" +Point Cloud Processing Toolkit + +This collection of Python functions is designed to facilitate the manipulation and processing of point cloud data, particularly in PLY format. Utilizing libraries such as `plyfile` and `numpy`, these functions offer a range of capabilities to work with point cloud files effectively. + +Key Features: + +1. Modification of Scalar Fields: + - `add_label_streetlight_to_ply(input_directory, output_directory)`: This function iterates through all PLY files in a given input directory. For each point cloud, it reads an existing scalar field named 'label'. Based on this field, it creates a new scalar field called 'label_streetlight'. The value of 'label_streetlight' is set to 2 if the original 'label' is 2, and 1 otherwise. The modified point clouds are saved in a specified output directory, preserving the original data structure and additional attributes. + +2. Conversion Between PLY and LAZ Formats: + - `ply_to_laz(directory, output_directory)`: This function allows the conversion of PLY files to the compressed LAZ format. It's particularly useful for reducing the size of point cloud files for storage or transmission. The function maintains the integrity of the original data, including custom scalar fields like 'label'. Converted files are stored in a separate output directory. + +Usage and Application: +These functions are ideal for scenarios where point cloud data needs to be preprocessed, such as adding new data fields based on existing ones or converting file formats for compatibility with different point cloud processing tools. They can be particularly useful in domains like 3D modeling, geographic information systems (GIS), and LiDAR data processing. + +Prerequisites: +- Python environment with packages `numpy`, `plyfile`, and `laspy` installed. +- Input PLY files should be structured correctly with necessary fields, especially for the `label` field required by some functions. +- Ensure you have read/write permissions for the specified directories. + +Example Usage: +# To add a new scalar field 'label_streetlight' to PLY files: +# add_label_streetlight_to_ply("path/to/input/ply_directory", "path/to/output/ply_directory") + +# To convert PLY files to LAZ format: +# ply_to_laz("path/to/input/ply_directory", "path/to/output/laz_directory") + +Note: +This toolkit is designed for batch processing of files within directories. It is advisable to backup your data before performing batch operations. The toolkit is easily extendable for more custom point cloud processing functionalities. +""" + + +def delete_files_without_label_2(directory): + """ + Delete all PLY files in a specified directory that do not have label 2. + + This function iterates over all files in the provided directory. For each file, + if it is a PLY file and does not have the label '2.000000', it will be deleted. + + Parameters: + directory (str): The path to the directory where the PLY files are located. + + Returns: + None + + Note: This function depends on a helper function 'has_label_2' to check for the label. + Ensure that 'has_label_2' is defined and correctly implemented. + """ + for filename in os.listdir(directory): + # Check if the file is a PLY file + if filename.endswith('.ply'): + file_path = os.path.join(directory, filename) + + # Check for label 2 and delete the file if it doesn't have it + if not has_label_2(file_path): + os.remove(file_path) + print(f"Deleted {file_path}") + +def has_label_2(file_path): + """ + Check if a PLY file contains any point with the label 2.000000. + + This function reads the PLY file located at the given file path. It then checks + if there is a 'label' field in the vertex data of the PLY file. If the 'label' field + exists, the function checks whether any of the points in the file have a label + value of 2.000000. + + Parameters: + file_path (str): The path to the PLY file. + + Returns: + bool: True if any point in the PLY file has label 2.000000, False otherwise. + + Note: This function relies on the 'plyfile' module for reading PLY files. + Ensure that 'plyfile' is installed and imported. + """ + ply_data = PlyData.read(file_path) + + # Check if 'label' field exists in the vertex data + if 'label' in ply_data['vertex'].data.dtype.names: + labels = ply_data['vertex']['label'] + return any(label == 2.000000 for label in labels) + else: + return False + +def add_label_streetlight_to_ply(input_directory, output_directory): + """ + Add a new scalar field 'label_streetlight' to each PLY file in the input directory and save + the modified files in the output directory. For each point in the point cloud, 'label_streetlight' + is set to 1 if 'label' is not 2, and set to 2 if 'label' is 2. + + Parameters: + input_directory (str): The path to the directory containing the original PLY files. + output_directory (str): The path to the directory where modified files will be saved. + + Returns: + None + """ + # Create the output directory if it doesn't exist + if not os.path.exists(output_directory): + os.makedirs(output_directory) + + for filename in os.listdir(input_directory): + if filename.endswith('.ply'): + input_file_path = os.path.join(input_directory, filename) + output_file_path = os.path.join(output_directory, filename) + ply_data = PlyData.read(input_file_path) + + if 'label' in ply_data['vertex'].data.dtype.names: + labels = ply_data['vertex']['label'] + label_streetlight = np.array([2 if label == 2 else 1 for label in labels], dtype=np.int32) + new_dtype = ply_data['vertex'].data.dtype.descr + [('label_streetlight', 'i4')] + new_data = np.empty(ply_data['vertex'].count, dtype=new_dtype) + for prop in ply_data['vertex'].data.dtype.names: + new_data[prop] = ply_data['vertex'][prop] + new_data['label_streetlight'] = label_streetlight + new_vertex = PlyElement.describe(new_data, 'vertex') + new_ply_data = PlyData([new_vertex], text=ply_data.text) + new_ply_data.write(output_file_path) + print(f"Updated {input_file_path} and saved as {output_file_path}") + +if __name__ == "__main__": + poles_path = "data/pole_data/poles_ply" + poles_path_modified = "data/pole_data/poles_modified_ply" + add_label_streetlight_to_ply(poles_path, poles_path_modified)