%% Edge Detection Using Sobel Method
% Detect edges in a thumbnail image using the Sobel method.
% Import a test image.

frmInput = imread('rice.png');
[frmActivePixels,frmActiveLines] = size(frmInput);
figure
imshow(frmInput)
title 'Input Image'

%
% Create a serializer and specify the 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 an edge detection object with the default property values. The default detection method is Sobel.

edgeDetectSobel = visionhdl.EdgeDetector();

%
% Speed up simulation by enabling a simulation mode that uses code generation for the System object.

edgeDetectSobel.simulateUsing('Code generation');

%
% Serialize the test image using the object you created. pixIn is a vector of intensity values. ctrlIn is a vector of control signal structures. Preallocate vectors for the output signals.
% 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);

[~,~,numPixelsPerFrame] = getparamfromfrm2pix(frm2pix);
ctrlOut = repmat(pixelcontrolstruct,numPixelsPerFrame,1);
edgeOut = false(numPixelsPerFrame,1);

%
% For each pixel in the stream, compute whether it represents an edge.

for p = 1:numPixelsPerFrame  
   [edgeOut(p),ctrlOut(p)] = edgeDetectSobel(pixIn(p),ctrlIn(p));
end

%
% Create a deserializer with a format matching that of the serializer. Use the deserializer to convert the output pixel stream to an image frame.

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

% Copyright 2015 The MathWorks, Inc.