| """ |
| BIOSCAN-5M Dataset Loader |
| |
| Author: Zahra Gharaee (https://github.com/zahrag) |
| License: MIT License |
| Description: |
| This script serves as a usage demo for loading and accessing the BIOSCAN-5M dataset, |
| which includes millions of annotated insect images along with associated metadata for machine learning and biodiversity research. |
| It demonstrates how to use the dataset loader to access multiple image resolutions (e.g., cropped and original) |
| and predefined splits (e.g., training, validation, pretraining). |
| The demo integrates with the Hugging Face `datasets` library, showcasing how to load |
| the dataset locally or from the Hugging Face Hub for seamless data preparation and machine learning workflows. |
| """ |
|
|
| import matplotlib.pyplot as plt |
| from datasets import load_dataset |
|
|
|
|
| def plot_image_with_metadata(ex): |
|
|
| image = ex["image"] |
|
|
| |
| fields_to_show = [ |
| "processid", "sampleid", "phylum", "class", "order", "family", "subfamily", "genus", "species", |
| "dna_bin", "dna_barcode", "country", "province_state", "coord-lat", "coord-lon", |
| "image_measurement_value", "area_fraction", "scale_factor", "split" |
| ] |
|
|
| |
| metadata_lines = [] |
| for cnt, field in enumerate(fields_to_show): |
| value = ex.get(field, "N/A") |
| if field == "dna_barcode" and value not in ("N/A", None, ""): |
| value = value[:10] + " ... " + f"({len(value)} bp)" |
| if field == "image_measurement_value" and value not in (None, "", "N/A"): |
| value = int(value) |
| metadata_lines.append(f"{cnt + 1}- {field}: {value}") |
|
|
| fig, axs = plt.subplots(1, 2, figsize=(12, 6), gridspec_kw={'width_ratios': [1.2, 2]}) |
| plt.subplots_adjust(wspace=0.1) |
| fig.suptitle(f"Image and Metadata: {ex.get('processid', '')}", fontsize=14) |
|
|
| |
| axs[0].axis("off") |
| metadata_text = "\n".join(metadata_lines) |
| axs[0].text(0, 0.9, metadata_text, fontsize=14, va='top', ha='left', transform=axs[0].transAxes, wrap=True) |
|
|
| |
| axs[1].imshow(image) |
| axs[1].axis("off") |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| def main(): |
|
|
| ds_val = load_dataset("dataset.py", name="cropped_256_eval", split="validation", trust_remote_code=True) |
| print(f"{ds_val.description}{ds_val.license}{ds_val.citation}") |
|
|
| |
| samples_to_show = 10 |
| cnt = 1 |
| for i, sp in enumerate(ds_val): |
| plot_image_with_metadata(sp) |
| if cnt == samples_to_show: |
| break |
| cnt += 1 |
|
|
| if __name__ == '__main__': |
| main() |
|
|
|
|
|
|
|
|