This repository provides a complete workflow for image preprocessing, deep feature extraction, and unsupervised clustering for insect morphology studies by using the wings images. The pipeline standardizes raw images, learns compact latent βfingerprintsβ using a convolutional autoencoder, and then groups similar specimens through clustering methods such as OPTICS, KMeans, and Agglomerative clustering for downstream systematics and evolutionary biology analysis.
This framework was developed in collaboration with MusΓ©um national d'Histoire naturelle (MNHN) teams, University of Oxford and INSERM. It's designed for reproducibility, scalability, and biological interpretability.-
Unified two-step pipeline
- Preprocessing: format unification, resizing, renaming.
- Autoencoder representation learning: compact latent embeddings.
- Clustering: OPTICS, KMeans, Agglomerative, with metrics and visualizations.
-
Rich visual outputs
- Activation maps
- Attention / importance heatmaps
- t-SNE / PCA projections
- Clustering diagnostics
-
Reproducible model + feature outputs
- Embedding files
- Model checkpoints
- Excel summary reports
Python 3.9+
Install all dependencies:
pip install -r requirements.txtβββ preprocess.py # Preprocessing raw images
βββ main.py # Autoencoder + clustering pipeline
βββ user_guide.docx # Full detailed documentation
βββ README.md # Project introduction
βββ (Output folders created after running the scripts)
- Scans all subfolders for images
- Resizes & converts images to PNG
- Standardizes naming scheme
- Produces dataset statistics & label summaries
| Setting | Meaning | Suggested |
|---|---|---|
input_dir |
Raw image folder | Your dataset path |
output_dir |
Output folder | e.g., D:\preprocessing |
IMAGE_SIZE |
Final image size | Match training resolution |
SUPPORTED_FORMATS |
Allowed types | png, jpg, jpeg, bmp, tif |
python preprocess.py- Resized PNGs
statistics.csvfamily_counts.csv,species_counts.csvunique_families.txt,unique_species.txt,unique_names.txterrors.log
Train an autoencoder to extract morphological features, then cluster them to reveal structure in the dataset.
A convolutional autoencoder compresses each image into a low-dimensional latent vector.
These embeddings are clustered and visualized using multiple methods.
| Param | Location | Description | Recommendation |
|---|---|---|---|
data_folder |
in main() |
Input processed images | Use preprocess output |
OUTPUT_DIR |
top of file | Save path | New folder per run |
IMG_SIZE |
top of file | Training size | 128β224 |
LATENT_DIM |
top of file | Embedding length | 32β128 |
BATCH_SIZE |
top of file | Step size | 8β32 |
EPOCHS |
top of file | Training epochs | 40β100 |
REG_FACTOR |
top of file | Weight decay | 1e-5 β 5e-5 |
python main.pyAll results are saved under your chosen OUTPUT_DIR.
| File/Folder | Description | Use |
|---|---|---|
autoencoder.h5 |
Full model | Reconstruction / further training |
encoder.h5 |
Encoder-only | Extract embeddings for new images |
image_embeddings.txt |
Latent vectors | Clustering & ML |
activations/ |
Filter activations | Interpret model focus |
heatmaps/ |
Attention overlays | Morphological relevance |
tsne_plots/ |
2D visualizations | Inspect global structure |
clustering_results.xlsx |
Cluster labels & coordinates | Main summary |
clustering_metrics.xlsx |
Silhouette, CH, DBI | Compare cluster quality |
clustering_metrics.png |
Bar chart | Quick inspection |
Contains:
- filename
- family / species / name
- cluster labels (OPTICS, KMeans, Agglomerative)
- t-SNE / PCA 2D coordinates
silhouetteβ higher = bettercalinski_harabaszβ higher = betterdavies_bouldinβ lower = better
- Start small:
128Γ128,LATENT_DIM=64,BATCH_SIZE=16,EPOCHS=40. - Blurry reconstructions β increase
LATENT_DIMorEPOCHS. - Noisy heatmaps β increase
REG_FACTOR. - Compare clustering metrics to choose the best run.
- Use a fresh
OUTPUT_DIRper experiment.
- Activation maps β internal filter responses
- Heatmaps β important morphological regions
- t-SNE & PCA β visual grouping of specimens
- No images found β check
data_folder - Out of memory β reduce
IMG_SIZEorBATCH_SIZE - OPTICS returns many
-1β try KMeans/Agglomerative - Windows path issues β use double
\\(e.g.,D:\\data\\images)
The segmentation folder contains two core scripts that perform automatic insect wing segmentation and biomechanical property estimation.
This script performs wing segmentation using the Segment Anything Model (SAM).
It automatically generates masks for each input image and extracts feature embeddings for further analysis.
Main steps:
- Load and preprocess all insect wing images.
- Use the Meta AI Segment Anything (ViT-B) model to detect and segment individual wing regions.
- Save all mask files for each specimen in a dedicated subfolder (
*_masks/). - Compute embeddings for each segmented region using a pretrained MobileNetV2 feature extractor.
- Visualize species clustering using PCA and t-SNE projections.
Output examples:
- Segmentation masks (per image)
- Extracted feature CSV files
- Clustering visualizations (
PCA,t-SNE,dendrograms)
π Example output structure:
SEG_all_new/
βββ image1_masks/
β βββ image1_mask_0.png
β βββ image1_mask_1.png
β βββ ...
βββ extracted_features.csv
βββ cluster_labels_with_pca_tsne.csv
Figure. Automatic segmentation.
This script post-processes the SAM-generated masks to extract wing outlines and compute morphological flight metrics.
Main functions:
- Combine individual mask regions for each specimen.
- Extract the largest contour representing the full wing area.
- Compute key aerodynamic parameters:
- Wing span (b)
- Wing area (S)
- Average chord (c = S/b)
- Aspect ratio (AR = bΒ²/S)
- Estimate body volumes and flight efficiency based on wing span scaling laws.
- Save all wing outline images and parameter reports (
TXT,Excel).
Output examples:
- Outlined wing images (black on white background)
wing_body_parameters.xlsxβ including span, area, aspect ratio, and flight efficiencywing_body_parameters.txtβ detailed per-image summaries
π Example output structure:
Wing_Outlines_new/
βββ image1_combined_outline.png
βββ wing_body_parameters.xlsx
βββ wing_body_parameters.txt
- Run
seg_main.pyβ performs segmentation and feature extraction. - Run
outline_extract_and_calculate.pyβ extracts outlines and computes morphological/flight traits.
π· Example illustration:
Figure. Automatic segmentation and morphological parameter extraction.
The repository includes a minimal, self-contained 3D generalization demo under `3d_expansion`. It shows that our representation-learning + clustering pipeline extends naturally to 3D morphology and primates 3d data by learning latent codes from synthetic volumetric shapes (e.g., sphere, cube, ellipsoid, cylinder, torus; and cuneiform, femur, mandible, patella, scapula, vertebra for primates).
![]() Cuneiform |
![]() Femur |
![]() Mandible |
![]() Vertebra |
![]() Patella |
![]() Scapula |
3D primates datasets examples. The raw volume data were downloaded from MorphoSource (ID: 000656244; AlmΓ©cija et al. 2024).
---3d_extensioni/
βββ main_3d.py # 3D synthetic shapes + 3D autoencoder + projections (t-SNE/PCA)
βββ primates/ # basic results for primates
βββ (generated outputs after running)
From the project root:
python main_3d.pyThis will:
- Generate synthetic 3D shapes (voxel grids)
- Train a lightweight 3D autoencoder to learn latent features
- Project latent codes with t-SNE/PCA for visualization
- Save plots under
outputs_3d_demo/
Expected outputs:
outputs_3d_demo/
βββ tsne_3d.png # t-SNE on latent features (colored by shape)
βββ pca_3d.png # PCA on latent features (colored by shape)
- The same autoencoder-based feature learning strategy works on 3D volumes.
- Shape classes form separable clusters in the learned latent space (see t-SNE/PCA).
- This provides a simple proof-of-concept that our 2D pipeline generalizes to 3D morphology.
3D latent projections: t-SNE (left) and PCA (right).
3D latent projections: t-SNE (left) and PCA (right).
If you use this pipeline in research, please cite:
AlmΓ©cija, S., Pugh, K. D., Anaya, A., Smith, C. M., Simmons, N. B., Voss, R. S., ... & Catalano, S. A. (2024). Primate Phenotypes: A Multi-Institution Collection of 3D Morphological Data Housed in MorphoSource. Scientific Data, 11(1), 1391.
MIT License
For questions, suggestions, or collaborations, please feel free to open an issue or contact the author [email protected].










