python 为什么我的斑点(Lee滤波器)会增加噪声而不是减少噪声?

gcmastyq  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(204)

我根据这个研究了Lee过滤器:https://pro.arcgis.com/en/pro-app/3.0/help/analysis/raster-functions/speckle-function.htm
我想让它减少噪音,但它反而增加了噪音。
我有这个python函数来对图像应用lee滤镜:

from scipy.ndimage.filters import uniform_filter
from scipy.ndimage.measurements import variance
def leeFilter(img, size):
  img_mean = uniform_filter(img, (size, size))
  img_sqr_mean = uniform_filter(img**2, (size, size))
  img_variance = img_sqr_mean - img_mean**2
  overall_variance = np.var(img)

  img_weights = img_variance / (img_variance + overall_variance)
  img_output = img_mean + img_weights * (img - img_mean)
  return img_output

然后,我将其应用于我的图像如下:

currImg = cv2.imread(os.path.join(currPath,f'{i}.png'))
# Get red, green and blue channels
red = currImg[:,:,0]
green = currImg[:,:,1]
blue = currImg[:,:,2]
# Apply the filter
red = lee_filter(red,15)
green = lee_filter(green,15)
blue = lee_filter(blue,15)
# merge channels
currImg[:,:,0] = red
currImg[:,:,1] = green
currImg[:,:,2] = blue
cv2.imwrite(os.path.join(newPath,f'{i}.png'),currImg)

问题是,使用15的窗口大小,看起来它是增加而不是降低图像的噪声。下面是之前和之后的图像比较。
enter image description here

dw1jzc5e

dw1jzc5e1#

Cris关于估计的噪声水平是正确的,但主要问题是算术溢出-将计算应用于uint8元素的结果。
我们可以在lee_filter之前将输入转换为float32,并在lee_filter之后将输出转换回uint8
代码示例:

import cv2
import numpy as np
from scipy.ndimage.filters import uniform_filter
from scipy.ndimage.measurements import variance

def lee_filter(img, size):
    img_mean = uniform_filter(img, (size, size))
    img_sqr_mean = uniform_filter(img**2, (size, size))
    img_variance = img_sqr_mean - img_mean**2
    overall_variance = np.var(img)

    img_weights = img_variance / (img_variance + overall_variance)
    img_output = img_mean + img_weights * (img - img_mean)
    return img_output

currImg = cv2.imread('before.png')
# Get red, green and blue channels
red = currImg[:,:,0].astype(np.float32)  # Convert dtype from np.uint8 to np.float32
green = currImg[:,:,1].astype(np.float32)
blue = currImg[:,:,2].astype(np.float32)
# Apply the filter
red = lee_filter(red, 15)
green = lee_filter(green, 15)
blue = lee_filter(blue, 15)
# merge channels
currImg[:,:,0] = red
currImg[:,:,1] = green
currImg[:,:,2] = blue
currImg = currImg.round().clip(0, 255).astype(np.uint8)  # Convert from np.float32 to np.uint8 with rounding and clipping
cv2.imwrite('after.png', currImg)

之前(before.png):

之后(after.png):

相关问题