blkpst commited on
Commit
5055182
·
verified ·
1 Parent(s): 293b8d6

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+
210
+ # LLM
211
+ CLAUDE.md
212
+
213
+ # Ignore all JSON files for github repo due to size constraints
214
+ *.json
.hfignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local/dev files
2
+ .git/
3
+ .claude/
4
+ .gitignore
5
+ .gitkeep
6
+ CLAUDE.md
7
+ firebase-debug.log
8
+
9
+ # Empty placeholder files
10
+ data/raw/
11
+ data/images/
LICENSE ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0)
2
+
3
+ Copyright (c) 2025
4
+
5
+ This work is licensed under the Creative Commons Attribution-NonCommercial 4.0
6
+ International License.
7
+
8
+ You are free to:
9
+
10
+ Share - copy and redistribute the material in any medium or format
11
+ Adapt - remix, transform, and build upon the material
12
+
13
+ Under the following terms:
14
+
15
+ Attribution - You must give appropriate credit, provide a link to the license,
16
+ and indicate if changes were made. You may do so in any reasonable manner, but
17
+ not in any way that suggests the licensor endorses you or your use.
18
+
19
+ NonCommercial - You may not use the material for commercial purposes.
20
+
21
+ No additional restrictions - You may not apply legal terms or technological
22
+ measures that legally restrict others from doing anything the license permits.
23
+
24
+ Notices:
25
+
26
+ You do not have to comply with the license for elements of the material in the
27
+ public domain or where your use is permitted by an applicable exception or
28
+ limitation.
29
+
30
+ No warranties are given. The license may not give you all of the permissions
31
+ necessary for your intended use. For example, other rights such as publicity,
32
+ privacy, or moral rights may limit how you use the material.
33
+
34
+ For the full license text, see:
35
+ https://creativecommons.org/licenses/by-nc/4.0/legalcode
36
+
37
+ ---
38
+
39
+ Note: Original Chang'E-4 imagery is owned by China's Lunar and Planetary Data
40
+ System (CLPDS) / National Astronomical Observatories of China (NAOC) and is
41
+ subject to their usage terms. This license applies only to the segmentation
42
+ masks and code in this repository.
README.md CHANGED
@@ -1,3 +1,129 @@
1
- ---
2
- license: cc-by-nc-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ task_categories:
4
+ - image-segmentation
5
+ tags:
6
+ - lunar
7
+ - chang-e-4
8
+ - terrain-classification
9
+ - segmentation
10
+ - planetary-science
11
+ pretty_name: Chang'E-4 Terrain Classification Dataset
12
+ ---
13
+
14
+ # Chang'E-4 TCM Dataset
15
+
16
+ Tools and data for terrain classification using Chang'E-4 Yutu-2 rover imagery.
17
+
18
+ > **Note:** This repository contains only segmentation mask annotations. Original Chang'E-4 images are not included due to copyright restrictions. You must download the source images directly from CLPDS (see instructions below).
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ # Install dependencies
24
+ pip install -r requirements.txt
25
+
26
+ # Convert PDS files to images
27
+ python scripts/convert_pds.py data/raw data/images
28
+ ```
29
+
30
+ ## Downloading Chang'E-4 Data
31
+
32
+ Data is available from China's Lunar and Planetary Data System (CLPDS).
33
+
34
+ ### 1. Register an Account
35
+
36
+ 1. Go to https://clpds.bao.ac.cn
37
+ 2. Create an account (check spam folder for confirmation email from NAOC)
38
+
39
+ ### 2. Download Data
40
+
41
+ 1. Navigate to Chang'E-4 data search: https://clpds.bao.ac.cn/ce5web/searchOrder-ce4En.do
42
+ 2. Select an instrument:
43
+ - **PCAM** - Panoramic Camera (rover, stereo pairs)
44
+ - **TCAM** - Terrain Camera (lander)
45
+ - **LPR** - Lunar Penetrating Radar
46
+ - **VNIS** - Visible/Near-IR Spectrometer
47
+ 3. Choose data level (L2A or higher for calibrated data)
48
+ 4. Add files to cart and process order
49
+ 5. Download and extract to `data/raw/`
50
+
51
+ ### Data Format
52
+
53
+ Chang'E-4 uses PDS4 format:
54
+ - XML label file (`.xml`) - metadata
55
+ - Data file (`.img`, `*L`) - image data
56
+
57
+ ## Converting to Images
58
+
59
+ The conversion script applies debayering and contrast stretching:
60
+
61
+ ```bash
62
+ # Convert all PDS files in data/raw to PNG
63
+ python scripts/convert_pds.py data/raw data/images
64
+
65
+ # Preview files without converting
66
+ python scripts/convert_pds.py data/raw data/images --dry-run
67
+
68
+ # Flatten output to single directory
69
+ python scripts/convert_pds.py data/raw data/images --flat
70
+ ```
71
+
72
+ ### Processing Steps
73
+
74
+ 1. Read PDS4 file using `pds4_tools`
75
+ 2. Debayer raw Bayer images (PCAM full-resolution)
76
+ 3. Apply 2% linear contrast stretch
77
+ 4. Save as PNG
78
+
79
+ ## Project Structure
80
+
81
+ ```
82
+ ├── data/
83
+ │ ├── masks/ # Segmentation mask annotations (JSON)
84
+ │ ├── raw/ # Downloaded PDS4 files (you provide)
85
+ │ └── images/ # Converted PNG images (generated)
86
+ ├── docs/
87
+ │ └── chinese-moon-data-access.md
88
+ ├── scripts/
89
+ │ └── convert_pds.py
90
+ └── requirements.txt
91
+ ```
92
+
93
+ ## References
94
+
95
+ - [CLPDS Data Portal](https://clpds.bao.ac.cn)
96
+ - [Chang'E-4 Data Releases](https://moon.bao.ac.cn/pubMsg/detail-CE4EN.jsp)
97
+ - [CLPDS Overview Paper](https://link.springer.com/article/10.1007/s11214-021-00862-3)
98
+
99
+ ## Citation
100
+
101
+ If you use this dataset in your research, please cite:
102
+
103
+ ```bibtex
104
+ @misc{chang4tcm2025,
105
+ author = {Yu, Sam and Lastname, Firstname and },
106
+ title = {Chang'E-4 Terrain Classification Dataset},
107
+ year = {2026},
108
+ organization = {Lothan Space, },
109
+ publisher = {GitHub},
110
+ url = {https://github.com/siyu6974/change4-tcm-dataset}
111
+ }
112
+ ```
113
+
114
+ Please also cite the original data source:
115
+
116
+ ```bibtex
117
+ @misc{clpds2025,
118
+ author = {{Ground Research and Application System of China's Lunar and Planetary Exploration Program}},
119
+ title = {Chang'E-4 Scientific Data},
120
+ publisher = {China National Space Administration},
121
+ url = {https://moon.bao.ac.cn}
122
+ }
123
+ ```
124
+
125
+ ## License
126
+
127
+ The code and segmentation masks in this repository are licensed under [CC BY-NC 4.0](LICENSE) (Creative Commons Attribution-NonCommercial 4.0). You are free to use, share, and adapt for non-commercial purposes with attribution.
128
+
129
+ Original Chang'E-4 imagery is owned by CLPDS/NAOC and must be downloaded directly from their portal. See [docs/chinese-moon-data-access.md](docs/chinese-moon-data-access.md) for their citation requirements.
data/images/.gitkeep ADDED
File without changes
data/raw/.gitkeep ADDED
File without changes
data/raw/placeholder.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Original files here
docs/chinese-moon-data-access.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Accessing Chang'E-4 Rover Data
2
+
3
+ This guide explains how to access and download images and scientific data from China's Chang'E-4 mission and Yutu-2 rover.
4
+
5
+ ## Chang'E-4 Mission Overview
6
+
7
+ Chang'E-4 achieved humanity's first soft landing on the lunar far side on January 3, 2019, landing in the Von Kármán crater. The mission includes a lander and the Yutu-2 rover, which continues to operate and explore the lunar surface.
8
+
9
+ **Key Facts:**
10
+ - **Launch**: December 8, 2018
11
+ - **Landing**: January 3, 2019
12
+ - **Location**: Von Kármán crater, lunar far side
13
+ - **Rover**: Yutu-2 (玉兔二号)
14
+ - **Data Format**: PDS4
15
+
16
+ ## Chang'E-4 Instruments
17
+
18
+ | Instrument | Abbreviation | Description |
19
+ |------------|--------------|-------------|
20
+ | Landing Camera | LCAM | Descent imaging during landing |
21
+ | Terrain Camera | TCAM | Surface imaging from lander |
22
+ | Panoramic Camera | PCAM | 360° surface imaging from rover |
23
+ | Lunar Penetrating Radar | LPR | Subsurface structure detection |
24
+ | Visible and Near-Infrared Imaging Spectrometer | VNIS | Mineral composition analysis |
25
+ | Low Frequency Spectrometer | LFS | Radio astronomy observations |
26
+
27
+ ## Data Portal
28
+
29
+ **Primary access point for Chang'E-4 data:**
30
+
31
+ - **Chang'E-4 Data Search**: https://clpds.bao.ac.cn/ce5web/searchOrder-ce4En.do
32
+ - **Main Portal**: https://moon.bao.ac.cn/web/enmanager/home
33
+ - **Contact**: lpdc@nao.cas.cn
34
+
35
+ The data is hosted by **China's Lunar and Planetary Data System (CLPDS)**, operated by the National Astronomical Observatories of China (NAOC).
36
+
37
+ ## Registration Process
38
+
39
+ 1. **Navigate to the portal**: Go to https://clpds.bao.ac.cn
40
+ 2. **Create an account**: Click on the registration/login link
41
+ 3. **Fill in the registration form**: Provide required information
42
+ 4. **Download and submit registration form**: Some datasets require an additional form
43
+ 5. **Check your spam folder**: Confirmation emails from NAOC may be incorrectly encoded
44
+
45
+ ## Downloading Chang'E-4 Data
46
+
47
+ The download process works like online shopping:
48
+
49
+ 1. **Log in** to your account
50
+ 2. **Go to Chang'E-4 search**: https://clpds.bao.ac.cn/ce5web/searchOrder-ce4En.do
51
+ 3. **Select an instrument**: PCAM, TCAM, LPR, VNIS, etc.
52
+ 4. **Choose data level**: Typically Level 2A or higher for calibrated data
53
+ 5. **Set time range** (optional): Filter by lunar day or date range
54
+ 6. **Add to cart**: Select the data products you need
55
+ 7. **Process order**: Submit to initiate download
56
+
57
+ ## Data Processing Levels
58
+
59
+ | Level | Description | Availability |
60
+ |-------|-------------|--------------|
61
+ | L0 | Raw telemetry data | Not public |
62
+ | L1 | Depacketized, time-tagged | Not public |
63
+ | L2A | Calibrated, geolocated | Public |
64
+ | L2B | Mosaics and derived products | Public |
65
+ | L2C | Higher-level products | Public |
66
+
67
+ **Note:** Only calibrated L2+ data is publicly available. Raw L0/L1 telemetry remains proprietary.
68
+
69
+ ## PDS4 Data Format
70
+
71
+ Chang'E-4 data uses PDS4 format. Each data product consists of:
72
+
73
+ - **XML label file** (`.xml`): Metadata describing the observation
74
+ - **Data file**: Image or measurement data (format varies by instrument)
75
+
76
+ Common image formats include `.img` or `.fits` files paired with their XML labels.
77
+
78
+ ## Data Releases
79
+
80
+ Chang'E-4 data is released periodically in batches organized by lunar day. Check the data release announcements for the latest available data:
81
+
82
+ - [Chang'E-4 Data Release Announcements](https://moon.bao.ac.cn/pubMsg/detail-CE4EN.jsp)
83
+
84
+ ## Usage Requirements
85
+
86
+ 1. **Non-commercial use**: Data is for research and educational purposes
87
+ 2. **Citation required**: Acknowledge the data source in publications
88
+ 3. **Submit results**: Send publications to lpdc@nao.cas.cn
89
+
90
+ ### Suggested Citation
91
+
92
+ ```
93
+ Ground Research and Application System of China's Lunar and Planetary
94
+ Exploration Program. Chang'E-4 [Instrument] Data. China National Space
95
+ Administration, [Year]. https://moon.bao.ac.cn
96
+ ```
97
+
98
+ ## Troubleshooting
99
+
100
+ - **Service instability**: The portal may be slow for overseas users. Retry if needed.
101
+ - **Language**: Some pages are Chinese-only. Use browser translation.
102
+ - **JavaScript required**: The data portal requires JavaScript enabled.
103
+
104
+ ## Other Chang'E Missions
105
+
106
+ For context, other missions in the Chinese Lunar Exploration Program:
107
+
108
+ | Mission | Year | Description |
109
+ |---------|------|-------------|
110
+ | Chang'E-1 | 2007 | Lunar orbiter |
111
+ | Chang'E-2 | 2010 | Lunar orbiter, higher resolution |
112
+ | Chang'E-3 | 2013 | Near-side lander + Yutu rover |
113
+ | Chang'E-5 | 2020 | Sample return (1,731g) |
114
+ | Chang'E-6 | 2024 | Far-side sample return (1,935g) |
115
+
116
+ ## References
117
+
118
+ - [CLPDS Overview Paper (Space Science Reviews)](https://link.springer.com/article/10.1007/s11214-021-00862-3)
119
+ - [Planetary Society Guide to Downloading Chang'e Data](http://www.planetary.org/blogs/guest-blogs/2016/01221450-china-invites-public-on-board.html)
120
+ - [Chang'E-4 Data Release Announcement](https://moon.bao.ac.cn/pubMsg/detail-CE4EN.jsp)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ pds4-tools>=1.3
2
+ colour-demosaicing>=0.2
3
+ colour-science>=0.4
4
+ scikit-image>=0.21
5
+ Pillow>=10.0
6
+ numpy>=1.24
scripts/convert_pds.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert Chang'E-4 PDS4 image files to PNG format.
4
+
5
+ Usage:
6
+ python scripts/convert_pds.py data/raw data/images
7
+
8
+ This script reads PDS4 files from the input directory, applies debayering
9
+ and contrast stretching, then saves the results as PNG images.
10
+ """
11
+
12
+ import argparse
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ from PIL import Image
18
+ from pds4_tools import pds4_read
19
+ from skimage import exposure
20
+ from skimage.util import img_as_float
21
+ from colour_demosaicing import demosaicing_CFA_Bayer_Menon2007
22
+ import colour
23
+
24
+
25
+ def read_pds(path: Path) -> np.ndarray:
26
+ """Read a PDS4 image file and return as float array."""
27
+ data = pds4_read(str(path), quiet=True)
28
+ img = np.array(data[0].data)
29
+ return img_as_float(img)
30
+
31
+
32
+ def debayer(img: np.ndarray, pattern: str = "RGGB") -> np.ndarray:
33
+ """Convert Bayer pattern image to RGB."""
34
+ debayered = demosaicing_CFA_Bayer_Menon2007(img, pattern)
35
+ return colour.cctf_encoding(debayered)
36
+
37
+
38
+ def stretch(img: np.ndarray, percentile: float = 2.0) -> np.ndarray:
39
+ """Apply linear contrast stretch using percentile clipping."""
40
+ p_low, p_high = np.percentile(img, (percentile, 100 - percentile))
41
+ return exposure.rescale_intensity(img, in_range=(p_low, p_high))
42
+
43
+
44
+ def save_image(img: np.ndarray, path: Path) -> None:
45
+ """Save float image array as PNG."""
46
+ img_uint8 = np.uint8(np.clip(img, 0, 1) * 255)
47
+ Image.fromarray(img_uint8).save(path)
48
+
49
+
50
+ def convert_pds_file(input_path: Path, output_path: Path) -> bool:
51
+ """
52
+ Convert a single PDS file to PNG.
53
+
54
+ Returns True on success, False on failure.
55
+ """
56
+ try:
57
+ img = read_pds(input_path)
58
+
59
+ # PCAM full resolution images need debayering
60
+ # Dimensions: 1728x2352 for raw Bayer, 864x1176 for already processed
61
+ if img.shape == (1728, 2352):
62
+ img = debayer(img)
63
+ elif len(img.shape) == 2 and img.shape not in [(864, 1176)]:
64
+ # Unknown grayscale format, try debayering if dimensions suggest Bayer
65
+ if img.shape[0] > 500 and img.shape[1] > 500:
66
+ img = debayer(img)
67
+
68
+ img = stretch(img)
69
+ save_image(img, output_path)
70
+ return True
71
+
72
+ except Exception as e:
73
+ print(f"Error converting {input_path}: {e}", file=sys.stderr)
74
+ return False
75
+
76
+
77
+ def find_pds_files(directory: Path) -> list[Path]:
78
+ """Find all PDS4 image files in directory (recursively)."""
79
+ pds_files = []
80
+
81
+ # PDS4 data files typically end with these extensions
82
+ patterns = ["*.*L", "*.img", "*.IMG", "*.dat", "*.DAT"]
83
+
84
+ for pattern in patterns:
85
+ pds_files.extend(directory.rglob(pattern))
86
+
87
+ # Filter out XML label files
88
+ pds_files = [f for f in pds_files if not f.suffix.lower() == ".xml"]
89
+
90
+ return sorted(set(pds_files))
91
+
92
+
93
+ def main():
94
+ parser = argparse.ArgumentParser(
95
+ description="Convert Chang'E-4 PDS4 files to PNG images",
96
+ formatter_class=argparse.RawDescriptionHelpFormatter,
97
+ epilog="""
98
+ Examples:
99
+ python scripts/convert_pds.py data/raw data/images
100
+ python scripts/convert_pds.py ./PCAM ./output --flat
101
+ """,
102
+ )
103
+ parser.add_argument(
104
+ "input_dir",
105
+ type=Path,
106
+ help="Directory containing PDS4 files",
107
+ )
108
+ parser.add_argument(
109
+ "output_dir",
110
+ type=Path,
111
+ help="Directory for output PNG images",
112
+ )
113
+ parser.add_argument(
114
+ "--flat",
115
+ action="store_true",
116
+ help="Output all files to single directory (ignore subdirectory structure)",
117
+ )
118
+ parser.add_argument(
119
+ "--dry-run",
120
+ action="store_true",
121
+ help="List files that would be converted without converting",
122
+ )
123
+
124
+ args = parser.parse_args()
125
+
126
+ if not args.input_dir.exists():
127
+ print(f"Error: Input directory does not exist: {args.input_dir}", file=sys.stderr)
128
+ sys.exit(1)
129
+
130
+ pds_files = find_pds_files(args.input_dir)
131
+
132
+ if not pds_files:
133
+ print(f"No PDS files found in {args.input_dir}")
134
+ sys.exit(0)
135
+
136
+ print(f"Found {len(pds_files)} PDS files")
137
+
138
+ if args.dry_run:
139
+ for f in pds_files:
140
+ print(f" {f}")
141
+ sys.exit(0)
142
+
143
+ args.output_dir.mkdir(parents=True, exist_ok=True)
144
+
145
+ success_count = 0
146
+ fail_count = 0
147
+
148
+ for pds_file in pds_files:
149
+ # Determine output path
150
+ if args.flat:
151
+ output_path = args.output_dir / f"{pds_file.stem}.png"
152
+ else:
153
+ # Preserve subdirectory structure
154
+ rel_path = pds_file.relative_to(args.input_dir)
155
+ output_path = args.output_dir / rel_path.with_suffix(".png")
156
+ output_path.parent.mkdir(parents=True, exist_ok=True)
157
+
158
+ print(f"Converting: {pds_file.name} -> {output_path.name}")
159
+
160
+ if convert_pds_file(pds_file, output_path):
161
+ success_count += 1
162
+ else:
163
+ fail_count += 1
164
+
165
+ print(f"\nDone: {success_count} converted, {fail_count} failed")
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()