%% Demosaic a Bayer Pattern Image
% This example constructs full RGB pixel data from a Bayer pattern thumbnail image.
% Set the dimensions of the test image. Load the source image file. This image is in Bayer pattern: each pixel is represented by one value, alternating green values with red and blue values. Then select a portion of the image matching the desired test size. These offsets select the face of the woman in the image.

frmActivePixels = 256;
frmActiveLines = 192;
frmOrig = imread('mandi.tif');
frmInput = frmOrig(900:899+frmActiveLines, 2350:2349+frmActivePixels);
figure
imshow(frmInput)
title 'Input Image'

%
% Create a serializer object and specify size of the inactive pixel regions.

frm2pix = visionhdl.FrameToPixels(...
      'NumComponents',1,...
      'VideoFormat','custom',...
      'ActivePixelsPerLine',frmActivePixels,...
      'ActiveVideoLines',frmActiveLines,...
      'TotalPixelsPerLine',frmActivePixels+10,...
      'TotalVideoLines',frmActiveLines+10,...
      'StartingActiveLine',6,...     
      'FrontPorch',5);

%
% Create an interpolator object. Specify the sequence of color values matching the 2-by-2 pixels in the top-left corner of the image.

BayerInterpolator = visionhdl.DemosaicInterpolator(...
   'SensorAlignment', 'RGGB');

%
% Serialize the test image. pixIn is a vector of pixel values. ctrlIn is a vector of control signal structures.
% Note: This syntax runs only in R2016b or later. If you are using an earlier release, replace each call of an object with the equivalent step syntax. For example, replace myObject(x) with step(myObject,x).

[pixIn,ctrlIn] = frm2pix(frmInput);

%
% Set up variables, and generate the {R,G,B} triplet for each pixel in the stream. This example prints a progress message every 32 lines.

[pixels,lines,numPixelsPerFrame] = getparamfromfrm2pix(frm2pix);
ctrlOut  = repmat(pixelcontrolstruct,numPixelsPerFrame,1);
pixOut = zeros(numPixelsPerFrame,3,'uint8');
lineCount = 1;
for p = 1:numPixelsPerFrame 
    if ctrlIn(p).hEnd
         lineCount = lineCount+1;
         if mod(lineCount,32)==0
              fprintf('Processing... line %d\n',lineCount)
         end
    end
    [pixOut(p,:),ctrlOut(p)] = BayerInterpolator(pixIn(p),ctrlIn(p));
end

%
% Create a deserializer object with a format matching that of the serializer. Convert the pixel stream to an image frame, and display the result.

pix2frm = visionhdl.PixelsToFrame(...
      'NumComponents',3,...
      'VideoFormat','custom',...
      'ActivePixelsPerLine',frmActivePixels,...
      'ActiveVideoLines',frmActiveLines);
[frmOutput,frmValid] = pix2frm(pixOut,ctrlOut);
if frmValid
    figure
    imshow(frmOutput)
    title 'Output Image'
end

% Copyright 2012 The MathWorks, Inc.