forked from microsoft/torchgeo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Fields Of The World field boundary delineation dataset (microsoft…
…#2296) * Initial commit * Formatting changes * Reformatting how self.files is stored * Added pyarrow dependency for reading parquet files * Load splits from existing parquet files * ruff * Adding tests * Adding tests * Ruff * Update torchgeo/datasets/ftw.py Co-authored-by: Adam J. Stewart <[email protected]> * Update torchgeo/datasets/ftw.py Co-authored-by: Adam J. Stewart <[email protected]> * Update torchgeo/datasets/ftw.py Co-authored-by: Adam J. Stewart <[email protected]> * Using einops * Use tuple for valid country list * Add pandas parquet * Added pyarrow req to min dataset * pandas bump * Add paper link * Add a pyarrow importorskip * No minversion * ClassVar not needed --------- Co-authored-by: Adam J. Stewart <[email protected]>
- Loading branch information
1 parent
3e968a9
commit b2f9936
Showing
10 changed files
with
574 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
import hashlib | ||
import os | ||
import shutil | ||
import zipfile | ||
|
||
import numpy as np | ||
import pandas as pd | ||
import rasterio | ||
from affine import Affine | ||
|
||
np.random.seed(0) | ||
|
||
country = 'austria' | ||
SIZE = 32 | ||
num_samples = {'train': 2, 'val': 2, 'test': 2} | ||
BASE_PROFILE = { | ||
'driver': 'GTiff', | ||
'dtype': 'uint16', | ||
'nodata': None, | ||
'width': SIZE, | ||
'height': SIZE, | ||
'count': 4, | ||
'crs': 'EPSG:4326', | ||
'transform': Affine(5.4e-05, 0.0, 0, 0.0, 5.4e-05, 0), | ||
'blockxsize': SIZE, | ||
'blockysize': SIZE, | ||
'tiled': True, | ||
'interleave': 'pixel', | ||
} | ||
|
||
|
||
def create_image(fn: str) -> None: | ||
os.makedirs(os.path.dirname(fn), exist_ok=True) | ||
|
||
profile = BASE_PROFILE.copy() | ||
|
||
data = np.random.randint(0, 20000, size=(4, SIZE, SIZE), dtype=np.uint16) | ||
with rasterio.open(fn, 'w', **profile) as dst: | ||
dst.write(data) | ||
|
||
|
||
def create_mask(fn: str, min_val: int, max_val: int) -> None: | ||
os.makedirs(os.path.dirname(fn), exist_ok=True) | ||
|
||
profile = BASE_PROFILE.copy() | ||
profile['dtype'] = 'uint8' | ||
profile['nodata'] = 0 | ||
profile['count'] = 1 | ||
|
||
data = np.random.randint(min_val, max_val, size=(1, SIZE, SIZE), dtype=np.uint8) | ||
with rasterio.open(fn, 'w', **profile) as dst: | ||
dst.write(data) | ||
|
||
|
||
if __name__ == '__main__': | ||
i = 0 | ||
cols = {'aoi_id': [], 'split': []} | ||
for split, n in num_samples.items(): | ||
for j in range(n): | ||
aoi = f'g_{i}' | ||
cols['aoi_id'].append(aoi) | ||
cols['split'].append(split) | ||
|
||
create_image(os.path.join(country, 's2_images', 'window_a', f'{aoi}.tif')) | ||
create_image(os.path.join(country, 's2_images', 'window_b', f'{aoi}.tif')) | ||
|
||
create_mask( | ||
os.path.join(country, 'label_masks', 'semantic_2class', f'{aoi}.tif'), | ||
0, | ||
1, | ||
) | ||
create_mask( | ||
os.path.join(country, 'label_masks', 'semantic_3class', f'{aoi}.tif'), | ||
0, | ||
2, | ||
) | ||
create_mask( | ||
os.path.join(country, 'label_masks', 'instance', f'{aoi}.tif'), 0, 100 | ||
) | ||
|
||
i += 1 | ||
|
||
# Create an extra train file to test for missing other files | ||
aoi = f'g_{i}' | ||
cols['aoi_id'].append(aoi) | ||
cols['split'].append(split) | ||
create_image(os.path.join(country, 's2_images', 'window_a', f'{aoi}.tif')) | ||
|
||
# Write parquet index | ||
df = pd.DataFrame(cols) | ||
df.to_parquet(os.path.join(country, f'chips_{country}.parquet')) | ||
|
||
# archive to zip | ||
with zipfile.ZipFile(f'{country}.zip', 'w') as zipf: | ||
for root, _, files in os.walk(country): | ||
for file in files: | ||
output_fn = os.path.join(root, file) | ||
zipf.write(output_fn, os.path.relpath(output_fn, country)) | ||
|
||
shutil.rmtree(country) | ||
|
||
# Compute checksums | ||
with open(f'{country}.zip', 'rb') as f: | ||
md5 = hashlib.md5(f.read()).hexdigest() | ||
print(f'{md5}') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
import os | ||
import shutil | ||
from itertools import product | ||
from pathlib import Path | ||
|
||
import matplotlib.pyplot as plt | ||
import pytest | ||
import torch | ||
import torch.nn as nn | ||
from _pytest.fixtures import SubRequest | ||
from pytest import MonkeyPatch | ||
from torch.utils.data import ConcatDataset | ||
|
||
from torchgeo.datasets import DatasetNotFoundError, FieldsOfTheWorld | ||
|
||
pytest.importorskip('pyarrow') | ||
|
||
|
||
class TestFieldsOfTheWorld: | ||
@pytest.fixture( | ||
params=product(['train', 'val', 'test'], ['2-class', '3-class', 'instance']) | ||
) | ||
def dataset( | ||
self, monkeypatch: MonkeyPatch, tmp_path: Path, request: SubRequest | ||
) -> FieldsOfTheWorld: | ||
split, task = request.param | ||
|
||
monkeypatch.setattr(FieldsOfTheWorld, 'valid_countries', ['austria']) | ||
monkeypatch.setattr( | ||
FieldsOfTheWorld, | ||
'country_to_md5', | ||
{'austria': '1cf9593c9bdceeaba21bbcb24d35816c'}, | ||
) | ||
base_url = os.path.join('tests', 'data', 'ftw') + '/' | ||
monkeypatch.setattr(FieldsOfTheWorld, 'base_url', base_url) | ||
root = tmp_path | ||
transforms = nn.Identity() | ||
return FieldsOfTheWorld( | ||
root, | ||
split, | ||
task, | ||
countries='austria', | ||
transforms=transforms, | ||
download=True, | ||
checksum=True, | ||
) | ||
|
||
def test_getitem(self, dataset: FieldsOfTheWorld) -> None: | ||
x = dataset[0] | ||
assert isinstance(x, dict) | ||
assert isinstance(x['image'], torch.Tensor) | ||
assert isinstance(x['mask'], torch.Tensor) | ||
|
||
def test_len(self, dataset: FieldsOfTheWorld) -> None: | ||
assert len(dataset) == 2 | ||
|
||
def test_add(self, dataset: FieldsOfTheWorld) -> None: | ||
ds = dataset + dataset | ||
assert isinstance(ds, ConcatDataset) | ||
assert len(ds) == 4 | ||
|
||
def test_already_extracted(self, dataset: FieldsOfTheWorld) -> None: | ||
FieldsOfTheWorld(root=dataset.root, download=True) | ||
|
||
def test_already_downloaded(self, monkeypatch: MonkeyPatch, tmp_path: Path) -> None: | ||
url = os.path.join('tests', 'data', 'ftw', 'austria.zip') | ||
root = tmp_path | ||
shutil.copy(url, root) | ||
FieldsOfTheWorld(root) | ||
|
||
def test_not_downloaded(self, tmp_path: Path) -> None: | ||
with pytest.raises(DatasetNotFoundError, match='Dataset not found'): | ||
FieldsOfTheWorld(tmp_path) | ||
|
||
def test_invalid_split(self) -> None: | ||
with pytest.raises(AssertionError): | ||
FieldsOfTheWorld(split='foo') | ||
|
||
def test_plot(self, dataset: FieldsOfTheWorld) -> None: | ||
x = dataset[0].copy() | ||
dataset.plot(x, suptitle='Test') | ||
plt.close() | ||
dataset.plot(x, show_titles=False) | ||
plt.close() | ||
x['prediction'] = x['mask'].clone() | ||
dataset.plot(x) | ||
plt.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.