在Matlab中过滤包含NaN的图像?

时间:2015-04-23 19:53:53

标签: matlab filtering nan

我有一个代表一些数据的二维数组(doubles),其中有一堆NaNs。数据的等高线图如下所示:

prefiltered

所有白色空格均为NaNs,灰色菱形可供参考,填充轮廓显示我的数据形状。当我使用imfilt过滤数据时,NaNs显着地咀嚼数据,因此我们最终会得到类似的结果:

postfiltered

您可以看到支持集显着缩小。我无法使用它,因为它已经咀嚼了边缘上一些更有趣的变化(出于我的实验特定的原因,这些边缘很重要)。

是否有一个函数可以在NaNs的岛内进行过滤,它可以处理类似于矩形过滤窗口边缘的边缘,而不仅仅是消除边缘?有点像nanmean函数,除了卷积图像?

这是我的过滤器代码:

filtWidth = 7;
imageFilter=fspecial('gaussian',filtWidth,filtSigma);
%convolve them
dataFiltered = imfilter(rfVals,imageFilter,'symmetric','conv');

和绘制等高线图的代码:

figure
contourf(dataFiltered); hold on
plot([-850 0 850 0 -850], [0 850 0 -850 0], 'Color', [.7 .7 .7],'LineWidth', 1); %the square (limits are data-specific)
axis equal

Mathworks文件交换中有一些代码(ndanfilter.m)接近我想要的,但我相信它只会插入内部的<{1}}内容图像的图像,而不是显示这种岛型效应的数据。

注意:我刚刚发现了nanconv.m,它完全符合我的要求,使用非常直观(卷入图像,忽略NaNs,非常像NaN工作)。我已经将这部分作为我接受的答案,并将其与其他答案的表现进行了比较。

相关问题

Gaussian filtering a image with Nan in Python

4 个答案:

答案 0 :(得分:7)

我最终使用的技术是Matlab的File Exchange中的函数nanconv.m。它完全符合我的要求:它以一种忽略NaNs的方式运行过滤器,就像Matlab的内置函数nanmean那样。这很难从函数的文档中解读,这有点神秘。

以下是我如何使用它:

filtWidth = 7;
filtSigma = 5;
imageFilter=fspecial('gaussian',filtWidth,filtSigma);
dataFiltered = nanconv(data,imageFilter, 'nanout');

我正在粘贴下面的nanconv功能(由the BSD license覆盖)。当我有机会时,我会发布图片等,只是想发布我最终为所有对我所做的事情感到好奇的人做的事情。

与其他答案的比较

使用gnovice's solution结果看起来直观非常好,但是边缘有一些定量的昙花一现。在实践中,超出边缘的图像外推导致我的数据边缘有许多虚假的高值。

使用krisdestruction's suggestion用原始数据替换丢失的位,看起来也相当不错(特别是对于非常小的滤波器),但是(按设计)你最终会得到未经滤波的数据,这是一个问题对于我的申请。

<强> nanconv

function c = nanconv(a, k, varargin)
% NANCONV Convolution in 1D or 2D ignoring NaNs.
%   C = NANCONV(A, K) convolves A and K, correcting for any NaN values
%   in the input vector A. The result is the same size as A (as though you
%   called 'conv' or 'conv2' with the 'same' shape).
%
%   C = NANCONV(A, K, 'param1', 'param2', ...) specifies one or more of the following:
%     'edge'     - Apply edge correction to the output.
%     'noedge'   - Do not apply edge correction to the output (default).
%     'nanout'   - The result C should have NaNs in the same places as A.
%     'nonanout' - The result C should have ignored NaNs removed (default).
%                  Even with this option, C will have NaN values where the
%                  number of consecutive NaNs is too large to ignore.
%     '2d'       - Treat the input vectors as 2D matrices (default).
%     '1d'       - Treat the input vectors as 1D vectors.
%                  This option only matters if 'a' or 'k' is a row vector,
%                  and the other is a column vector. Otherwise, this
%                  option has no effect.
%
%   NANCONV works by running 'conv2' either two or three times. The first
%   time is run on the original input signals A and K, except all the
%   NaN values in A are replaced with zeros. The 'same' input argument is
%   used so the output is the same size as A. The second convolution is
%   done between a matrix the same size as A, except with zeros wherever
%   there is a NaN value in A, and ones everywhere else. The output from
%   the first convolution is normalized by the output from the second 
%   convolution. This corrects for missing (NaN) values in A, but it has
%   the side effect of correcting for edge effects due to the assumption of
%   zero padding during convolution. When the optional 'noedge' parameter
%   is included, the convolution is run a third time, this time on a matrix
%   of all ones the same size as A. The output from this third convolution
%   is used to restore the edge effects. The 'noedge' parameter is enabled
%   by default so that the output from 'nanconv' is identical to the output
%   from 'conv2' when the input argument A has no NaN values.
%
% See also conv, conv2
%
% AUTHOR: Benjamin Kraus (bkraus@bu.edu, ben@benkraus.com)
% Copyright (c) 2013, Benjamin Kraus
% $Id: nanconv.m 4861 2013-05-27 03:16:22Z bkraus $

