Edge detection using sobel operator

Can anyone point out what's causing the error in the code below?
Below is the code for detecting edge using sobel operator.
Thank you for your time and effort in advance.
function output = edgy(a)
a = double(a);
[row col] = size(a);
My = [-1 -2 -1;0 0 0;1 2 1];
Mx =[-1 0 1;-2 0 2;-1 0 1];
a3 =zeros(row,col);
for i =1:row-2
for j=1:col-2
Gx = sum(sum(Mx.*a(i:i+2, j:j+2)));
Gy = sum(sum(My.*a(i:i+2, j:j+2)));
filtered_image(i,j) = sqrt(Gx.^2 + Gy.^2);
end
end
filtered_image = uint8(filtered_image);
thresholdvalue =100;
output = max(filtered_image,thresholdvalue);
end

6 Comments

you need to deal with the edges: filtered_image offsets everything by 1, so your output image will be undefined (I guess zero?) along the top and left edges and have an extra row and column on the bottom and right. But the second error is confusing, why your output has 497 rows whereas the image has 351...
Milind Amga
Milind Amga on 8 Oct 2020
Edited: Milind Amga on 8 Oct 2020
@J. Alex Lee
I tried removing the +1 from the filtered_image in for loop but that throws back an error saying that output value is not correct.
Now, I updated the post with the original question, updated the code and error too.
Can you please take a look at it again.
And sorry for the misinformation earlier :)
then it may just be about your algorithm. have you searched TMW docs for "sobel edge detection"? matlab has very high level functions to achieve things like this - so it's not really clear to me how valuable this exercise is as a CODY challenge (is this a cody challenge?).
If you want to really learn about this method, I would look at the image processing toolbox, and do a deeper comparison of the results of your code versus what matlab canned edge detector returns. That is the more valuable feedback than "it's not right".
@J. Alex Lee Thank you for your feedback. I will dig deeper into the method. This is an assignment of online course :)
Try imfilter().
Ah ok. If you have access to full matlab (image processing toolbox), look into imfilter() as Image Analyst suggests, but also imgradientxy(). Then later you can look into conv2().

Sign in to comment.

Answers (0)

Asked:

on 8 Oct 2020

Commented:

on 9 Oct 2020

Community Treasure Hunt

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

Start Hunting!