我有一个X
表示受噪声影响的图像的矩阵。我还有一个布尔矩阵M
,表示哪些像素受噪声影响。我想要做的是将每个“损坏的”像素设置为其八个相邻像素的平均值。
损坏的像素保证总是被未损坏的像素包围,并且图像边界上的任何像素都没有损坏。我可以用什么函数来编写它的矢量化版本?
对于您的情况,这应该执行得相当快
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。
这可能不是最有效的解决方案,但它应该可以工作。
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