%
%letterdemo.m
% This Matlab program takes as input
% a letter image and a letter mask image and 
% illustrates the computation of the letter image statistics for 
% the readability index of Scharff and Ahumada (2003).

% mask for the letter e
mask = ...
[    0     0     0     0
     0     1     1     0
     1     0     0     1
     1     1     1     1
     1     0     0     0
     1     0     0     1
     0     1     1     0
     0     0     0     0];
 
 % letter e simulated luminance image
% imageY = floor(100*rand(size(mask))+50*mask);
imageY =...
[   81    83    79    87
    66   106   145    73
    84    37    52    63
    78   120   138    51
    84    54    17    89
   103    44    97    69
    72   119    77    29
    30    62    25    66];

%number of text pixels
nmask = sum(mask(:)); % 13
% average text pixel luminance
avetxt = sum(mask(:).*imageY(:))/nmask; % 95.1538
% variance of the text pixel luminance
vtxt = sum(mask(:).*(imageY(:)-avetxt).^2)/nmask;% 786.5917
% number of background pixels
nbck = sum(1-mask(:)); % 19
% average background luminance
avebck = sum((1-mask(:)).*imageY(:))/nbck; % 60.1579
% variance of background luminance
vbck = sum((1-mask(:)).*(imageY(:)-avebck).^2)/nbck; % 551.5014
% proportion of text pixels
pT = nmask/(nmask+nbck); 
% To obtain the Global masking index of Scharff, Hill, and Ahumada (2000)
% pT = 0 ;
qT = 1-pT; % 0.4063 0.5937
% contrast of the text with respect to the background
CT = avetxt/avebck - 1;% 0.5817
% contrast of the text with respect to the image average
CA = qT*CT/(pT*CT+1); % 0.2794
% variance of the image contrast
vTB = ((pT*vtxt+qT*vbck)/avebck^2+pT*qT*CT^2)/(pT*CT+1)^2;% 0.1704
% image contrast adjusted by the masking variance relative to the 
%  contrast masking threshold C2
C2 = 0.05;
index = CA/sqrt(1+vTB/C2^2); %0.0336