Segmentation / code /src /data /dataset /kvasir_seg.py
MaybeRichard's picture
Upload PixelGen code: cross-attention mask mode + multi-scale ablation configs
01fdb75 verified
Raw
History Blame
6.51 kB
# Kvasir-SEG Dataset for PixelGen Medical Image Generation
# Polyp segmentation dataset: 1000 RGB colonoscopy images with binary masks
import os
import torch
import random
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
from torchvision.transforms import Normalize
class KvasirSEGDataset(Dataset):
"""
Kvasir-SEG dataset for mask-conditional image generation.
Data format:
- Images: ~620x530 RGB colonoscopy images (varying sizes)
- Masks: Binary polyp segmentation (near 0/255, grayscale)
- 1000 image pairs total
Returns format compatible with PixelGen:
- normalized_image: [3, H, W] in range [-1, 1]
- label: class label (0 for all)
- metadata: dict with 'raw_image', 'mask', 'class'
"""
def __init__(self, data_root, resolution=256, split='train', train_ratio=0.9,
augment=True, seed=42, max_samples=None, random_flip=True):
super().__init__()
self.data_root = data_root
self.resolution = resolution
self.split = split
self.augment = augment and (split == 'train')
self.random_flip = random_flip and (split == 'train')
self.img_dir = os.path.join(data_root, 'images')
self.mask_dir = os.path.join(data_root, 'masks')
# Get all image files
all_files = sorted([f for f in os.listdir(self.img_dir)
if f.endswith(('.jpg', '.png', '.jpeg'))])
# Split by index
random.seed(seed)
indices = list(range(len(all_files)))
random.shuffle(indices)
split_idx = int(len(indices) * train_ratio)
if split == 'train':
selected_indices = indices[:split_idx]
else:
selected_indices = indices[split_idx:]
self.images = [all_files[i] for i in sorted(selected_indices)]
# Limit samples if specified
if max_samples is not None and max_samples < len(self.images):
random.seed(seed)
self.images = random.sample(self.images, max_samples)
# Normalization for images ([-1, 1] range)
self.normalize = Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
print(f"[KvasirSEGDataset] {split} set: {len(self.images)} images")
def __len__(self):
return len(self.images)
def _load_and_process(self, idx):
"""Load and process a single sample."""
img_name = self.images[idx]
img_path = os.path.join(self.img_dir, img_name)
mask_path = os.path.join(self.mask_dir, img_name)
# Load images - RGB colonoscopy
image = Image.open(img_path).convert('RGB')
mask = Image.open(mask_path).convert('L')
# Resize to target size (square)
image = TF.resize(image, (self.resolution, self.resolution),
interpolation=transforms.InterpolationMode.BILINEAR)
mask = TF.resize(mask, (self.resolution, self.resolution),
interpolation=transforms.InterpolationMode.NEAREST)
# Data augmentation
if self.augment:
# Random horizontal flip
if self.random_flip and random.random() > 0.5:
image = TF.hflip(image)
mask = TF.hflip(mask)
# Random vertical flip
if self.random_flip and random.random() > 0.5:
image = TF.vflip(image)
mask = TF.vflip(mask)
# Random color jitter for image only
if random.random() > 0.5:
brightness_factor = random.uniform(0.85, 1.15)
image = TF.adjust_brightness(image, brightness_factor)
contrast_factor = random.uniform(0.85, 1.15)
image = TF.adjust_contrast(image, contrast_factor)
saturation_factor = random.uniform(0.85, 1.15)
image = TF.adjust_saturation(image, saturation_factor)
return image, mask
def __getitem__(self, idx):
max_retries = 10
for retry in range(max_retries):
try:
actual_idx = (idx + retry) % len(self.images)
image, mask = self._load_and_process(actual_idx)
break
except Exception as e:
if retry == max_retries - 1:
raise RuntimeError(f"Failed to load image after {max_retries} retries: {e}")
continue
raw_image = TF.to_tensor(image) # [3, H, W], range [0, 1]
normalized_image = self.normalize(raw_image)
mask_tensor = TF.to_tensor(mask) # [1, H, W], range [0, 1]
label = 0
metadata = {
"raw_image": raw_image,
"mask": mask_tensor,
"class": label,
}
return normalized_image, label, metadata
class KvasirSEGRandnDataset(Dataset):
"""
Random noise dataset for evaluation/prediction.
Samples random masks from the dataset.
"""
def __init__(self, data_root, resolution=256, max_num_instances=1000,
noise_scale=1.0, seed=42):
super().__init__()
self.resolution = resolution
self.noise_scale = noise_scale
mask_dir = os.path.join(data_root, 'masks')
all_files = sorted([f for f in os.listdir(mask_dir)
if f.endswith(('.jpg', '.png', '.jpeg'))])
random.seed(seed)
if max_num_instances <= len(all_files):
self.mask_files = random.sample(all_files, max_num_instances)
else:
self.mask_files = all_files * (max_num_instances // len(all_files) + 1)
self.mask_files = self.mask_files[:max_num_instances]
self.mask_dir = mask_dir
print(f"[KvasirSEGRandnDataset] {len(self.mask_files)} samples for generation")
def __len__(self):
return len(self.mask_files)
def __getitem__(self, idx):
xT = self.noise_scale * torch.randn(3, self.resolution, self.resolution)
mask_path = os.path.join(self.mask_dir, self.mask_files[idx])
mask = Image.open(mask_path).convert('L')
mask = TF.resize(mask, (self.resolution, self.resolution),
interpolation=transforms.InterpolationMode.NEAREST)
mask_tensor = TF.to_tensor(mask)
label = 0
metadata = {
"mask": mask_tensor,
"class": label,
}
return xT, label, metadata