Problem in sobel edge detection method

1 view (last 30 days)
Emre Can Ertekin
Emre Can Ertekin on 25 Jun 2018
Answered: Abhishek on 11 Mar 2025
I need to make a sobel edge detection. I shouldn't use the shortcuts of MATLAB functions. I couldn't run the code and i can't find my error. I get a white screen as a output. I think that i didn't make the non maximum suppression so i get the error. Thanks for helping
orginal=imread('img.jpg');
orgdoub=im2double(orginal);
gray_img=rgb2gray(orgdoub);
kx=[-100,-200,-100;0 0 0 ; 100 200 100];
ky=[-100 0 100; -200 0 200 ; -100 0 100];
H= conv2(gray_img,kx,'same');
V= conv2(gray_img, ky, 'same');
E=sqrt(H.^2+V.^2);
filterimg=imfilter(gray_img,E);
edgeimg=edge(filterimg);
figure(1);
imshow(filterimg);
title('gradyantlı');
figure(2);
sob = edge(gray_img,'sobel');
imshow(sob);
title('With using sobel function ');

Answers (1)

Abhishek
Abhishek on 11 Mar 2025
Hello Emre,
I understand that you want to perform ‘Sobel’ edge detection on an image without using the inbuilt MATLAB function but are encountering issues.
Here are some observations from the shared code:
  • The white screen issue is likely due to passing the wrong variable to the “imshow" function.
  • Since, the edge detection should be performed without using MATLAB's built-in functions, the use of the “edge” function is unnecessary.
  • The kernel used is scaled by 100, which affects the magnitude of the gradient but not the direction. If focus is on relative strength of the edges, use of kernel without scaling is recommended.
  • The use of function “imfilter” is not required for this task.
Considering the above points, the following code produces the correct output:
orginal = imread('football.jpg'); % Read the image
orgdoub = im2double(orginal); % Convert the image to double
gray_img = rgb2gray(orgdoub); % Convert RGB image to grayscale
kx = (1/100).*[-100, -200, -100; 0, 0, 0; 100, 200, 100]; % Sobel filer for horizontal edges
ky = (1/100).*[-100, 0, 100; -200, 0, 200; -100, 0, 100]; % Sobel filer for vertical edges
% Apply the filters
H = conv2(gray_img, kx, 'same');
V = conv2(gray_img, ky, 'same');
E = sqrt(H.^2 + V.^2); % Compute magnitude of the gradient
threshold = 0.5; % Threshold for edge detection
figure(1);
imshow(E>threshold);
title('Sobel Edge Detection');
Please note that the variable 'threshold' can be varied to detect fewer or more edge pixels, respectively.
Hope this helps.

Products

Community Treasure Hunt

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

Start Hunting!