Sample source code for calculating dichromats' color

Tweet


Sample program which converts color image to Protanopia's color. Open Google Colab, create new file, copy&paste the text below. Run, push upload button, select 1 image file. Output image file is downloaded.

from google.colab import files
import os
import numpy as np
import cv2

uploaded=files.upload()
filename=list(uploaded.keys())[0]
image=cv2.imread(filename,cv2.IMREAD_COLOR)
rows,cols,_=image.shape
simulatep=np.zeros((rows,cols,3),dtype=np.uint8)

for y in range(rows):
  for x in range(cols):
    valr=image[y,x,2]
    valg=image[y,x,1]
    valb=image[y,x,0]

    valr/=255
    valg/=255
    valb/=255

    if valr<=0.04045: valr/=12.92
    else:             valr=((valr+0.055)/1.055)**2.4
    if valg<=0.04045: valg/=12.92
    else:             valg=((valg+0.055)/1.055)**2.4
    if valb<=0.04045: valb/=12.92
    else:             valb=((valb+0.055)/1.055)**2.4

    valx=0.4124*valr+0.3576*valg+0.1805*valb
    valy=0.2126*valr+0.7152*valg+0.0722*valb
    valz=0.0193*valr+0.1192*valg+0.9505*valb

    vall= 0.155*valx+0.543*valy-0.0031*valz
    valm=-0.155*valx+0.457*valy+0.0329*valz
    vals=                       0.016 *valz

    vallp=2.02*valm-2.52*vals
    valmp=valm
    valsp=vals

    valx=2.9484*vallp-3.5032*valmp+7.7748*valsp
    valy=       vallp+       valmp-1.8625*valsp
    valz=                           62.5 *valsp

    valr= 3.2406*valx-1.5372*valy-0.4986*valz
    valg=-0.9689*valx+1.8758*valy+0.0415*valz
    valb= 0.0557*valx-0.204 *valy+1.057 *valz

    if valr<=0: valr=0
    if valg<=0: valg=0
    if valb<=0: valb=0

    if valr>0.0031308: valr=1.055*(valr**(1/2.4))-0.055
    else:              valr=12.92*valr
    if valg>0.0031308: valg=1.055*(valg**(1/2.4))-0.055
    else:              valg=12.92*valg
    if valb>0.0031308: valb=1.055*(valb**(1/2.4))-0.055
    else:              valb=12.92*valb

    valr*=255
    valg*=255
    valb*=255

    simulatep[y,x,2]=np.clip(valr,0,255)
    simulatep[y,x,1]=np.clip(valg,0,255)
    simulatep[y,x,0]=np.clip(valb,0,255)

cv2.imwrite('simulatep.bmp',simulatep)
files.download('simulatep.bmp')


Back