-
Notifications
You must be signed in to change notification settings - Fork 350
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added substation segementation dataset #2352
Open
rijuld
wants to merge
22
commits into
microsoft:main
Choose a base branch
from
rijuld:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
7dff61c
Added substation segementation dataset
rijuld 10637af
resolved bugs
rijuld 2cb0842
a
rijuld 608f76a
Resolved error
rijuld 288e8b1
fixed ruff errors
rijuld 2e9bf83
fixed mypy errors for substation seg py file
rijuld 78c494d
removed more errors
rijuld 75ca32c
resolved ruff errors and mypy errors
rijuld e2326cc
fixed length and data size along with ruff and mypy errors
rijuld 9832db4
resolved float error
rijuld ef79cd7
organized imports
rijuld 83f2eb4
changed to float
rijuld 69f5815
resolved mypy errors
rijuld 898e6b3
resolved further tests
rijuld d14eca6
sorted imports
rijuld d6ae700
more test coverage
rijuld 8892f0d
ruff format
rijuld 3f135b4
increased test code coverage
rijuld 9a05811
added formatting
rijuld 4e65b04
removed transformations so that I can add them in data module
rijuld 9a9d555
increased underline length
rijuld 3e12e7e
corrected csv row length
rijuld File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
import hashlib | ||
import os | ||
import shutil | ||
|
||
import numpy as np | ||
|
||
SIZE = 228 | ||
NUM_SAMPLES = 5 | ||
np.random.seed(0) | ||
|
||
FILENAME_HIERARCHY = dict[str, 'FILENAME_HIERARCHY'] | list[str] | ||
|
||
filenames: FILENAME_HIERARCHY = { | ||
'image_stack': ['image'], | ||
'mask': ['mask'], | ||
} | ||
|
||
def create_file(path: str) -> None: | ||
for i in range(NUM_SAMPLES): | ||
new_path = f'{path}_{i}.npz' | ||
fn = os.path.basename(new_path) | ||
if fn.startswith('image'): | ||
data = np.random.rand(4, SIZE, SIZE).astype(np.float32) # 4 channels (RGB + NIR) | ||
elif fn.startswith('mask'): | ||
data = np.random.randint(0, 4, size=(SIZE, SIZE)).astype(np.uint8) # Mask with 4 classes | ||
np.savez_compressed(new_path, arr_0=data) | ||
|
||
def create_directory(directory: str, hierarchy: FILENAME_HIERARCHY) -> None: | ||
if isinstance(hierarchy, dict): | ||
# Recursive case | ||
for key, value in hierarchy.items(): | ||
path = os.path.join(directory, key) | ||
os.makedirs(path, exist_ok=True) | ||
create_directory(path, value) | ||
else: | ||
# Base case | ||
for value in hierarchy: | ||
path = os.path.join(directory, value) | ||
create_file(path) | ||
|
||
if __name__ == '__main__': | ||
create_directory('.', filenames) | ||
|
||
# Create a zip archive of the generated dataset | ||
filename_images = 'image_stack.tar.gz' | ||
filename_masks = 'mask.tar.gz' | ||
shutil.make_archive('image_stack', 'gztar', '.', 'image_stack') | ||
shutil.make_archive('mask', 'gztar', '.', 'mask') | ||
|
||
# Compute checksums | ||
with open(filename_images, 'rb') as f: | ||
md5_images = hashlib.md5(f.read()).hexdigest() | ||
print(f'{filename_images}: {md5_images}') | ||
|
||
with open(filename_masks, 'rb') as f: | ||
md5_masks = hashlib.md5(f.read()).hexdigest() | ||
print(f'{filename_masks}: {md5_masks}') |
Binary file not shown.
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,142 @@ | ||
import os | ||
from pathlib import Path | ||
|
||
import numpy as np | ||
import pytest | ||
import torch | ||
from pytest import MonkeyPatch | ||
|
||
from torchgeo.datasets import DatasetNotFoundError, SubstationDataset | ||
|
||
|
||
class TestSubstationDataset: | ||
@pytest.fixture( | ||
params=[ | ||
{ | ||
'image_files': ['image_1.npz', 'image_2.npz'], | ||
'geo_transforms': None, | ||
'color_transforms': None, | ||
'image_resize': None, | ||
'mask_resize': None, | ||
} | ||
] | ||
) | ||
def dataset(self, monkeypatch: MonkeyPatch, tmp_path: Path, request: pytest.FixtureRequest) -> SubstationDataset: | ||
""" | ||
Fixture to create a mock dataset with specified parameters. | ||
""" | ||
class Args: | ||
pass | ||
|
||
args = Args() | ||
args.data_dir = tmp_path | ||
args.in_channels = 4 | ||
args.use_timepoints = False | ||
args.normalizing_type = 'zscore' | ||
args.normalizing_factor = np.array([1.0]) | ||
args.means = np.array([0.5]) | ||
args.stds = np.array([0.1]) | ||
args.mask_2d = True | ||
args.model_type = 'segmentation' | ||
|
||
# Creating mock image and mask files | ||
for filename in request.param['image_files']: | ||
os.makedirs(os.path.join(tmp_path, 'image_stack'), exist_ok=True) | ||
os.makedirs(os.path.join(tmp_path, 'mask'), exist_ok=True) | ||
np.savez_compressed(os.path.join(tmp_path, 'image_stack', filename), arr_0=np.random.rand(4, 128, 128)) | ||
np.savez_compressed(os.path.join(tmp_path, 'mask', filename), arr_0=np.random.randint(0, 4, (128, 128))) | ||
|
||
image_files = request.param['image_files'] | ||
geo_transforms = request.param['geo_transforms'] | ||
color_transforms = request.param['color_transforms'] | ||
image_resize = request.param['image_resize'] | ||
mask_resize = request.param['mask_resize'] | ||
|
||
return SubstationDataset( | ||
args, | ||
image_files=image_files, | ||
geo_transforms=geo_transforms, | ||
color_transforms=color_transforms, | ||
image_resize=image_resize, | ||
mask_resize=mask_resize, | ||
) | ||
|
||
def test_getitem(self, dataset: SubstationDataset) -> None: | ||
image, mask = dataset[0] | ||
assert isinstance(image, torch.Tensor) | ||
assert isinstance(mask, torch.Tensor) | ||
assert image.shape[0] == 4 # Checking number of channels | ||
assert mask.shape == (1, 128, 128) | ||
|
||
def test_len(self, dataset: SubstationDataset) -> None: | ||
assert len(dataset) == 2 | ||
|
||
def test_already_downloaded(self, tmp_path: Path) -> None: | ||
# Test to ensure dataset initialization doesn't download if data already exists | ||
class Args: | ||
pass | ||
|
||
args = Args() | ||
args.data_dir = tmp_path | ||
args.in_channels = 4 | ||
args.use_timepoints = False | ||
args.normalizing_type = 'zscore' | ||
args.normalizing_factor = np.array([1.0]) | ||
args.means = np.array([0.5]) | ||
args.stds = np.array([0.1]) | ||
args.mask_2d = True | ||
args.model_type = 'segmentation' | ||
|
||
os.makedirs(os.path.join(tmp_path, 'image_stack')) | ||
os.makedirs(os.path.join(tmp_path, 'mask')) | ||
|
||
# No need to assign `dataset` variable, just assert | ||
SubstationDataset(args, image_files=[]) | ||
assert os.path.exists(os.path.join(tmp_path, 'image_stack')) | ||
assert os.path.exists(os.path.join(tmp_path, 'mask')) | ||
|
||
def test_not_downloaded(self, tmp_path: Path) -> None: | ||
class Args: | ||
pass | ||
|
||
args = Args() | ||
args.data_dir = tmp_path | ||
args.in_channels = 4 | ||
args.use_timepoints = False | ||
args.normalizing_type = 'zscore' | ||
args.normalizing_factor = np.array([1.0]) | ||
args.means = np.array([0.5]) | ||
args.stds = np.array([0.1]) | ||
args.mask_2d = True | ||
args.model_type = 'segmentation' | ||
|
||
with pytest.raises(DatasetNotFoundError, match='Dataset not found'): | ||
SubstationDataset(args, image_files=[]) | ||
|
||
def test_plot(self, dataset: SubstationDataset) -> None: | ||
dataset.plot() | ||
# No assertion, just ensuring that the plotting does not throw any exceptions. | ||
|
||
def test_corrupted(self, tmp_path: Path) -> None: | ||
class Args: | ||
pass | ||
|
||
args = Args() | ||
args.data_dir = tmp_path | ||
args.in_channels = 4 | ||
args.use_timepoints = False | ||
args.normalizing_type = 'zscore' | ||
args.normalizing_factor = np.array([1.0]) | ||
args.means = np.array([0.5]) | ||
args.stds = np.array([0.1]) | ||
args.mask_2d = True | ||
args.model_type = 'segmentation' | ||
|
||
# Creating corrupted files | ||
os.makedirs(os.path.join(tmp_path, 'image_stack')) | ||
os.makedirs(os.path.join(tmp_path, 'mask')) | ||
with open(os.path.join(tmp_path, 'image_stack', 'image_1.npz'), 'w') as f: | ||
f.write('corrupted') | ||
|
||
with pytest.raises(Exception): | ||
SubstationDataset(args, image_files=['image_1.npz']) |
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.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These should be in alphabetical order