% Edge Detection
% Justin Weight
% Spring 2017
% Utah State University

% Include an image in the same folder named "image.png"
% Note: The image needs to have pretty distinct lines in order to work
% properly
% The program will produce a wav file named "vector.wav" that can be
% manipulated in Audacity or any other audio editing program
% Note the program produces the audio for one loop which may be less than
% 1/100 of a second.  You will need to either loop the audio file or copy
% and the signal multiple times to get the desired length.
function EdgeDetect()

close all;
clear all;

Irgb = imread('image.png');
Igray = 0.2989*Irgb(:,:,1)+0.5870*Irgb(:,:,2)+0.1140*Irgb(:,:,3);
figure
image(Igray,'CDataMapping','scaled');
colormap('gray')
title('Input Image in Grayscale')

I = double(Igray);
classType = class(Igray);
scalingFactor = double(intmax(classType));
I = I/scalingFactor;

[~, threshold] = edge(I, 'sobel');
fudgeFactor = .5;
BWs = edge(I,'sobel', threshold * fudgeFactor);
figure, imshow(BWs), title('binary gradient mask');

[B,L,N,A] = bwboundaries(I,'holes');

imshow(I); hold on;
title('Different parts detected')
colors=['b' 'g' 'r' 'c' 'm' 'y'];
for k=1:length(B),
  boundary = B{k};
  cidx = mod(k,length(colors))+1;
  plot(boundary(:,2), boundary(:,1),...
       colors(cidx),'LineWidth',2);

  %randomize text position for better visibility
  rndRow = ceil(length(boundary)/(mod(rand*k,7)+1));
  col = boundary(rndRow,2); row = boundary(rndRow,1);
  h = text(col+1, row-1, num2str(L(row,col)));
  set(h,'Color',colors(cidx),'FontSize',14,'FontWeight','bold');
end


%Scaling Factor
count = 0;
%Switch the following numbers to what you want from the Edge Detect Screen
for i=[1 2 3 4 7 8 9 10 11 12 13]
    xy=B{i,1};
    
    x=xy(:,2);    
    y=-xy(:,1);
    
    for j=1:length(x)
        k = count + j;
        x1(k,1)=x(j);
        y1(k,1)=y(j);
    end
    count = count + length(x);    
end
%Downsample
%Too many samples will cause the image to be skewed
% The higher N the less amount of samples
N=1;
x1 = x1(1:N:end);
y1 = y1(1:N:end);

%Scale signal to between -1 and 1
x1 = 2*(x1 - min(x1))/(max(x1) - min(x1)) - 1;
y1 = 2*(y1 - min(y1))/(max(y1) - min(y1)) - 1;
signal = horzcat(x1,y1);

filename = 'vector.wav';
Fs = 44100;
audiowrite(filename,signal,Fs);








