# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda env:root] *
#     language: python
#     name: conda-root-py
# ---

import cv2
import numpy as np
import matplotlib.pyplot as plt

# +
B = cv2.imread("target.png")
R = cv2.imread("input.png")

B = cv2.cvtColor(B, cv2.COLOR_BGR2RGB)
R = cv2.cvtColor(R, cv2.COLOR_BGR2RGB)

B = cv2.resize(B, (256, 384))
R = cv2.resize(R, (256, 384))
# -

plt.imshow(np.concatenate((B, cv2.resize(R, (B.shape[1], B.shape[0]))), axis=1))


def calHistRGB(I):
    hr = np.zeros(2**8+5).astype(np.uint64)
    hg = np.zeros(2**8+5).astype(np.uint64)
    hb = np.zeros(2**8+5).astype(np.uint64)
    for r in range(I.shape[0]):
        for c in range(I.shape[1]):
            hr[I[r][c][0]] = hr[I[r][c][0]] + 1
            hg[I[r][c][1]] = hg[I[r][c][1]] + 1
            hb[I[r][c][2]] = hb[I[r][c][2]] + 1
    return hr, hg, hb


hrB, hgB, hbB = calHistRGB(B)
hrR, hgR, hbR = calHistRGB(R)

print(hrB, hgB, hbB)


def calCDF(hr, hg, hb, A):
    cdf_r = np.zeros(2**8).astype(np.float16)
    cdf_g = np.zeros(2**8).astype(np.float16)
    cdf_b = np.zeros(2**8).astype(np.float16)
    for i in range(0, 2**8):
        cdf_r[i] = 1.0*hr[i]/A + (cdf_r[i-1] if i > 0 else 0.0)
        cdf_g[i] = 1.0*hg[i]/A + (cdf_g[i-1] if i > 0 else 0)
        cdf_b[i] = 1.0*hb[i]/A + (cdf_b[i-1] if i > 0 else 0)
    return cdf_r, cdf_g, cdf_b


cdfB = calCDF(hrB, hgB, hbB, B.shape[0]*B.shape[1])
cdfR = calCDF(hrR, hgR, hbR, R.shape[0]*R.shape[1])
print(cdfB[0][-1])

# +
LUT = np.zeros((3, 2**8)).astype(np.uint64)

for k in range(3):
    j = 0
    for i in range(2**8):
        while( cdfB[k][j] < cdfR[k][i] and j < 255):
            j = j + 1
        LUT[k][i] = j
        
for r in range(R.shape[0]):
    for c in range(R.shape[1]):
        for k in range(R.shape[2]):
            R[r][c][k] = LUT[k][R[r][c][k]];
print(LUT)
plt.imshow(R)
# -





StarcoderdataJupyterScriptsDedupFiltered