Clear Filters
Clear Filters

How to get the thresholded gradient of an image?

7 views (last 30 days)
I have an image and I want to get the thresholded gradient of the smoothed image the average filter is 5*5 but I cant find out how to get the gradient because the command imgradient doesnt work for my matlab version R2011b
Here is my code
img = mat2gray( imread ('image')); %to make it grayscale
smooth = imfilter (img, (ones (5)/25)); %average filter 5*5

Answers (2)

Image Analyst
Image Analyst on 3 Jan 2014
You can use imfilter or conv2(). Either way, you'll need some negative weights to get the gradient, as I'm sure you know. Try my dog filter (Difference of Gaussians), attached below in blue text. The "harshest" gradient is the Laplacian which is just
kernel = [-1, -1, -1; -1, 8, -1; -1, -1, -1];
laplacianImage = conv2(double(grayImage), kernel);
imshow(laplacianImage, []);
You can get smoother gradients using the dog filter or smoother kernels, for example the Sobel filter.
  8 Comments
Image Analyst
Image Analyst on 10 Jan 2021
It would be like this. Please "Vote" for my Answer if it helped you.
Of course my answer also worked. The Sobel is an edge detector which is not like a true gradient like the Laplacian, but it does find edges pretty well. Canny is another one like that.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fprintf('Beginning to run %s.m ...\n', mfilename);
grayImage = imread('coins.png');
subplot(2, 2, 1);
imshow(grayImage);
title('Original Image')
% Calculate the x- and y-directional gradients. By default, imgradientxy uses the Sobel gradient operator.
[Gmag, Gdir] = imgradient(grayImage);
% Display the directional gradients.
subplot(2, 2, 2);
imshow(Gmag, []);
title('Magnitude using Sobel Method')
threshold = 0.15 * max(Gmag(:))
binaryImage = Gmag > threshold;
subplot(2, 2, 3);
imshow(binaryImage, []);
caption = sprintf('Thresholded at %.1f', threshold);
title(caption)
fprintf('Done running %s.m.\n', mfilename);

Sign in to comment.


Youssef  Khmou
Youssef Khmou on 3 Jan 2014
you can try this essay :
I=im2double(imread('image1.tif'));
k=-1*ones(5);k(3,3)=23;
J=conv2(I,k);
figure, imshow(J)

Community Treasure Hunt

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

Start Hunting!