Reputation:
I have a grayscale image. I want to calculate Del for every pixel of image, where
del = sum(absoluteValue(anypixelInensity - it's 8 neighbors Pixel Intensity)
I = imread('crop.bmp');
%KERNEL
windowSize = 3;
kernel = -1 * ones(3,3);
del = abs(conv2(double(I), double(kernel), 'same'));
disp(I)
disp(del)
I want to implement it with matlab conv2
function. Which would subtract current pixel intensity from its neighbors and give the absolute sum.
for example:
10 2 3
12 15 7
4 5 6
del(1,1) = abs(10-2)+abs(10-12)+abs(10-15)
or del(2,2) = abs(15-10)+abs(15-2)+abs(15-3)+abs(15-12)+abs(15-7)+abs(15-4)+abs(15-5)+abs(15-6)
Upvotes: 1
Views: 431
Reputation: 16809
This one is a bit tricky because, as @AnderBiguri says, the abs
inside the kernel makes it nonlinear, so conv2
won't work.
You can, however, use nlfilter
with a custom function. (This implementation uses nansum
, which is in the Statistics Toolbox. If you don't have access to this function, I can give you an alternate function, it's just easier with nansum
.)
Another difficulty is that we have to handle the image borders in such a way that they don't mess up the sum. This means that we have handle the image padding ourselves. I've chosen to use nan
values to pad. I've also been lazy and assumed an odd value for windowSize
. If this is not always the case, we'll have to adjust the padding.
% windowSize assumed to be odd; window assumed to be square
windowSize = 3;
% pad the input image
% padsize is how far the window extends beyond anchor
padsize = floor(windowSize/2);
A = padarray(I, [padsize, padsize], nan);
% create an anonymous function for nlfilter to use
% calculate row/column number of anchor within its neighborhood
anchor = ceil(windowSize/2);
% subtract the anchor element from its neighbors
% then sum the neighbors *not* equal to NaN
% (value at anchor position will be 0)
f = @(x) sum(nansum(abs(x-x(anchor,anchor))));
% filter padded image, and then crop off the padding
del = nlfilter(A, [windowSize, windowSize], f);
del = del(1+padsize:end-padsize, 1+padsize:end-padsize);
Upvotes: 1
Reputation: 35525
Yes, conv2
function does the convolution itself.
Given an image, A
and a kernel k
imout=conv2(A,k);
Will give you the convolution of the kernel over the image.
However, you may want to use imfilter
, as it s upports better different types of images.
Upvotes: 0