import cv2
from matplotlib import pyplot as plt


def show_image_cv2(image, maxdim=700):
    h, w, c = image.shape
    maxhw = max(h, w)
    if maxhw > maxdim:
        ratio = maxdim / maxhw
        h = int(h * ratio)
        w = int(w * ratio)
        img = cv2.resize(image, (h, w))
    cv2.imshow("", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def show_image_mpl(image):
    fig, ax = plt.subplots(1, 1)
    fig.set_size_inches(20, 20)
    ax.imshow(image, cmap="gray")
    plt.show()


def show_image(image, backend="m"):
    if backend.startswith("m"):
        show_image_mpl(image)
    else:
        show_image_cv2(image)


def save_image(image, path):
    cv2.imwrite(path, image)