% Process input arguments
for arg = 1:nargin-2
    switch lower(varargin{arg})
        case 'edge'; edge = true; % Apply edge correction
        case 'noedge'; edge = false; % Do not apply edge correction
        case {'same','full','valid'}; shape = varargin{arg}; % Specify shape
        case 'nanout'; nanout = true; % Include original NaNs in the output.
        case 'nonanout'; nanout = false; % Do not include NaNs in the output.
        case {'2d','is2d'}; is1D = false; % Treat the input as 2D
        case {'1d','is1d'}; is1D = true; % Treat the input as 1D
    end
end

% Apply default options when necessary.
if(exist('edge','var')~=1); edge = false; end
if(exist('nanout','var')~=1); nanout = false; end
if(exist('is1D','var')~=1); is1D = false; end
if(exist('shape','var')~=1); shape = 'same';
elseif(~strcmp(shape,'same'))
    error([mfilename ':NotImplemented'],'Shape ''%s'' not implemented',shape);
end

% Get the size of 'a' for use later.
sza = size(a);

% If 1D, then convert them both to columns.
% This modification only matters if 'a' or 'k' is a row vector, and the
% other is a column vector. Otherwise, this argument has no effect.
if(is1D);
    if(~isvector(a) || ~isvector(k))
        error('MATLAB:conv:AorBNotVector','A and B must be vectors.');
    end
    a = a(:); k = k(:);
end

% Flat function for comparison.
o = ones(size(a));

% Flat function with NaNs for comparison.
on = ones(size(a));

% Find all the NaNs in the input.
n = isnan(a);

% Replace NaNs with zero, both in 'a' and 'on'.
a(n) = 0;
on(n) = 0;

% Check that the filter does not have NaNs.
if(any(isnan(k)));
    error([mfilename ':NaNinFilter'],'Filter (k) contains NaN values.');
end

% Calculate what a 'flat' function looks like after convolution.
if(any(n(:)) || edge)
    flat = conv2(on,k,shape);
else flat = o;
end

% The line above will automatically include a correction for edge effects,
% so remove that correction if the user does not want it.
if(any(n(:)) && ~edge); flat = flat./conv2(o,k,shape); end

% Do the actual convolution
c = conv2(a,k,shape)./flat;

% If requested, replace output values with NaNs corresponding to input.
if(nanout); c(n) = NaN; end

% If 1D, convert back to the original shape.
if(is1D && sza(1) == 1); c = c.'; end

end

答案 1 :(得分:3)

一种方法是在执行过滤之前使用scatteredInterpolant(或旧版MATLAB版本中的TriScatteredInterp)用最近邻插值替换NaN值,然后再用NaN值替换这些点。这类似于使用'replicate'参数过滤完整的2-D数组而不是'symmetric'参数作为imfilter的边界选项(即您正在复制而不是相反)反映锯齿状NaN边界的值。)

以下是代码的样子:

% Make your filter:
filtWidth = 7;
imageFilter = fspecial('gaussian', filtWidth, filtWidth);

% Interpolate new values for Nans:
nanMask = isnan(rfVals);
[r, c] = find(~nanMask);
[rNan, cNan] = find(nanMask);
F = scatteredInterpolant(c, r, rfVals(~nanMask), 'nearest');
interpVals = F(cNan, rNan);
data = rfVals;
data(nanMask) = interpVals;

% Filter the data, replacing Nans afterward:
dataFiltered = imfilter(data, imageFilter, 'replicate', 'conv');
dataFiltered(nanMask) = nan;

答案 2 :(得分:0)

好的,不使用你的情节功能,我仍然可以给你一个解决方案。您要做的是找到所有新的NaN并将其替换为原始未过滤的数据(假设它是正确的)。虽然没有过滤,但它比减少轮廓图像的域要好。

% Toy Example Data
rfVals= rand(100,100);
rfVals(1:2,:) = nan;
rfVals(:,1:2) = nan;

% Create and Apply Filter
filtWidth = 3;
imageFilter=fspecial('gaussian',filtWidth,filtWidth);
dataFiltered = imfilter(rfVals,imageFilter,'symmetric','conv');
sum(sum(isnan( dataFiltered ) ) )

% Replace New NaN with Unfiltered Data
newnan = ~isnan( rfVals) & isnan( dataFiltered );
dataFiltered( newnan ) = rfVals( newnan );
sum(sum(isnan( rfVals) ) )
sum(sum(isnan( dataFiltered ) ) )

使用以下代码检测新的NaN。您也可以使用xor函数。

newnan = ~isnan( rfVals) & isnan( dataFiltered );

然后,此行将dataFiltered中的索引设置为rfVals

中的值
dataFiltered( newnan ) = rfVals( newnan );

结果

从控制台中打印的行和我的代码中,您可以看到dataFiltered中NaN的数量从688减少到396,而NaNrfVals的数量也是如此

ans =
   688
ans =
   396
ans =
   396

替代解决方案1 ​​

您也可以通过指定较小的内核并在之后合并它来在边缘附近使用较小的过滤器,但如果您只想要使用最少代码的有效数据,我的主要解决方案将起作用。

替代解决方案2

另一种方法是使用零或某些常量填充/替换NaN值,以便它可以工作,然后截断它。但是对于信号处理/过滤,您可能需要我的主要解决方案。

答案 3 :(得分:-3)

只要滤波器相同,

nanfilter在过滤时与nanconv完全相同。如果在使用nanfilter之前获得nan值,然后将其添加到经过滤后的矩阵中,那么只要你使用选项&#39; nanout&#39;就可以获得与nanconv相同的结果。使用相同的过滤器。