%% Filter a Pixel-Stream
% This example implements a 2-D blur filter on a thumbnail image.
% Load the source image from a file. Select a portion of the image matching the desired test size.

frmOrig = imread('rice.png');
frmActivePixels = 64;
frmActiveLines = 48;
frmInput = frmOrig(1:frmActiveLines,1:frmActivePixels);
figure
imshow(frmInput,'InitialMagnification',300)
title 'Input Image'

%
% Create a serializer object and specify the 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 a filter object.

 filt2d = visionhdl.ImageFilter(...
          'Coefficients',ones(2,2)/4,...
          'CoefficientsDataType','Custom',...
          'CustomCoefficientsDataType',numerictype(0,1,2),...
          'PaddingMethod','Symmetric');

%
% Serialize the test image by calling the serializer object. pixIn is a vector of intensity values. ctrlIn is a vector of control signal structures.
% Note: This object 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);

%
% Prepare to process pixels by preallocating output vectors.

[~,~,numPixelsPerFrame] = getparamfromfrm2pix(frm2pix);
pixOut = zeros(numPixelsPerFrame,1,'uint8');
ctrlOut  = repmat(pixelcontrolstruct,numPixelsPerFrame,1);

%
% For each pixel in the padded frame, compute the filtered value. Monitor the control signals to determine latency of the object. The latency of a filter configuration depends on:
% The number of active pixels in a line.
% The size of the filter kernel.
% Optimization of symmetric or duplicate coefficients.

foundValIn = false;
foundValOut = false;
for p = 1:numPixelsPerFrame  
    if (ctrlIn(p).valid && foundValIn==0)
        foundValIn = p;
    end
    [pixOut(p),ctrlOut(p)] = filt2d(pixIn(p),ctrlIn(p));
    if (ctrlOut(p).valid && foundValOut==0)
        foundValOut = p;
    end
end
sprintf('object latency is %d cycles',foundValOut-foundValIn)

%
% Create a deserializer object with a format matching that of the serializer. Convert the pixel stream to an image frame by calling the deserializer object. Display the resulting image.

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

% Copyright 2012 The MathWorks, Inc.