-
Notifications
You must be signed in to change notification settings - Fork 2k
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 support for HDF5 dataset and an HDF5 creation tool #1468
Open
madisi98
wants to merge
4
commits into
fizyr:main
Choose a base branch
from
madisi98:hdf5s
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 all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
fd67a65
Added build_hdf5.py and an entry point for it
madisi98 14066a8
Added support for hdf5 datasets
madisi98 9d2b9e5
Added abstract methods that were left from implementation
madisi98 8382be0
Swaped tqdm for progressbar2 in build_hdf5.py
madisi98 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,4 +20,7 @@ __pycache__/ | |
.coverage | ||
.coverage.* | ||
coverage.xml | ||
*.cover | ||
*.cover | ||
|
||
# IDE | ||
.idea |
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,115 @@ | ||
import argparse | ||
|
||
import h5py | ||
import numpy as np | ||
from progressbar import progressbar | ||
|
||
from ..preprocessing.csv_generator import CSVGenerator | ||
from ..models import backbone | ||
|
||
|
||
def parse(): | ||
parser = argparse.ArgumentParser(description='Simple script for building an HDF5 file for retinanet training.') | ||
|
||
parser.add_argument('--train-annotations', | ||
help='Path to CSV file containing annotations for training.', | ||
required=True) | ||
parser.add_argument('--val-annotations', | ||
help='Path to CSV file containing annotations for validation (optional).') | ||
parser.add_argument('--classes', | ||
help='Path to a CSV file containing class label mapping.', | ||
required=True) | ||
parser.add_argument('--dest-file', | ||
help='Path to destination HDF5 file.', | ||
required=True) | ||
|
||
parser.add_argument('--backbone-to-use', | ||
help='Backbone that will be used in training.', | ||
default='resnet50', | ||
type=str) | ||
parser.add_argument('--image-min-side', | ||
help='Rescale the image so the smallest side is min_side.', | ||
type=int, | ||
default=800) | ||
parser.add_argument('--image-max-side', | ||
help='Rescale the image if the largest side is larger than max_side.', | ||
type=int, | ||
default=1333) | ||
parser.add_argument('--no-resize', | ||
help='Don\'t rescale the image.', | ||
action='store_true') | ||
|
||
args = parser.parse_args() | ||
|
||
return args | ||
|
||
|
||
def main(): | ||
args = parse() | ||
annotations_csv = { | ||
'train': args.train_annotations, | ||
'val': args.val_annotations, | ||
} | ||
classes_csv = args.classes | ||
dataset_file = args.dest_file | ||
|
||
common_args = { | ||
'batch_size' : 1, | ||
'image_min_side' : args.image_min_side, | ||
'image_max_side' : args.image_max_side, | ||
'no_resize' : args.no_resize, | ||
'preprocess_image' : backbone(args.backbone_to_use).preprocess_image, | ||
} | ||
|
||
transform_generator = None | ||
visual_effect_generator = None | ||
|
||
for split in ['train', 'val']: | ||
if not annotations_csv[split]: | ||
continue | ||
|
||
generator = CSVGenerator( | ||
annotations_csv[split], | ||
classes_csv, | ||
transform_generator=transform_generator, | ||
visual_effect_generator=visual_effect_generator, | ||
**common_args | ||
) | ||
|
||
# Computing the data that will be stored | ||
# H5py does not allow variable length arrays of more than 1 dimension | ||
# so we save the shapes to be able to reconstruct them. | ||
# Also preprocessed images are saved so they don't have to be preprocessed avery time they are used in training. | ||
all_images_group = [] | ||
labels_group = [] | ||
bboxes_group = [] | ||
shapes_group = [] | ||
|
||
for i in progressbar(range(generator.size()), prefix=f'{split}: '): | ||
group = [i] | ||
image_group = generator.load_image_group(group) | ||
annotations_group = generator.load_annotations_group(group) | ||
|
||
image_group, annotations_group = generator.filter_annotations(image_group, annotations_group, group) | ||
image_group, annotations_group = generator.preprocess_group(image_group, annotations_group) | ||
|
||
shapes_group += [image_group[0].shape] | ||
all_images_group += [image_group[0].reshape(-1)] | ||
labels_group += [annotations_group[0]['labels']] | ||
bboxes_group += [annotations_group[0]['bboxes'].reshape(-1)] | ||
|
||
save_classes = [k for k in generator.classes] | ||
|
||
# Creating and filling the hdf5 file. We use special dtypes because we have variable lengths in our variables | ||
dt = h5py.special_dtype(vlen=np.dtype('float64')) | ||
st = h5py.special_dtype(vlen=str) | ||
print(f'Saving {split}...') | ||
with h5py.File(dataset_file, 'a') as hf: | ||
hf.create_dataset(f'{split}/img', data=all_images_group, compression='gzip', compression_opts=9, dtype=dt) | ||
hf.create_dataset(f'{split}/shapes', data=shapes_group, compression='gzip', compression_opts=9) | ||
hf.create_dataset(f'{split}/labels', data=labels_group, compression='gzip', compression_opts=9, dtype=dt) | ||
hf.create_dataset(f'{split}/bboxes', data=bboxes_group, compression='gzip', compression_opts=9, dtype=dt) | ||
if split == 'train': | ||
hf.create_dataset('classes', data=np.string_(save_classes), compression='gzip', compression_opts=9, dtype=st) | ||
print(f'[OK] {split}') | ||
|
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,104 @@ | ||
from collections import OrderedDict | ||
|
||
import h5py | ||
|
||
from .generator import Generator | ||
|
||
|
||
class HDF5Generator(Generator): | ||
|
||
def __init__( | ||
self, | ||
hdf5_file, | ||
partition, | ||
**kwargs | ||
): | ||
with h5py.File(hdf5_file, 'r') as hf: | ||
self.images = list(hf[partition]['img']) | ||
shapes = list(hf[partition]['shapes']) | ||
self.labels = list(hf[partition]['labels']) | ||
self.bboxes = list(hf[partition]['bboxes']) | ||
self.classes = list(hf['classes']) | ||
|
||
# hdf5 only allows storage of unidimensional arrays if they have different lengths | ||
self.images = [img.reshape(shapes[i]) for i, img in enumerate(self.images)] | ||
self.bboxes = [box.reshape(-1, 4) for box in self.bboxes] | ||
self.classes = OrderedDict({key: i for i, key in enumerate(self.classes)}) | ||
|
||
self.labels_dict = {} | ||
for key, value in self.classes.items(): | ||
self.labels_dict[value] = key | ||
|
||
super(HDF5Generator, self).__init__(**kwargs) | ||
|
||
def size(self): | ||
return len(self.images) | ||
|
||
def num_classes(self): | ||
""" Number of classes in the dataset. | ||
""" | ||
return max(self.classes.values()) + 1 | ||
|
||
def image_aspect_ratio(self, image_index): | ||
""" Compute the aspect ratio for an image with image_index. | ||
""" | ||
return float(self.images[image_index].shape[1]) / float(self.images[image_index].shape[0]) | ||
|
||
def get_image_group(self, group): | ||
return [self.images[i] for i in group] | ||
|
||
def get_annotations_group(self, group): | ||
return [{'labels': self.labels[i], | ||
'bboxes': self.bboxes[i]} for i in group] | ||
|
||
def has_label(self, label): | ||
""" Return True if label is a known label. | ||
""" | ||
return label in self.labels_dict | ||
|
||
def has_name(self, name): | ||
""" Returns True if name is a known class. | ||
""" | ||
return name in self.classes | ||
|
||
def name_to_label(self, name): | ||
""" Map name to label. | ||
""" | ||
return self.classes[name] | ||
|
||
def label_to_name(self, label): | ||
""" Map label to name. | ||
""" | ||
return self.labels_dict[label] | ||
|
||
def image_path(self, image_index): | ||
return str(image_index) | ||
|
||
def load_image(self, image_index): | ||
return self.images[image_index] | ||
|
||
def load_annotations(self, image_index): | ||
return {'labels': self.labels[image_index], | ||
'bboxes': self.bboxes[image_index]} | ||
|
||
def compute_input_output(self, group): | ||
""" Compute inputs and target outputs for the network. | ||
""" | ||
# load images and annotations | ||
image_group = self.get_image_group(group) | ||
annotations_group = self.get_annotations_group(group) | ||
|
||
# randomly apply visual effect | ||
image_group, annotations_group = self.random_visual_effect_group(image_group, annotations_group) | ||
|
||
# randomly transform data | ||
image_group, annotations_group = self.random_transform_group(image_group, annotations_group) | ||
|
||
# compute network inputs | ||
inputs = self.compute_inputs(image_group) | ||
|
||
# compute network targets | ||
targets = self.compute_targets(image_group, annotations_group) | ||
|
||
return inputs, targets | ||
|
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
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.
You override this to remove the filtering, right? Does it have a large computational impact? I'd expect it to be minimal, in which case it would be cleaner to not override this function. Do you have a measurement for this?
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.
Yes, I removed filtering because filtering happens when creating the hdf5. This process relies in the CSVGenerator class which filters the annotations already, so I considered removing that