Spaces:
Sleeping
Sleeping
File size: 2,478 Bytes
b213d84 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from torch.utils.data.dataset import Dataset
from detectron2.data.detection_utils import read_image
ImageTransform = Callable[[torch.Tensor], torch.Tensor]
class ImageListDataset(Dataset):
"""
Dataset that provides images from a list.
"""
_EMPTY_IMAGE = torch.empty((0, 3, 1, 1))
def __init__(
self,
image_list: List[str],
category_list: Union[str, List[str], None] = None,
transform: Optional[ImageTransform] = None,
):
"""
Args:
image_list (List[str]): list of paths to image files
category_list (Union[str, List[str], None]): list of animal categories for
each image. If it is a string, or None, this applies to all images
"""
if type(category_list) == list:
self.category_list = category_list
else:
self.category_list = [category_list] * len(image_list)
assert len(image_list) == len(
self.category_list
), "length of image and category lists must be equal"
self.image_list = image_list
self.transform = transform
def __getitem__(self, idx: int) -> Dict[str, Any]:
"""
Gets selected images from the list
Args:
idx (int): video index in the video list file
Returns:
A dictionary containing two keys:
images (torch.Tensor): tensor of size [N, 3, H, W] (N = 1, or 0 for _EMPTY_IMAGE)
categories (List[str]): categories of the frames
"""
categories = [self.category_list[idx]]
fpath = self.image_list[idx]
transform = self.transform
try:
image = torch.from_numpy(np.ascontiguousarray(read_image(fpath, format="BGR")))
image = image.permute(2, 0, 1).unsqueeze(0).float() # HWC -> NCHW
if transform is not None:
image = transform(image)
return {"images": image, "categories": categories}
except (OSError, RuntimeError) as e:
logger = logging.getLogger(__name__)
logger.warning(f"Error opening image file container {fpath}: {e}")
return {"images": self._EMPTY_IMAGE, "categories": []}
def __len__(self):
return len(self.image_list)
|