%% Convert Between Full-Frame and Pixel-Streaming Data
% This example converts a custom-size grayscale image to a pixel stream. It uses the visionhdl.LookupTable object to obtain the negative image. Then it converts the pixel-stream back to a full-frame 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 size of 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 lookup table (LUT) object to generate the negative of the input image.

tabledata = linspace(255,0,256);
inverter = visionhdl.LookupTable(tabledata);

%
% 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 stream, look up the negative of the pixel value.

for p = 1:numPixelsPerFrame  
    [pixOut(p),ctrlOut(p)] = inverter(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 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.