加权中值滤波matlab
时间: 2023-09-09 10:13:07 浏览: 121
下面是一个简单的加权中值滤波的 Matlab 代码示例:
```matlab
function outImg = weightedMedianFilter(inImg, maskSize, weights)
% Convert the input image to double precision
inImg = im2double(inImg);
% Determine the padding required to apply the mask
padSize = floor(maskSize/2);
% Pad the image with zeros
paddedImg = padarray(inImg, [padSize padSize], 'symmetric');
% Initialize the output image
outImg = zeros(size(inImg));
% Loop through the pixels in the input image
for i = 1:size(inImg,1)
for j = 1:size(inImg,2)
% Extract the neighborhood around the current pixel
neighborhood = paddedImg(i:i+maskSize-1, j:j+maskSize-1);
% Flatten the neighborhood into a vector
neighborhoodVec = neighborhood(:);
% Sort the vector in ascending order
sortedVec = sort(neighborhoodVec);
% Calculate the weighted median
cumWeights = cumsum(weights(sortedVec+1));
idx = find(cumWeights >= cumWeights(end)/2, 1, 'first');
outImg(i,j) = sortedVec(idx);
end
end
% Convert the output image back to the same class as the input image
outImg = cast(outImg, class(inImg));
end
```
其中,`inImg` 是输入图像,`maskSize` 是滤波器的大小,`weights` 是一个权重向量,用于计算加权中值。在上述代码中,我们首先将输入图像转换为双精度格式,并使用 `padarray` 函数对图像进行零填充,以便能够在边缘处也能进行滤波。接着,我们循环遍历图像中的每个像素,提取以该像素为中心的邻域,并将其展平为一个向量。然后,我们按升序对向量进行排序,并使用给定的权重向量计算加权中值。最后,我们将输出图像转换回与输入图像相同的格式。
阅读全文