MCPcopy Create free account
hub / github.com/pytorch/tutorials / __getitem__

Method __getitem__

intermediate_source/torchvision_tutorial.py:156–197  ·  view source on GitHub ↗
(self, idx)

Source from the content-addressed store, hash-verified

154 self.masks = list(sorted(os.listdir(os.path.join(root, "PedMasks"))))
155
156 def __getitem__(self, idx):
157 # load images and masks
158 img_path = os.path.join(self.root, "PNGImages", self.imgs[idx])
159 mask_path = os.path.join(self.root, "PedMasks", self.masks[idx])
160 img = read_image(img_path)
161 mask = read_image(mask_path)
162 # instances are encoded as different colors
163 obj_ids = torch.unique(mask)
164 # first id is the background, so remove it
165 obj_ids = obj_ids[1:]
166 num_objs = len(obj_ids)
167
168 # split the color-encoded mask into a set
169 # of binary masks
170 masks = (mask == obj_ids[:, None, None]).to(dtype=torch.uint8)
171
172 # get bounding box coordinates for each mask
173 boxes = masks_to_boxes(masks)
174
175 # there is only one class
176 labels = torch.ones((num_objs,), dtype=torch.int64)
177
178 image_id = idx
179 area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
180 # suppose all instances are not crowd
181 iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
182
183 # Wrap sample and targets into torchvision tv_tensors:
184 img = tv_tensors.Image(img)
185
186 target = {}
187 target["boxes"] = tv_tensors.BoundingBoxes(boxes, format="XYXY", canvas_size=F.get_size(img))
188 target["masks"] = tv_tensors.Mask(masks)
189 target["labels"] = labels
190 target["image_id"] = image_id
191 target["area"] = area
192 target["iscrowd"] = iscrowd
193
194 if self.transforms is not None:
195 img, target = self.transforms(img, target)
196
197 return img, target
198
199 def __len__(self):
200 return len(self.imgs)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected