How to compute the horizontal and vertical gradients of a gray-scale image without the use of imgradientxy()

10 views (last 30 days)
Hi guys, I'm completely new to matlab and am having some troubles with getting a seemingly trivial part of an assignment. I need to be able to find the horizontal and vertical gradients of a gray-scale image without the use of matlab functions such as imgradientxy(). The kernal I am using to find gradient is (-1,0,1). My attempt was to use loops to loop through the location of each pixel and change them one by one like so:
original = imread('grayscale.jpg')
[x,y] = size(original)
hor_grad = zeros(x,y)
ver_grad = zeros(x,y)
for i=1:x
for j=2:y-1
hor_grad(i,j) = -1*original(i,j-1)+original(i,j+1)
end
end
for i=2:x-1
for j=1:y
ver_grad(i,j) = -1*original(i-1,j)+original(i+1,j)
end
end
imshow(hor_grad)
imshow(ver_grad)
However I quickly learned that this approach will not work. I am at a loss here. What is a concise way to do this?

Answers (1)

Arun Mathamkode
Arun Mathamkode on 19 Oct 2017
Although this is not the best way of doing it, should also work fine. Please convert the original image to double before processing to avoid errors due to integer precision.
original = imread('grayscale.jpg');
original=double(original);
[x,y] = size(original);
hor_grad = zeros(x,y);
ver_grad = zeros(x,y);
for i=1:x
for j=2:y-1
hor_grad(i,j) = -1*original(i,j-1)+original(i,j+1);
end
end
for i=2:x-1
for j=1:y
ver_grad(i,j) = -1*original(i-1,j)+original(i+1,j);
end
end
figure;imshow(hor_grad,[])
figure;imshow(ver_grad,[])

Community Treasure Hunt

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

Start Hunting!