hmaissoro commited on
Commit
896f322
·
verified ·
1 Parent(s): 86165a4

add RoofSegmentationDataset

Browse files
Files changed (1) hide show
  1. model_and_lightning_module.py +184 -2
model_and_lightning_module.py CHANGED
@@ -1,12 +1,18 @@
1
  """
2
- PyTorch Lightning modules for roof segmentation.
3
  """
4
- from typing import Any, Dict
 
5
 
 
 
 
6
  import pytorch_lightning as pl
7
  import torch
8
  import torch.nn as nn
9
  import torch.nn.functional as F
 
 
10
 
11
 
12
  class DoubleConv(nn.Module):
@@ -150,3 +156,179 @@ class SegmentationLightningModule(pl.LightningModule):
150
 
151
  def forward(self, x):
152
  return self.model(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Modules for roof segmentation.
3
  """
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Dict, Optional, Tuple
6
 
7
+ import albumentations as A
8
+ import cv2
9
+ import numpy as np
10
  import pytorch_lightning as pl
11
  import torch
12
  import torch.nn as nn
13
  import torch.nn.functional as F
14
+ from albumentations.pytorch import ToTensorV2
15
+ from torch.utils.data import Dataset
16
 
17
 
18
  class DoubleConv(nn.Module):
 
156
 
157
  def forward(self, x):
158
  return self.model(x)
159
+
160
+
161
+ class RoofSegmentationDataset(Dataset):
162
+ """Dataset for roof segmentation with images and masks."""
163
+
164
+ def __init__(
165
+ self,
166
+ images_dir: Path,
167
+ masks_dir: Path,
168
+ transform: Optional[Callable] = None,
169
+ image_size: Tuple[int, int] = (512, 512)
170
+ ):
171
+ """
172
+ Args:
173
+ images_dir: Directory containing input images
174
+ masks_dir: Directory containing segmentation masks
175
+ transform: Albumentations transforms to apply
176
+ image_size: Target size for images (height, width)
177
+ """
178
+ self.images_dir = Path(images_dir)
179
+ self.masks_dir = Path(masks_dir)
180
+ self.image_size = image_size
181
+ self.transform = transform
182
+
183
+ # Get all image files
184
+ self.image_files = []
185
+ for ext in ['.jpg', '.jpeg', '.png', '.tiff', '.tif']:
186
+ self.image_files.extend(self.images_dir.glob(f'*{ext}'))
187
+ self.image_files.extend(self.images_dir.glob(f'*{ext.upper()}'))
188
+
189
+ self.image_files = sorted(self.image_files)
190
+
191
+ # Verify that corresponding masks exist
192
+ self.valid_pairs = []
193
+ for image_path in self.image_files:
194
+ mask_candidates = []
195
+ for ext in ['.jpg', '.jpeg', '.png', '.tiff', '.tif']:
196
+ mask_path = self.masks_dir / f"{image_path.stem}{ext}"
197
+ if mask_path.exists():
198
+ mask_candidates.append(mask_path)
199
+
200
+ if mask_candidates:
201
+ self.valid_pairs.append((image_path, mask_candidates[0]))
202
+
203
+ print(f"Dataset initialized with {len(self.valid_pairs)} image-mask pairs")
204
+
205
+ def __len__(self) -> int:
206
+ return len(self.valid_pairs)
207
+
208
+ def __getitem__(self, idx: int) -> dict:
209
+ image_path, mask_path = self.valid_pairs[idx]
210
+
211
+ # Load image
212
+ image = cv2.imread(str(image_path))
213
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
214
+
215
+ # Load mask
216
+ mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE)
217
+
218
+ # Resize to target size
219
+ image = cv2.resize(image, self.image_size)
220
+ mask = cv2.resize(mask, self.image_size, interpolation=cv2.INTER_NEAREST)
221
+
222
+ # Normalize mask to 0-1 (assuming binary segmentation)
223
+ mask = (mask > 127).astype(np.uint8)
224
+
225
+ # Apply transforms
226
+ if self.transform:
227
+ transformed = self.transform(image=image, mask=mask)
228
+ image = transformed['image']
229
+ mask = transformed['mask']
230
+
231
+ # Ensure mask is float for loss calculations
232
+ if isinstance(mask, torch.Tensor):
233
+ mask = mask.float()
234
+ else:
235
+ # Convert to tensors manually if no transforms
236
+ image = torch.from_numpy(image.transpose(2, 0, 1)).float()
237
+ mask = torch.from_numpy(mask).float()
238
+
239
+ return {
240
+ 'image': image,
241
+ 'mask': mask,
242
+ 'image_path': str(image_path),
243
+ 'mask_path': str(mask_path)
244
+ }
245
+
246
+
247
+ def get_training_transforms(image_size: Tuple[int, int] = (512, 512)) -> A.Compose:
248
+ """Get augmentation transforms for training."""
249
+ return A.Compose([
250
+ A.HorizontalFlip(p=0.5),
251
+ A.VerticalFlip(p=0.5),
252
+ A.RandomRotate90(p=0.5),
253
+ A.ShiftScaleRotate(
254
+ shift_limit=0.1,
255
+ scale_limit=0.2,
256
+ rotate_limit=45,
257
+ border_mode=cv2.BORDER_CONSTANT,
258
+ value=0,
259
+ p=0.5
260
+ ),
261
+ A.OneOf([
262
+ A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=1.0),
263
+ A.HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=1.0),
264
+ ], p=0.5),
265
+ A.OneOf([
266
+ A.GaussianBlur(blur_limit=(3, 7), p=1.0),
267
+ A.MedianBlur(blur_limit=5, p=1.0),
268
+ ], p=0.3),
269
+ A.Resize(image_size[0], image_size[1]),
270
+ A.Normalize(
271
+ mean=[0.485, 0.456, 0.406],
272
+ std=[0.229, 0.224, 0.225]
273
+ ),
274
+ ToTensorV2()
275
+ ])
276
+
277
+
278
+ def get_validation_transforms(image_size: Tuple[int, int] = (512, 512)) -> A.Compose:
279
+ """Get transforms for validation (no augmentation)."""
280
+ return A.Compose([
281
+ A.Resize(image_size[0], image_size[1]),
282
+ A.Normalize(
283
+ mean=[0.485, 0.456, 0.406],
284
+ std=[0.229, 0.224, 0.225]
285
+ ),
286
+ ToTensorV2()
287
+ ])
288
+
289
+
290
+ def create_dataloaders(
291
+ train_images_dir: Path,
292
+ train_masks_dir: Path,
293
+ val_images_dir: Path,
294
+ val_masks_dir: Path,
295
+ batch_size: int = 8,
296
+ num_workers: int = 4,
297
+ image_size: Tuple[int, int] = (512, 512)
298
+ ) -> Tuple[torch.utils.data.DataLoader, torch.utils.data.DataLoader]:
299
+ """Create training and validation dataloaders."""
300
+
301
+ # Create datasets
302
+ train_dataset = RoofSegmentationDataset(
303
+ images_dir=train_images_dir,
304
+ masks_dir=train_masks_dir,
305
+ transform=get_training_transforms(image_size),
306
+ image_size=image_size
307
+ )
308
+
309
+ val_dataset = RoofSegmentationDataset(
310
+ images_dir=val_images_dir,
311
+ masks_dir=val_masks_dir,
312
+ transform=get_validation_transforms(image_size),
313
+ image_size=image_size
314
+ )
315
+
316
+ # Create dataloaders
317
+ train_loader = torch.utils.data.DataLoader(
318
+ train_dataset,
319
+ batch_size=batch_size,
320
+ shuffle=True,
321
+ num_workers=num_workers,
322
+ pin_memory=True,
323
+ drop_last=True
324
+ )
325
+
326
+ val_loader = torch.utils.data.DataLoader(
327
+ val_dataset,
328
+ batch_size=batch_size,
329
+ shuffle=False,
330
+ num_workers=num_workers,
331
+ pin_memory=True
332
+ )
333
+
334
+ return train_loader, val_loader