image denoise with bifilter

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)
        	
	

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值