I'm working on a script detecting edges of an image.
Here is the script:
clear all; close all; clc;
c = rgb2gray(imread('image_S004_I0004.jpg'));
c = double(c);
k = imnoise(c, 'salt & pepper', 0.01);
gg = [-1 0 1;-2 0 2; -1 0 1];
gh = gg';
grad_g = conv2(k, gg);
grad_h = conv2(k, gh);
grad = sqrt(grad_g.^2 + grad_h.^2);
[r s] = size(grad);
T = 80;
for ii = 1:r
for jj = 1:s
if grad(ii, jj) < T
thresh_grad(ii, jj) = 0;
else
thresh_grad(ii, jj) = 1;
end
end
end
figure()
subplot(121); imshow(uint8(c));
subplot(122); imshow(thresh_grad);
Here is what I always get:
On the left is an original image, on the right should be an image with detected edges (as you can see in the script, I have implemented some noise on the image - has to be there). But I get literally nothing, not matter what the value of threshold T is.
Could you please help me to find my mistake?
The problem in your code is right before you apply the noise. You are casting the image to
double
prior to callingimnoise
. By doing this,double
precision images are assumed to have a dynamic range of[0,1]
and so the output ofimnoise
would be clipped to the[0,1]
range. This means that your threshold of80
would therefore be unsuitable because there will never be any gradient values that would exceed the value of 80 so everything is visualized as black.In addition,
thresh_grad
is not defined and it's recommended you pre-allocate the image prior to using it. Simply dothresh_grad = zeros(size(grad));
prior to the doublefor
loop.As such, call
double
after you make the call toimnoise
which would make the image still be inuint8
and then convert todouble
for the purposes of convolution. By doing this I managed to get output. I don't have access to your image, but I used thecameraman.tif
image that's built-into MATLAB's image processing toolbox.Therefore:
I get:
As for future development, I recommend you use
im2double
to actually convert the images todouble
precision, which would also convert the data into a[0,1]
range. You would thus need to change the threshold from80
to80/255
as the threshold of80
was originally designed foruint8
images.Finally, when you show the original image you can get rid of the
uint8
casting.For completeness: