JmJ
JmJ

Reputation: 2098

Getting derivative of each pixel in image

I'm trying to calculate and store the derivatives of each pixel (i,j) of an image using ▽xf(i,j) = f(i,j)- f(i, j-1) at each pixel location, my problem is I'm having trouble implementing this in Matlab.

What I'm doing is loading an image, converting it to double from unsigned integer, initialising Dxf with zeroes and then attempting to get the derivatives of each pixel for every (i,j):

InputImage = imread([DataDir,'kodim09gray.png']); 

InputImage = double(InputImage);

[IHeight,IWidth] = size(InputImage);
Dxf = zeros(IHeight,IWidth);

for i = 1:IHeight
    for j = 1:IWidth
        Dxf(i,j) = InputImage(i,j) - InputImage(i,j-1);
    end
end

Unfortunately I get the following indexing error:

Attempted to access InputImage(1,0); index must be a positive integer or logical.

Error in GetXDerivative (line 13)
        Dxf(i,j) = InputImage(i,j) - InputImage(i,j-1);

I can see what's causing the issue as InputImage(1,0) can't exist, but I still can't think of how to resolve this without ruining the calculation needed at each pixel.

Upvotes: 0

Views: 370

Answers (2)

Jias
Jias

Reputation: 174

You'll have to decide what it means to take the derivative at the edge of an image. Typically f' can only be defined where f is continuous. Consider f(x) = |x|. The derivatives at x=1 and x=-19584 are defined but not at x=0. The edge of the image is similarly not continuous as j=0 does not exist.

I would think the best option would be to make Dxf smaller in the x direction so definitions exist for all pixels. Similarly, the range of DDxf would be even smaller.

Alternatively, you could decide that Dxf(1,1) should be white or black.

Upvotes: 0

knedlsepp
knedlsepp

Reputation: 6084

There are plenty of ways to do this. Here are two:

n = size(InputImage,1);
%// Method 1
Dxf = [nan(n,1), diff(InputImage,1,2)]
%// Method 2
Dxf = [nan(n,1), conv2(InputImage,[1,-1],'valid')]

A quick fix for your code would be to start your loop at 2:

for j = 2:IWidth

You will however have zeros in your first column, which are not correct, as they should be undefined.

Upvotes: 1

Related Questions