%% Convert a Color Image to Grayscale
% This example shows how to convert pixel stream data to a different color space.
% Set the dimensions of the test image and load a color source image. Select a portion of the image matching the desired test size.

frmActivePixels = 64;
frmActiveLines = 48;
frmOrig = imread('fabric.png');
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',3,...
      'VideoFormat','custom',...
      'ActivePixelsPerLine',frmActivePixels,...
      'ActiveVideoLines',frmActiveLines,...
      'TotalPixelsPerLine',frmActivePixels+10,...
      'TotalVideoLines',frmActiveLines+10,...
      'StartingActiveLine',6,...     
      'FrontPorch',5);

%
% Create a color space converter object. Select a conversion from RGB to grayscale.

convertrgb2gray = visionhdl.ColorSpaceConverter(...
      'Conversion','RGB to intensity');

%
% Serialize the test image. pixIn is a numPixelsPerFrame-by-3 matrix. 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 convert each pixel in the stream to the new color space.

[~,~,numPixelsPerFrame] = getparamfromfrm2pix(frm2pix);
pixOut = zeros(numPixelsPerFrame,1,'uint8');
ctrlOut = repmat(pixelcontrolstruct,numPixelsPerFrame,1);
for p = 1:numPixelsPerFrame  
    [pixOut(p),ctrlOut(p)] = convertrgb2gray(pixIn(p,:),ctrlIn(p));
end

%
% Create a deserializer object with format matching that of the serializer. Convert the pixel stream to an image frame, and display the grayscale output 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.