| 54 | |
| 55 | #i should make a utility function file |
| 56 | def validate_and_convert_image(image, target_size=(256, 256)): |
| 57 | if image is None: |
| 58 | print("Encountered a None image") |
| 59 | return None |
| 60 | |
| 61 | if isinstance(image, torch.Tensor): |
| 62 | # Convert PyTorch tensor to PIL Image |
| 63 | if image.ndim == 3 and image.shape[0] in [1, 3]: # Check for CxHxW format |
| 64 | if image.shape[0] == 1: # Convert single-channel grayscale to RGB |
| 65 | image = image.repeat(3, 1, 1) |
| 66 | image = image.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() |
| 67 | image = Image.fromarray(image) |
| 68 | else: |
| 69 | print(f"Invalid image tensor shape: {image.shape}") |
| 70 | return None |
| 71 | elif isinstance(image, Image.Image): |
| 72 | # Resize PIL Image |
| 73 | image = image.resize(target_size) |
| 74 | else: |
| 75 | print("Image is not a PIL Image or a PyTorch tensor") |
| 76 | return None |
| 77 | |
| 78 | return image |
| 79 | |
| 80 | def create_image_grid(images, rows, cols, target_size=(256, 256)): |
| 81 | valid_images = [validate_and_convert_image(img, target_size) for img in images] |