将numpy数组转换为PIL Image对象 Args: array: numpy数组 Returns: PIL Image对象 Raises: ImageProcessError: 当转换失败时
(array: np.ndarray)
| 120 | |
| 121 | |
| 122 | def _numpy_to_pil_image(array: np.ndarray) -> Image.Image: |
| 123 | """ |
| 124 | 将numpy数组转换为PIL Image对象 |
| 125 | |
| 126 | Args: |
| 127 | array: numpy数组 |
| 128 | |
| 129 | Returns: |
| 130 | PIL Image对象 |
| 131 | |
| 132 | Raises: |
| 133 | ImageProcessError: 当转换失败时 |
| 134 | """ |
| 135 | try: |
| 136 | # 确保数组是正确的数据类型 |
| 137 | if array.dtype != np.uint8: |
| 138 | # 如果是浮点数,假设范围是0-1,转换为0-255 |
| 139 | if array.dtype in [np.float32, np.float64]: |
| 140 | if array.max() <= 1.0: |
| 141 | array = (array * 255).astype(np.uint8) |
| 142 | else: |
| 143 | array = array.astype(np.uint8) |
| 144 | else: |
| 145 | array = array.astype(np.uint8) |
| 146 | |
| 147 | # 处理不同的数组形状 |
| 148 | if len(array.shape) == 2: |
| 149 | # 灰度图像 (H, W) |
| 150 | return Image.fromarray(array, mode='L') |
| 151 | elif len(array.shape) == 3: |
| 152 | if array.shape[2] == 1: |
| 153 | # 单通道图像 (H, W, 1) -> (H, W) |
| 154 | return Image.fromarray(array.squeeze(axis=2), mode='L') |
| 155 | elif array.shape[2] == 3: |
| 156 | # RGB图像 (H, W, 3) |
| 157 | return Image.fromarray(array, mode='RGB') |
| 158 | elif array.shape[2] == 4: |
| 159 | # RGBA图像 (H, W, 4) |
| 160 | return Image.fromarray(array, mode='RGBA') |
| 161 | else: |
| 162 | raise ImageProcessError(f"不支持的通道数: {array.shape[2]},支持1、3、4通道") |
| 163 | else: |
| 164 | raise ImageProcessError(f"不支持的数组维度: {len(array.shape)},支持2D或3D数组") |
| 165 | |
| 166 | except Exception as e: |
| 167 | raise ImageProcessError(f"numpy数组转PIL图像失败: {str(e)}") from e |
| 168 | |
| 169 | |
| 170 | def image_to_numpy(image: Image.Image, target_mode: str = 'RGB') -> np.ndarray: |
no test coverage detected
searching dependent graphs…