How to set a matrix element to indicate surrounding elements?

I have a matrix Xthat represents an image affected by noise. I also have a boolean matrix Mthat represents which pixels are affected by noise. I want to make each “damaged” pixel equal to the average of eight neighboring pixels.

Damaged pixels are guaranteed to always be surrounded by intact ones, and also none of the pixels at the borders of the image will be damaged. What function could I use to vectorize this version?

+5
source share
2 answers

This is probably not the most effective solution, but it should work.

N = size(M, 1);
target_ind = find(M);
offset = [-N-1, -N, -N+1, -1, 0, 1, N-1, N, N+1];

area_ind = bsxfun(@plus, offset, target_ind);
X(target_ind) = median(X(area_ind), 2);

, . , X .

I , target_ind area_ind :

for i = 1:size(X, 3)
    chan_offset = (i - 1)*size(X, 1)*size(X, 2) % Add the number of elements in previous channels to get indices in the current channel
    X(target_ind + chan_offset) = median(X(area_ind + chan_offset), 2);
end
+2

fixed = conv2 (image, [1 1 1; 1 0 1; 1 1 1]/8, "same")
# mask is a logical matrix for the corrupted pixels
image(mask) = fixed(mask)

: conv2. ​​ones (3) / 9 , 1/9 . , 0 ( ), - 1/8.

+4

All Articles