python opencv 双边滤波

#双边滤波,代码实现
import numpy as np
import math
import cv2
def getClosenessHeight(sigma_g,H,W):
    r,c = np.mgrid[0:H:1,0:W:1]
    r-=(H-1)/2
    c-=(W-1)/2
    closeWeight = np.exp(-0.5*(np.power(r,2)+np.power(c,2))/math.pow(sigma_g,2))
    return closeWeight

def bfltGray(I,H,W,sigma_g,sigma_d):#sigma_g>1,sigma_d<1,效果比较好
    closenessWeight = getClosenessHeight(sigma_g,H,W) #构建空间距离权重模板
    #模板的中心位置
    cH =(H-1)/2
    cW =(W-1)/2
    rows,cols = I.shape
    #双边滤波后的结果
    bfltGrayImg = np.zeros(I.shape,np.float32)
    for r in range(rows):   
        for c in range(cols):
            pixel = I[r][c]
            #判断边界
            rTop =0 if r-cH<0 else r-cH
            rBottom = rows-1 if r+cH>rows -1 else r+cH
            cLeft =0 if c-cW<0 else c-cW
            cRight = cols-1 if c+cW > cols-1 else c+cW
            #权重模板作用区域
            region2=I[rTop:rBottom+1,cLeft:cRight+1]
            #构建灰度值相似性的权重因子
            similarityWeightTemp = np.exp(-0.5*np.power(region2-pixel,2.0)/math.pow(sigma_d,2))
            closenessWeightTemp = closenessWeight[rTop-r+cH:rBottom-r+cH+1,
                                                  cLeft-c+cW:cRight-c+cW+1]
            #两个权重模板相乘
            weightTemp = similarityWeightTemp*closenessWeightTemp
            #归一化权重模板
            weightTemp = weightTemp/np.sum(weightTemp)
            #权重模板盒对应的邻域值相乘求和
            bfltGrayImg[r][c] = np.sum(region2*weightTemp)

    return bfltGrayImg 


     
    


if __name__=="__main__":
    print('out data is:p383')
    image = cv2.imread('dayan.png',cv2.IMREAD_GRAYSCALE)
    cv2.imshow('img',image)
    #将灰度值归一化
    image = image /255.0
    #双边滤波
    bfltImage = bfltGray(image,33,33,19,0.2)
    #显示双边滤波的结果
    cv2.imshow('bilateralFiltering',bfltImage)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

 API:

在OpenCV中通过定义函数bilateralFilter和adaptiveBilateralFilter实现了双边滤波的功
能

 

posted @ 2024-04-07 15:54  txwtech  阅读(130)  评论(0编辑  收藏  举报