List out of range when using boundings boxes in object detection

Rexedoziem: <p>import os<br>
import torch<br>
from torch.utils.data import Dataset<br>
import albumentations as A<br>
from albumentations.pytorch import ToTensorV2<br>
import cv2<br>
import numpy as np<br>
import matplotlib.pyplot as plt</p>
<p>class CropDiseaseDataset(Dataset):<br>
def <strong>init</strong>(self, df, img_dir, transforms=None):<br>
self.df = df.reset_index(drop=True)  # Reset index to handle indexing correctly<br>
self.img_dir = img_dir<br>
self.transforms = transforms  # Augmentations should be passed during dataset instantiation<br>
self.file_names = self.df[‘Image_ID’].values  # Assuming ‘file_names’ column for image paths<br>
self.targets = self.df[‘class’].values          # Assuming ‘class’ column for labels<br>
self.bboxes = self.df[[‘xmin’, ‘ymin’, ‘xmax’, ‘ymax’]].values  # Assuming columns for bounding boxes</p>
<pre><code>def __len__(self):
    return len(self.df)

def __getitem__(self, index):
    # Construct image path
    img_path = os.path.join(self.img_dir, self.file_names[index])
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert BGR (OpenCV) to RGB format
    
    target = self.targets[index]
    bbox = self.bboxes[index].astype(float)  # Convert bbox to float
    # Check if bbox is valid
    if bbox.shape[0] != 4 or any(bbox &lt; 0):
        print(f"Warning: Invalid bbox format at index {index}. Skipping sample.")
        return None
    
    # Apply transformations if they exist
    if self.transforms is not None:
        transformed = self.transforms(image=img, bboxes=[bbox], labels=[target])
        # If transformation removes bounding box or any issue, skip the sample
        if len(transformed['bboxes']) == 0:
            print(f"Warning: Transformation removed bbox at index {index}. Skipping sample.")
            return None
        img = transformed['image']
        bbox = transformed['bboxes'][0]  # Extract transformed bbox as single bbox
        target = transformed['labels'][0]

    return {
        'image': img,
        'bbox': bbox,
        'label': target
    }
</code></pre>
<h1><a name="p-458896-define-the-transformations-1" class="anchor" href="#p-458896-define-the-transformations-1"></a>Define the transformations</h1>
<p>train_transform = A.Compose([<br>
A.RandomResizedCrop(224, 224),<br>
A.HorizontalFlip(p=0.5),<br>
A.RandomGamma(gamma_limit=(80, 120), p=0.5),<br>
A.RandomBrightnessContrast(p=0.5),<br>
A.CLAHE(clip_limit=4.0, tile_grid_size=(8, 8), p=0.5),<br>
A.ShiftScaleRotate(shift_limit=0.05, scale_limit=0.05, rotate_limit=15, p=0.5),<br>
A.RGBShift(r_shift_limit=15, g_shift_limit=15, b_shift_limit=15, p=0.5),<br>
A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>
ToTensorV2(),<br>
], bbox_params=A.BboxParams(format=‘pascal_voc’, min_visibility=0.05, label_fields=[‘labels’]))</p>
<p>val_transform = A.Compose([<br>
A.Resize(256, 256),<br>
A.CenterCrop(224, 224),<br>
A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>
ToTensorV2(),<br>
], bbox_params=A.BboxParams(format=‘pascal_voc’, min_visibility=0.05, label_fields=[‘labels’]))</p>
<p>def visualize_dataset_samples(dataset, num_samples=5):<br>
“”"<br>
Visualize a set number of samples from the dataset to check for issues.<br>
“”"<br>
for idx in range(num_samples):<br>
print(f"\nVisualizing sample {idx}:“)<br>
try:<br>
sample = dataset[idx]<br>
if sample is None:<br>
print(f"Sample {idx} is None. Skipping.”)<br>
continue</p>
<pre><code>        img = sample['image'].permute(1, 2, 0).numpy()  # Convert to HWC format for display
        bbox = sample['bbox']
        label = sample['label']
        
        # Draw bounding box on the image
        x_min, y_min, x_max, y_max = map(int, bbox)
        img = cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (255, 0, 0), 2)  # Draw bounding box
        
        plt.imshow(img)
        plt.title(f"Label: {label}")
        plt.axis('off')
        plt.show()
        
    except IndexError as e:
        print(f"Error visualizing sample {idx}: {e}")
    except Exception as e:
        print(f"An unexpected error occurred for sample {idx}: {e}")
</code></pre>
<h1><a name="p-458896-usage-example-assuming-your-dataframe-df-and-image-directory-image_dir-are-set-up-2" class="anchor" href="#p-458896-usage-example-assuming-your-dataframe-df-and-image-directory-image_dir-are-set-up-2"></a>Usage example (assuming your DataFrame <code>df</code> and image directory <code>IMAGE_DIR</code> are set up)</h1>
<p>dataset = CropDiseaseDataset(df=df, img_dir=IMAGE_DIR, transforms=train_transform)<br>
visualize_dataset_samples(dataset, num_samples=5)</p>
<p>The error: Visualizing sample 1:<br>
Warning: Transformation removed bbox at index 1. Skipping sample.<br>
Sample 1 is None. Skipping.<br>
it reads some images and also show this error in some too?</p>