import numpy as np
import cv2
import sys


def createGammaLookup():
    return np.array([removeGammaCorrection(i) for i in np.arange(0, 256)]).astype("float64")


def createReverseGammaLookup():
    return np.array([applyGammaCorrection(i / 255) for i in np.arange(0.0, 256.0)]).astype("uint8")


def removeGammaCorrection(v):
    if v <= 0.04045 * 255:
        return (v / 255) / 12.92
    elif v > 0.04045 * 255:
        return (((v / 255) + 0.055) / 1.055) ** 2.4


def applyGammaCorrection(v_reverse):
    if abs(v_reverse) <= 0.0031308:
        return round(255 * (12.92 * abs(v_reverse)))
    elif abs(v_reverse) > 0.0031308:
        if (round(255 * (1.055 * abs(v_reverse) ** 0.41666 - 0.055))) > 255:
            return 255 - (round(255 * (1.055 * abs(v_reverse) ** 0.41666 - 0.055)) - 255)
        else:
            return round(255 * (1.055 * abs(v_reverse) ** 0.41666 - 0.055))


class Dyschromasie:
    cb_image = np.array([]).astype('float64')
    sim_image = np.array([]).astype('uint8')

    def __init__(self, img_mat=np.array([]), rows=0, cols=0, kanaele=0, sim_faktor=0, sim_kind='d'):
        self.rows = rows
        self.cols = cols
        self.kanaele = kanaele
        self.img_mat = img_mat
        self.sim_faktor = sim_faktor
        self.sim_kind = sim_kind

    T = np.array([[0.31399022, 0.63951294, 0.04649755],
                  [0.15537241, 0.75789446, 0.08670142],
                  [0.01775239, 0.10944209, 0.87256922]])

    T_reversed = np.array([[5.47221206, -4.6419601, 0.16963708],
                           [-1.1252419, 2.29317094, -0.1678952],
                           [0.02980165, -0.19318073, 1.16364789]])

    def Simulate(self):

        removeGammaCorrectionLUT = createGammaLookup()

        if self.sim_kind == 'p':
            sim_mat = np.array([[(1 - self.sim_faktor), 1.05118294 * self.sim_faktor, -0.05116099 * self.sim_faktor],
                                [0, 1, 0],
                                [0, 0, 1]])
        elif self.sim_kind == 'd':
            sim_mat = np.array([[1, 0, 0],
                                [0.9513092 * self.sim_faktor, (1 - self.sim_faktor), 0.04866992 * self.sim_faktor],
                                [0, 0, 1]])
        else:
            sim_mat = np.array([[1, 0, 0],
                                [0, 1, 0],
                                [-0.86744736 * self.sim_faktor, 1.86727089 * self.sim_faktor, (1 - self.sim_faktor)]])

        # Gammakorrektur durchfuehren
        self.cb_image = np.copy(self.img_mat).astype('float64')

        self.cb_image = cv2.LUT(self.img_mat, removeGammaCorrectionLUT)

        rechen_Mat = np.copy(self.T_reversed.dot(sim_mat).dot(self.T))

        # Einzelne Pixelwertberechnung
        for i in range(self.rows):
            for j in range(self.cols):
                self.cb_image[i, j] = rechen_Mat.dot(self.cb_image[i, j])

        self.sim_image = np.copy(self.cb_image)
        self.sim_image = self.sim_image.astype('uint8')
        # Rücktransformation der Gammawerte
        for i in range(self.rows):
            for j in range(self.cols):
                for x in range(3):
                    self.sim_image[i, j, x] = applyGammaCorrection(self.cb_image[i, j, x])

        return self.sim_image

    def daltonize(self):

        err2mod = np.array([[0, 0, 0], [0.7, 1, 0], [0.7, 0, 1]])
        simulated_image = self.Simulate()

        E = np.copy(simulated_image).astype('int32')
        for i in range(self.rows):
            for j in range(self.cols):
                for x in range(3):
                    E[i, j, x] = abs(int(self.img_mat[i, j, x]) - int(simulated_image[i, j, x]))

        ERR = np.zeros_like(image).astype('int32')

        for i in range(self.rows):
            for j in range(self.cols):
                err = E[i, j, :3]
                ERR[i, j, :3] = np.dot(err2mod, err)

        dtpn = np.copy(image).astype('int32')

        for i in range(self.rows):
            for j in range(self.cols):
                 for x in range(3):
                     dtpn[i, j, x] = abs(int(ERR[i, j, x]) + int(image[i, j, x]))

        for i in range(rows):
               for j in range(cols):
                    dtpn[i, j, 0] = max(0, dtpn[i, j, 0])
                    dtpn[i, j, 0] = min(255, dtpn[i, j, 0])
                    dtpn[i, j, 1] = max(0, dtpn[i, j, 1])
                    dtpn[i, j, 1] = min(255, dtpn[i, j, 1])
                    dtpn[i, j, 2] = max(0, dtpn[i, j, 2])
                    dtpn[i, j, 2] = min(255, dtpn[i, j, 2])

        result = dtpn.astype('uint8')

        dalt = Dyschromasie(result, self.rows, self.cols, self.kanaele, self.sim_faktor, self.sim_kind)
        return dalt.Simulate()


script_dir = sys.path[0]
path = script_dir[:-4] + r'Beispielbilder\rot-gruen-schwaeche-test-bild.jpg'
image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)

rows, cols, kanaele = image.shape

dalt = Dyschromasie(image, rows, cols, kanaele, 1, 'p')
cv2.imshow('Dalt_Img', cv2.cvtColor(dalt.daltonize(), cv2.COLOR_RGB2BGR))
cv2.waitKey(0)