Any help solving this will be highly appreciated.
I have an idea why the error is happening, it is because the xmin == xmax and ymin == ymax which should not be. However I seem not to know how this is happening. Here is how I load my custom dataset with pytorch Dataset class.
`class CustomDataset(torch.utils.data.Dataset):
def __init__(self, root, transforms=None):
self.root = root
self.transforms = transforms
# load all image files, sorting them to
# ensure that they are aligned
self.imgs = list(sorted(os.listdir(os.path.join(root, "seg_image_use"))))
self.masks = list(sorted(os.listdir(os.path.join(root, "seg_mask_use"))))
def __getitem__(self, idx):
# load one image and mask using idx
img_path = os.path.join(self.root, "seg_image_use", self.imgs[idx])
mask_path = os.path.join(self.root, "seg_mask_use", self.masks[idx])
img = Image.open(img_path).convert("RGB")
# note that we haven't converted the mask to RGB,
# because each color corresponds to a different instance
# with 0 being background
mask = Image.open(mask_path)
mask = np.asarray(mask)
# instances are encoded as different colors
obj_ids = np.unique(mask)[1:] # first id is the background, so remove it
masks = mask == obj_ids[:, None, None] # split the color-encoded mask into a set of binary masks
# get bounding box coordinates for each mask
num_objs = len(obj_ids)
boxes = []
for i in range(num_objs):
pos = np.where(masks[i])
xmin = np.min(pos[1])
xmax = np.max(pos[1])
ymin = np.min(pos[0])
ymax = np.max(pos[0])
boxes.append([xmin, ymin, xmax, ymax])
# convert everything into torch.Tensor
boxes = torch.as_tensor(boxes, dtype=torch.float32)
area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
target = {}
target["boxes"] = boxes
target["labels"] = torch.as_tensor(obj_ids, dtype=torch.int64) - 1 # corrected by Rawi
target["masks"] = torch.as_tensor(masks, dtype=torch.uint8) #uint8
target["image_id"] = torch.tensor([idx])
target["area"] = area
target["iscrowd"] = torch.zeros((num_objs,), dtype=torch.int64) # suppose all instances are not crowd
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
`
And then when I call it to see the dataset, I get the first index of each dataset showing this; take note of the first index in the 'boxes' tensor. (italic)
`dataset_sample = CustomDataset('C:/Users/LENOVO/Desktop/clothme/Train')
img, target = dataset_sample[2]
print(target)
result: {'boxes': tensor(*[[ 0., 0., 286., 403.]*,
[ 30., 240., 52., 241.],
[ 25., 183., 31., 204.],
[ 26., 224., 34., 240.],
[ 30., 169., 88., 181.],
[ 32., 239., 85., 251.],
`
Here is the error I get when I try to train the model.
`---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-81-c798930961c1> in <module>
4 for epoch in range(num_epochs):
5 # train for one epoch, printing every 10 iterations
----> 6 train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
7 # update the learning rate
8 lr_scheduler.step()
~measurement_model_devengine.py in train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq)
28 targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
29
---> 30 loss_dict = model(images, targets)
31
32 losses = sum(loss for loss in loss_dict.values())
~anaconda3envsmeasurement_py37libsite-packagesorch
nmodulesmodule.py in _call_impl(self, *input, **kwargs)
725 result = self._slow_forward(*input, **kwargs)
726 else:
--> 727 result = self.forward(*input, **kwargs)
728 for hook in itertools.chain(
729 _global_forward_hooks.values(),
~anaconda3envsmeasurement_py37libsite-packagesorchvisionmodelsdetectiongeneralized_rcnn.py in forward(self, images, targets)
92 raise ValueError("All bounding boxes should have positive height and width."
93 " Found invalid box {} for target at index {}."
---> 94 .format(degen_bb, target_idx))
95
96 features = self.backbone(images.tensors)
ValueError: All bounding boxes should have positive height and width. Found invalid box [790.0323486328125, 359.0328369140625, 790.0323486328125, 359.0328369140625] for target at index 0.
`
question from:
https://stackoverflow.com/questions/66068158/valueerror-all-bounding-boxes-should-have-positive-height-and-width