Converts a NumPy array to a PIL image. Automatically: - Squeezes dimensions of size 1. - Moves the channel dimension (if it has size 3) to the last axis. Args: array (np.ndarray): Input array. Expected shape can be [C, H, W], [H, W, C], or [H, W]. Retur
(array)
| 103 | |
| 104 | |
| 105 | def array_to_pil(array): |
| 106 | """ |
| 107 | Converts a NumPy array to a PIL image. Automatically: |
| 108 | - Squeezes dimensions of size 1. |
| 109 | - Moves the channel dimension (if it has size 3) to the last axis. |
| 110 | |
| 111 | Args: |
| 112 | array (np.ndarray): Input array. Expected shape can be [C, H, W], [H, W, C], or [H, W]. |
| 113 | |
| 114 | Returns: |
| 115 | PIL.Image: The converted PIL image. |
| 116 | """ |
| 117 | # Remove singleton dimensions |
| 118 | array = np.squeeze(array) |
| 119 | |
| 120 | # Ensure the array has the channel dimension as the last axis |
| 121 | if array.ndim == 3 and array.shape[0] == 3: # If the channel is the first axis |
| 122 | array = np.transpose(array, (1, 2, 0)) # Move channel to the last axis |
| 123 | |
| 124 | # Handle single-channel grayscale images |
| 125 | if array.ndim == 2: # [H, W] |
| 126 | return Image.fromarray((array * 255).astype(np.uint8), mode="L") |
| 127 | elif array.ndim == 3 and array.shape[2] == 3: # [H, W, C] with 3 channels |
| 128 | return Image.fromarray((array * 255).astype(np.uint8), mode="RGB") |
| 129 | else: |
| 130 | raise ValueError(f"Unsupported array shape for PIL conversion: {array.shape}") |
| 131 | |
| 132 | |
| 133 | def rotate_target_dim_to_last_axis(x, target_dim=3): |