MCPcopy Create free account
hub / github.com/Ropedia/SpatialBench / array_to_pil

Function array_to_pil

benchmark/models/loger/utils/basic.py:108–133  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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

Callers 1

tensor_to_pilFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected