天天看點

聯合雙邊濾波

#聯合雙邊濾波
#圖像高斯平滑,近似性權重由高斯平滑後确定
import numpy as np
from scipy import signal
import cv2,math
def getClosenessWeight(sigma_g,H,W):
    r,c = np.mgrid[0:H:1,0:W:1]
    r=r.astype(np.float64)
    c=c.astype(np.float64)
    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 jointBLF(I,H,W,sigma_g,sigma_d,borderType=cv2.BORDER_DEFAULT):
    closenessWeight = getClosenessWeight(sigma_g,H,W)
    #高斯平滑
    Ig = cv2.GaussianBlur(I,(W,H),sigma_g)
    cH = int((H-1)/2)
    cW = int((W-1)/2)
    Ip = cv2.copyMakeBorder(I,cH,cH,cW,cW,borderType)
    Igp = cv2.copyMakeBorder(Ig,cH,cH,cW,cW,borderType)
    rows,cols = I.shape
    i,j = 0,0
    jblf = np.zeros(I.shape,np.float64)
    for r in np.arange(cH,cH+rows,1):
        for c in np.arange(cW,cW+cols,1):
            pixel = Igp[r][c]
            rTop,rBottom = r-cH,r+cH
            cLeft,cRight = c-cW,c+cW
            region = Igp[rTop:rBottom+1,cLeft:cRight+1]
            similarityWeight = np.exp(-0.5*np.power(region-pixel,2.0)/math.pow(sigma_d,2.0))
            weight = closenessWeight*similarityWeight
            weight = weight/np.sum(weight)
            jblf[i][j] = np.sum(Ip[rTop:rBottom+1,cLeft:cRight+1]*weight)
            j+=1
        j = 0
        i+=1
    return jblf
if __name__ =='__main__':
    I = cv2.imread('E:/sy2/5/img3.jpg',cv2.IMREAD_GRAYSCALE)
    cv2.imshow('I',I)
    fI = I.astype(np.float64)
    jblf = jointBLF(fI,33,33,7,2)
    jblf = np.round(jblf)
    jblf = jblf.astype(np.uint8)
    cv2.imshow('jblf',jblf)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
           
聯合雙邊濾波
聯合雙邊濾波