File size: 1,217 Bytes
3040ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import base64
import io
from typing import List

import numpy as np
from fastapi.exceptions import HTTPException
from PIL import Image
from pydantic import BaseModel

from ..hloc import logger
from .core import ImageMatchingAPI


class ImagesInput(BaseModel):
    data: List[str] = []
    max_keypoints: List[int] = []
    timestamps: List[str] = []
    grayscale: bool = False
    image_hw: List[List[int]] = [[], []]
    feature_type: int = 0
    rotates: List[float] = []
    scales: List[float] = []
    reference_points: List[List[float]] = []
    binarize: bool = False


def decode_base64_to_image(encoding):
    if encoding.startswith("data:image/"):
        encoding = encoding.split(";")[1].split(",")[1]
    try:
        image = Image.open(io.BytesIO(base64.b64decode(encoding)))
        return image
    except Exception as e:
        logger.warning(f"API cannot decode image: {e}")
        raise HTTPException(status_code=500, detail="Invalid encoded image") from e


def to_base64_nparray(encoding: str) -> np.ndarray:
    return np.array(decode_base64_to_image(encoding)).astype("uint8")


__all__ = [
    "ImageMatchingAPI",
    "ImagesInput",
    "decode_base64_to_image",
    "to_base64_nparray",
]