How can I set the value of border pixels after applying a sliding window operation?

夙愿已清 提交于 2019-12-11 13:27:07

问题


After applying a sliding-window operation like stdfilt(i, ones(5, 5)) to an image in MATLAB, I would like to set the border pixels, the pixels calculated using padding, to NaN to mark them as meaningless. In this example, I would set the outermost two rows and columns to NaN. Given an M * M window, how can I set this border that is (M - 1) / 2 pixels wide to a specific value?


回答1:


Suppose, r is the matrix (result of stdfilt). Here is an example how to assign NaN to borders. In general, you need to specify the correct index.

>> r = rand(4)

r =

    0.8147    0.6324    0.9575    0.9572
    0.9058    0.0975    0.9649    0.4854
    0.1270    0.2785    0.1576    0.8003
    0.9134    0.5469    0.9706    0.1419

>> r([1, end], :) = nan

r =

       NaN       NaN       NaN       NaN
    0.9058    0.0975    0.9649    0.4854
    0.1270    0.2785    0.1576    0.8003
       NaN       NaN       NaN       NaN

>> r(:, [1, end]) = nan

r =

       NaN       NaN       NaN       NaN
       NaN    0.0975    0.9649       NaN
       NaN    0.2785    0.1576       NaN
       NaN       NaN       NaN       NaN

update: in general, since image is a matrix, your question is "how to set certain matrix values?". The answer is: "using matrix's indexes". There are many ways to do it (for example, by building matrix of indexes, logical mask, or using rows/columns coordinates). The decision what method to use usually depends on the speed of the operation for this specific task. For example, if you need to replace zeros by NaN's, it's faster to use a logical mask: r(r == 0) = nan, and so on.




回答2:


First find where are NaN's in your matrix. Assume your image Name is A.

a = isnan(A);

This will create matric a with 0 at locations that are numbers, and 1 at locations that are NaN. Then find the location of Nan elements as:

[x,y]=find(a==1);

Then replace them with value V as:

for i=1:length(x)
   A(x(i),y(i)) = V;
end



回答3:


This will do the job, but this seems like the sort of function which would be in the image processing toolbox.

mask = logical(ones(size(i)));
width = (m - 1) / 2;
mask(width + 1:size(i, 1) - width, width + 1:size(i, 2) - width) = 0;
i(mask) = NaN;


来源:https://stackoverflow.com/questions/13336113/how-can-i-set-the-value-of-border-pixels-after-applying-a-sliding-window-operati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!