Spaces:
Sleeping
Sleeping
| import base64 | |
| from typing import Optional | |
| import cv2 | |
| import numpy as np | |
| def encode_png_base64(image: np.ndarray) -> str: | |
| bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| success, buf = cv2.imencode('.png', bgr) | |
| if not success: | |
| raise RuntimeError('Failed to encode image to PNG.') | |
| return base64.b64encode(buf.tobytes()).decode('ascii') | |
| def decode_base64_image(data: str) -> np.ndarray: | |
| # Support data URLs: data:image/png;base64,.... | |
| if ',' in data and data.strip().startswith('data:'): | |
| data = data.split(',', 1)[1] | |
| binary = base64.b64decode(data) | |
| arr = np.frombuffer(binary, dtype=np.uint8) | |
| image = cv2.imdecode(arr, cv2.IMREAD_COLOR) | |
| if image is None: | |
| raise ValueError('Unable to decode image.') | |
| return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |