""" Simple script to create a FiftyOne dataset from the parkseg12k dataset with NDVI calculation. """ # Import necessary libraries import fiftyone as fo import os import numpy as np from PIL import Image from datasets import load_dataset def main(): # Create a new FiftyOne dataset name = "parkseg12k_train" dataset = fo.Dataset(name, overwrite=True, persistent=True) # Load the Hugging Face dataset try: hf_dataset = load_dataset("file://" + os.path.join(os.getcwd(), "parkseg12k_dataset")) print("Loaded dataset from local storage") except: print("Loading from HuggingFace") hf_dataset = load_dataset("UTEL-UIUC/parkseg12k") # Create directories for storing images images_dir = os.path.join(os.getcwd(), "parkseg12k_images_train") ndvi_dir = os.path.join(os.getcwd(), "parkseg12k_ndvi") os.makedirs(images_dir, exist_ok=True) os.makedirs(ndvi_dir, exist_ok=True) # Only process the train split split = "train" print(f"Processing {split} split...") samples = [] # Process each sample for i, sample in enumerate(hf_dataset[split]): if i % 100 == 0: print(f"Processing sample {i}/{len(hf_dataset[split])}") # Create paths for saving images rgb_path = os.path.join(images_dir, f"{i}_rgb.png") mask_path = os.path.join(images_dir, f"{i}_mask.png") nir_path = os.path.join(images_dir, f"{i}_nir.png") ndvi_path = os.path.join(ndvi_dir, f"{i}_ndvi.npy") # Save images to disk sample['rgb'].save(rgb_path) sample['mask'].save(mask_path) sample['nir'].save(nir_path) # Calculate NDVI rgb_array = np.array(sample['rgb']) nir_array = np.array(sample['nir']) # Extract red channel and normalize red = rgb_array[:, :, 0].astype(np.float32) / 255.0 nir = nir_array.astype(np.float32) / 255.0 # Calculate NDVI: (NIR - Red) / (NIR + Red) numerator = nir - red denominator = nir + red # Avoid division by zero ndvi = np.where(denominator != 0, numerator / denominator, 0) # Clip to valid NDVI range ndvi = np.clip(ndvi, -1, 1) # Save NDVI array np.save(ndvi_path, ndvi) # Create FiftyOne sample fo_sample = fo.Sample(filepath=rgb_path) # Add mask as Segmentation using mask_path fo_sample["segmentation"] = fo.Segmentation(mask_path=mask_path) # Add NIR as Heatmap using map_path with range [0,1] fo_sample["nir"] = fo.Heatmap(map_path=nir_path, range=[0, 1]) # Add NDVI as Heatmap with the array directly fo_sample["ndvi"] = fo.Heatmap(map=ndvi, range=[-1, 1]) # Optional: Add NDVI statistics as metadata fo_sample["ndvi_mean"] = float(np.mean(ndvi)) fo_sample["ndvi_std"] = float(np.std(ndvi)) fo_sample["ndvi_min"] = float(np.min(ndvi)) fo_sample["ndvi_max"] = float(np.max(ndvi)) # Add to samples list samples.append(fo_sample) # Add all samples at once print(f"Adding {len(samples)} samples to dataset...") dataset.add_samples(samples) # Compute metadata and add dynamic fields dataset.compute_metadata() dataset.add_dynamic_sample_fields() return dataset if __name__ == "__main__": dataset = main()