2014-08-27 5 views
1

Я пытаюсь вычислить полную вариацию изображения в matlab, используя норму 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?

Edit:

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

ответ

2

Вы не принимают во внимание производные на втором тусклым: только

g = gradient(y) 

возвращается производной по горизонтали, для того, чтобы получить производную по вертикальному размеру также необходимо

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

Я отредактировал вопрос и добавил производную по вертикальному направлению. Действительно ли код действителен? – Sebi