16 lines
532 B
Python
16 lines
532 B
Python
import base64
|
|
import cv2
|
|
import numpy as np
|
|
|
|
def mask_to_png_base64(mask: np.ndarray) -> str:
|
|
if mask.dtype != np.uint8:
|
|
mask = (mask > 0).astype(np.uint8) * 255
|
|
ok, buf = cv2.imencode(".png", mask)
|
|
if not ok:
|
|
raise RuntimeError("PNG encoding failed")
|
|
return base64.b64encode(buf).decode("ascii")
|
|
|
|
def png_base64_to_mask(png_b64: str) -> np.ndarray:
|
|
buf = np.frombuffer(base64.b64decode(png_b64), dtype=np.uint8)
|
|
m = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
|
|
return (m > 0).astype(np.uint8) |