import numpy as np
from PIL import Image
from scipy.interpolate import PchipInterpolator
import json


def pil2arr(pil):
    if isinstance(pil, list):
        arr = np.array(
            [np.array(e.convert('RGB').getdata(), dtype=np.uint8).reshape(e.size[1], e.size[0], -1) for e in pil])
    else:
        arr = np.array(pil)
    return arr


def image2pil(filename):
    return Image.open(filename)


def image2arr(filename):
    pil = image2pil(filename)
    return pil2arr(pil)


def interpolate_trajectory(points, n_points):
    x = [point[0] for point in points]
    y = [point[1] for point in points]

    t = np.linspace(0, 1, len(points))

    fx = PchipInterpolator(t, x)
    fy = PchipInterpolator(t, y)

    new_t = np.linspace(0, 1, n_points)

    new_x = fx(new_t)
    new_y = fy(new_t)
    new_points = list(zip(new_x, new_y))

    return new_points


def load_json(file_path, key=None):
    with open(file_path, 'r', encoding='utf-8') as json_file:
        data = json.load(json_file)
    if key is not None:
        return data[key]
    return data
