Upload LegoDataset.py
Browse files- LegoDataset.py +57 -0
LegoDataset.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from pycocotools.coco import COCO
|
| 6 |
+
import torchvision.transforms as T
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LegoDataset(torch.utils.data.Dataset):
|
| 10 |
+
def __init__(self, root, annFile, transforms=None):
|
| 11 |
+
self.root = root
|
| 12 |
+
self.coco = COCO(annFile)
|
| 13 |
+
self.ids = list(self.coco.imgs.keys())
|
| 14 |
+
self.transforms = transforms or T.Compose([T.ToTensor()])
|
| 15 |
+
|
| 16 |
+
def __getitem__(self, index):
|
| 17 |
+
img_id = self.ids[index]
|
| 18 |
+
img_info = self.coco.loadImgs(img_id)[0]
|
| 19 |
+
path = img_info["file_name"]
|
| 20 |
+
img = Image.open(os.path.join(self.root, path)).convert("RGB")
|
| 21 |
+
|
| 22 |
+
ann_ids = self.coco.getAnnIds(imgIds=img_id)
|
| 23 |
+
annotations = self.coco.loadAnns(ann_ids)
|
| 24 |
+
|
| 25 |
+
boxes = []
|
| 26 |
+
labels = []
|
| 27 |
+
masks = [] # Dummy masks
|
| 28 |
+
|
| 29 |
+
for ann in annotations:
|
| 30 |
+
xmin, ymin, width, height = ann["bbox"]
|
| 31 |
+
boxes.append([xmin, ymin, xmin + width, ymin + height])
|
| 32 |
+
labels.append(1) # 'lego' is the only class, labeled as 1
|
| 33 |
+
|
| 34 |
+
# Dummy mask for Mask R-CNN, filled with zeros
|
| 35 |
+
dummy_mask = np.zeros(
|
| 36 |
+
(img_info["height"], img_info["width"]), dtype=np.uint8
|
| 37 |
+
)
|
| 38 |
+
masks.append(dummy_mask)
|
| 39 |
+
|
| 40 |
+
boxes = torch.as_tensor(boxes, dtype=torch.float32)
|
| 41 |
+
labels = torch.as_tensor(labels, dtype=torch.int64)
|
| 42 |
+
masks = torch.as_tensor(np.array(masks), dtype=torch.uint8)
|
| 43 |
+
|
| 44 |
+
target = {
|
| 45 |
+
"boxes": boxes,
|
| 46 |
+
"labels": labels,
|
| 47 |
+
"masks": masks,
|
| 48 |
+
"image_id": torch.tensor([img_id]),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
if self.transforms:
|
| 52 |
+
img = self.transforms(img)
|
| 53 |
+
|
| 54 |
+
return img, target
|
| 55 |
+
|
| 56 |
+
def __len__(self):
|
| 57 |
+
return len(self.ids)
|