Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %318810637 Perov Danny
- %318455813 Eden Klainer
- %
- %The function finds the edges in the image using the Canny edge detector.
- %Input: grayscale image
- %Output: binary image with only the images.
- function [newImg] = edgeDetect(img)
- %Smooth the image.
- img = conv2(img, [1,2,1; 2, 4, 2; 1, 2, 1] / 16, 'same');
- %Find the gradient.
- Sx = conv2(img, [1, -1], 'same');
- Sy = conv2(img, [1; -1], 'same');
- S = sqrt(Sx.^2 + Sy.^2);
- teta = Sy ./ Sx;
- [rows, cols] = size(img);
- tempImg = S;
- %Go over all the pixels, and compare each and one of them to its neighbours
- for r = 1 : rows
- for c = 1 : cols
- if(isnan(teta(r, c)) == 1 || isinf(teta(r, c)) == 1 || r == 1 || c == 1 || r == rows || c == cols)
- tempImg(r, c) = 0;
- continue;
- end
- if(-0.4142 <= teta(r, c) && teta(r, c) <= 0.4142)
- if(S(r, c) <= S(r, c - 1) || S(r, c) <= S(r, c + 1))
- tempImg(r, c) = 0;
- end
- elseif(0.4142 <= teta(r, c) && teta(r, c) <= 2.4142)
- if(S(r, c) <= S(r - 1, c + 1) || S(r, c) <= S(r + 1, c - 1))
- tempImg(r, c) = 0;
- end
- elseif(abs(teta(r, c)) >= 2.4142 )
- if(S(r, c) <= S(r - 1, c) || S(r, c) <= S(r + 1, c))
- tempImg(r, c) = 0;
- end
- elseif(-2.4142 <= teta(r, c) && teta(r, c) <= -0.4142)
- if(S(r, c) <= S(r - 1, c - 1) || S(r, c) <= S(r + 1, c + 1))
- tempImg(r, c) = 0;
- end
- end
- end
- end
- Tmax = 17/255;%43 / 255; % TODO decide upon values
- Tmin = 5/255;%10 / 255;
- %Create matrices which contain values above the given thresholds
- aboveTMax = (tempImg > Tmax);
- aboveTMin = (tempImg > Tmin);
- %Create a matix in which a strong cell has value 2, and a weak one has value 1
- aboveThreshold = aboveTMax + aboveTMin;
- finalEdges = aboveTMax;
- counter = 1;
- currentPixels = [];
- %Check each of the cells to find the edges by using the local patch
- for r = 2 : rows - 1
- for c = 2 : cols - 1
- if(aboveThreshold(r, c) ~= 1)
- continue;
- end
- localPatch = aboveThreshold(r - 1 : r + 1, c - 1 : c + 1);
- patchMax = max(max(localPatch));
- if(patchMax == 2)
- currentPixels(counter, 1) = r;
- currentPixels(counter, 2) = c;
- counter = counter + 1;
- finalEdges(r, c) = 1;
- end
- end
- end
- counter = 1;
- %Set the final edge values in the result matrix.
- while(size(currentPixels, 1) > 0)
- newPix = [];
- for i = 1 : size(currentPixels, 1)
- r = currentPixels(i, 1);
- c = currentPixels(i, 2);
- if r ~= 0 && c ~= 0
- for dr = -1 : 1
- for dc = -1 : 1
- if (dr == 0 && dc == 0)
- continue;
- end
- r2 = r + dr;
- c2 = c + dc;
- if (aboveThreshold(r2, c2) == 1 && finalEdges(r2, c2) == 0)
- newPix(counter, 1) = r2;
- newPix(counter, 2) = c2;
- counter = counter + 1;
- finalEdges(r2, c2) = 1;
- end
- end
- end
- end
- end
- currentPixels = newPix;
- end
- newImg = finalEdges;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement