im = imread('toygc.png');


[imh, imw, nb] = size(im); 

im=im2double(im);

im2var = zeros(imh, imw); 
im2var(1:imh*imw) = 1:imh*imw; 

A = sparse(imh*(imw-1)+(imh-1)*imw+1,max(max(im2var)));

output = zeros(imh,imw,nb);
output = double(output);

for color=1:nb
    s = im(:,:,color);
    e = 0;
    for y=1:imh
        for x=1:imw-1
            e = e+1;
            A(e, im2var(y,x+1))=1; 
            A(e, im2var(y,x))=-1; 
            b(e) = s(y,x+1)-s(y,x);
        end
    end

    for y=1:imh-1
        for x=1:imw
            e = e+1;
            A(e, im2var(y+1,x))=1; 
            A(e, im2var(y,x))=-1; 
            b(e) = s(y+1,x)-s(y,x);
        end
    end

    e=e+1; 
    A(e, im2var(1,1))=1; 
    b(e)=s(1,1); 
    b = double(b(:));

    v = A\b;

    for y=1:imh
        for x=1:imw
            output(y,x,color) = v(im2var(y,x));
        end
    end
end

imshow(output);