function [Pix_out] = scalarmedian3x3(Pix_in)
%
%SCALARMEDIAN3X3  Performs median filtering on the R and B planes in
%                 a 3x3 window, referenced to the G plane 
%
%   Usage: [Pix_out] = scalarmedian3x3(Pix_in)
%
%      Pix_out       = Filtered image 3D array output
%                      Valid range: 0 <= Pix_out(:,:,:) <= 255 (8 bits)
%
%      Pix_in        = RGB image 3D array input
%                      Valid range: 0 <= Pix_in(:,:,:) <= 255 (8 bits)
%
%   Assumptions: Pix_in has the following format -
%
%   d   Color Plane
%  --- -------------
%   1   R
%   2   G
%   3   B
%
%   Author:    Gary Embler
%   Email:     gary_embler@agilent.com
%   Date:      05/21/01
%   Reference: "Correlation-Based Color Mosaic Interpolation Using a
%              Connectionist Approach", G. Embler
%
%   Copyright (c) 2001 by Gary Embler
%

%======================================================================
% Initialization
%----------------------------------------------------------------------

[h, w, d]   = size(Pix_in);

%======================================================================
% G Pixels Pass-Through
%----------------------------------------------------------------------

Pix_out(:,:,2) = Pix_in(:,:,2);

%======================================================================
% Color Differences
%----------------------------------------------------------------------

Colordiff(:,:,1)  = Pix_in(:,:,1) - Pix_in(:,:,2);       % R - G

Colordiff(:,:,2)  = Pix_in(:,:,3) - Pix_in(:,:,2);       % B - G

%======================================================================
% G-Referenced R, B Median Filtering
%----------------------------------------------------------------------

Pix_out(:,:,1)    =...                                   % R
   clip(  fix(medfilt2(Colordiff(:,:,1))...              % R - G
        + Pix_in(:,:,2)), 0, 255);                       % G

Pix_out(:,:,3)    =...                                   % B
   clip(  fix(medfilt2(Colordiff(:,:,2))...              % B - G
        + Pix_in(:,:,2)), 0, 255);                       % G

%======================================================================
