Edge detection taking too long, Sobel method

6 views (last 30 days)
I must make an edge detection function using the sobel operator, this is what i have so far, but it takes too long so I've never been able to see if it actually works;
Workspace:
img = imread('image.png');
Function:
function edge = edgy(img)
[row, col]=size(img);
row=row-1;
col=col-1;
edge=zeros(row-1,col-1);
l=0;
a=0;
x=[-1, 0 1;-2, 0, 2;-1, 0, 1];
y=[1, 2, 1;0, 0, 0;-1, -2, -1];
img=double(img);
for ii=2:row
for jj=2:col
l=l+1;
a=a+1;
a1=ii-1;
a2=ii+1;
b1=jj-1;
b2=jj+1;
A=img(a1:a2,b1:b2);
Sx=sum(dot(A, x));
Sy=sum(dot(A, y));
B=double(Sx^2+Sy^2);
M=sqrt(B);
edge(l, a)=M;
end
end
edge=uint8(edg);
end
Workspace;
edg = edgy(img);
The tool which grades my code times out before it can actually get a result, so waiting for it to work isn't an option for me, does anybody have any idea of whats going wrong?

Answers (1)

Abhishek
Abhishek on 12 Mar 2025
Hi Edith,
I understand that you want to implement a MATLAB function to perform edge detection using the Sobel operator and it is taking too long to execute. There are two minor issues in the code:
  1. The variables ‘l’ and ‘a’, used to index the edge matrix, are not being reset correctly because of which the size of edge matrix is growing continuously. To resolve this, instead of creating separate variables, the loop index variables can be used directly to index the edge matrix, as shown below:
edge(ii-1, jj-1) = M;
2. The variable ‘edge’ is mistyped as ‘edg’ in the last line of the function. This should be corrected to:
edge = uint8(edge);
By making these modifications, the code will run correctly and efficiently. I hope this resolves your query!

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!