PawanratRung commited on
Commit
360fe5f
·
verified ·
1 Parent(s): abd0b8d

Create image_list_dataset.py

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