如何在matlab中计算图像的总变差

时间:2014-08-27 11:21:51

标签: image matlab image-processing variations

我正在尝试使用空间一阶导数的l1范数来计算matlab中图像的总变差。代码如下:

function TV = compute_total_variation1(y)
% y is the image
nbdims = 2;

% check number of channels in an image
if size(y,1)==1 || size(y,2)==1
    % we have one dimension
    nbdims = 1;
end

if size(y,1)>1 && size(y,2)>1 && size(y,3)>1
    % we have three dimensions
    nbdims = 3;
end

if nbdims==1
    TV = sum(abs(diff(y)));
    return;
end

% the total variation weight is 1
% weight_tv = ones(size(y));

g = gradient(y);
% compute using the l1 norm of the first order derivatives
TV = sum( abs(g),nbdims+1);

% TV = TV .* weight_tv;
TV = sum(TV(:));

我是否使用l1标准正确计算总变差?

修改

function TV = compute_total_variation1(y)
% y is the image
nbdims = 2;

% check number of channels in an image
if size(y,1)==1 || size(y,2)==1
    % we have one dimension
    nbdims = 1;
end

if size(y,1)>1 && size(y,2)>1 && size(y,3)>1
    % we have three dimensions
    nbdims = 3;
end

if nbdims==1
    TV = sum(abs(diff(y)));
    return;
end

% the total variation weight is 1
% weight_tv = ones(size(y));

[gx gy] = gradient(y);
% compute using the l1 norm of the first order derivatives
% horizontal
TVgx = sum( abs(gx),nbdims+1);
% vertical
TVgy = sum( abs(gy),nbdims+1);
% TV = TV .* weight_tv;
TV = sum(TVgx(:)) + sum(TVgy(:));

1 个答案:

答案 0 :(得分:2)

你没有考虑第二个暗淡的衍生物:

g = gradient(y)

只返回水平维度的导数,为了得到垂直维度的导数,你需要

[gx, gy] = gradient(y);