import cv2
import numpy as np
import sys
def denoise_bifilter(img):
#some important parameters
radius = 5
dist_lambda = 2
range_lambda = 100
shape = img.shape;
if img.ndim != 2:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img = np.float32(img)
#1--distance filter
distflt = np.zeros((2*radius + 1, 2*radius+1), float)
for y in range(distflt.shape[0]):
for x in range(distflt.shape[1]):
dx = x - radius
dy = y - radius
d = dx * dx + dy * dy
d = d / (2 * dist_lambda * dist_lambda)
distflt[y,x] = np.exp(-d)
result = np.zeros(img.shape)
#2--sliding window
range_lambda2 = np.power(range_lambda,2) * 2
lut255 = range(256)
for k in range(256):
lut255[k] = np.exp(-np.power(k,2) / range_lambda2)
for y in range(shape[0]):
for x in range(shape[1]):
thresh = img[y,x]
w = 0
m = 0
for i in range(distflt.shape[0]):
for j in range(distflt.shape[1]):
dx = j - radius
dy = i - radius
if y + dy < 0 or y + dy >= shape[0] or x + dx < 0 or x + dx >= shape[1]:
continue
w1 = distflt[i,j]
idx = np.int32(np.abs(img[y + dy, x + dx] - thresh))
w2 = lut255[idx]
w = w + w1 * w2
m = m + w1 * w2 * img[y + dy, x + dx]
result[y,x] = m / w
mat255 = np.ones(img.shape,float) * 255
result = np.minimum(mat255, result)
result = np.uint8(result)
return result
def imnoise(img):
if img.ndim != 2:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
noiseimg = np.random.normal(0, 50, img.shape)
noiseimg = noiseimg + np.float32(img)
mat255 = np.ones(img.shape, float) * 255
mat0 = np.zeros(img.shape, float)
noiseimg = np.minimum(mat255, noiseimg)
noiseimg = np.maximum(mat0, noiseimg)
noiseimg = np.uint8(noiseimg)
return noiseimg
if __name__=="__main__":
img = cv2.imread(sys.argv[1])
cv2.imshow("src", img)
cv2.waitKey(-1)
noiseimg = imnoise(img)
cv2.imshow("noise", noiseimg)
cv2.waitKey(-1)
cleanimg = denoise_bifilter(noiseimg)
cv2.imshow("clean", cleanimg)
cv2.waitKey(-1)
image denoise with bifilter
最新推荐文章于 2024-02-21 11:50:13 发布