function [ rgb ] = nhkBilinear_CFA4x2( sensorImage, isa )
%User defined bilinear demosaicking routine
%
%  [ rgb ] = myBilinear( sensorImage, isa )
%
% Purpose:
%
%   This file illustrates how to write a custom demosaic algorithm file.
%
%   The demosaic algorithm call has two arguments.  The first,sensorImage,
%   is an RGB image (row x col x nPlanes) defining the image sensor data.
%   In each of the color planes, many of the values are 0 corresponding to
%   the missing data.
%
%   The second, isa, is the entire image sensor array structure.  You
%   should use the various sensorGet() options to identify information
%   about the sensor that you need to implement the demosaic algorithm.
%
%   In this example, for the bilinear algorithm, we need to know the
%   positions of the three types of sensors.  We read the color filter
%   array pattern from the isa structure.  Using this information, and the
%   image data in sensorImage, we apply the algorithm.
%
%   The return argument, rgb, is (row x col x nPlanes) with the missing
%   data filled in.
%
%    This function is included only to illustrate the API.
%
% Example: 
%
% Copyright ImagEval Consultants, LLC, 2005.

% You can use the sensorGet routine to obtain information about the sensor.
% The most likely information you will need is the position of the
% different color filters in the pattern.
cfaPattern = sensorGet(isa,'pattern');

% We will need to know the number of color planes.
nPlanes = size(sensorImage,3);

% There are three basic configurations for a color sensor in a 2x2 block.
% The sensor can occupy a single location, a pair of locations in a common row/col,
% or a pair of locations in diagonal positions.  We use the appropriate
% linear interpolation kernel in each of these cases.

for ii=1:nPlanes
    
    % Read the data in the first plane
    thisPlane = sensorImage(:,:,ii);
    
    % Find the positions in the 1x4 (instead of regular 2x2) bloack that contain this color image
    % plane
    
    %     pattern = ...
    %     [2, 1; 
    %     3, 2; 
    %     2, 3; 
    %     1, 2];
    % 1=R, 2=G, 3=B??

    l = (cfaPattern == ii);
    
    if ( l(1) == 2 & l(5) == 2) | (l(4) == 2 & l(8) == 2) 
        % If there are two positions at opposite corners, we apply this
        % convolution.  This is for the G sensor in a conventional Bayer array.
        rgb(:,:,ii) = conv2(thisPlane, [1/4; 1/4; 1/4; 1/4], 'valid');        
    elseif ( l(2) == 1 & l(7) == 1)
        % Otherwise it is one of the single sensors (usually R), and
        % we apply a different convolution
        rgb(:,:,ii) = conv2(thisPlane, [0 1/2; 0 0; 0 0; 1/2 0] , 'valid');
    elseif ( l(3) == 3 & l(6) == 3)
        % Otherwise it is one of the single sensors (usually B), and
        % we apply a different convolution
        rgb(:,:,ii) = conv2(thisPlane, [0 0; 1/2 0; 0 1/2; 0 0] , 'valid');
    end
end

return;
