2014-08-27 219 views
1

我正試圖使用​​空間一階導數的l1範數計算matlab中圖像的總變差。代碼是波紋管:如何計算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

如果你想使它更快,我寧願像'A = abs(img(1:end-1,:) - img(2:end,:)); B = abs(img(:,1:end-1)-img(:,2:end)); sum(A(:))+ sum(B(:))' – matheburg 2014-08-27 12:01:00

回答

2

你不考慮第二昏暗的衍生品:只有

g = gradient(y) 

返回沿水平方向導數,以獲得微分沿着垂直方向,您也需要

[gx, gy] = gradient(y); 
+0

我編輯了問題並沿垂直方向添加了導數。代碼現在有效嗎? – Sebi 2014-08-27 12:24:21