一、基礎介紹
雙邊濾波器是一種局部濾波器,其能夠做到平滑圖像的同時保留圖像的邊緣信息,被廣泛用於圖像和視頻處理領域。其原理是基於圖像中像素點的相似度來確定權值,使得相似的像素點權值更大,從而達到平滑圖像的效果同時不模糊圖像的邊緣信息。
二、雙邊濾波器算法
雙邊濾波器算法包含以下幾個步驟:
1. 對於每一個像素點,選取一個窗口,窗口的大小和形狀可以自行定義,一般情況下取窗口為正方形或圓形。
for i in range(x_min, x_max): for j in range(y_min, y_max): window = func_get_window(i, j, image, window_size)
2. 利用高斯函數計算空間權值,高斯函數考慮的是像素的空間分佈,距離較遠的像素點所對應的權值較小。
space_w = np.zeros_like(window) for x in range(window_size): for y in range(window_size): space_w[x, y] = np.exp(- ((x-center)**2 + (y-center)**2) / (2 * sigma_s ** 2))
3. 利用高斯函數計算像素相似度權值,高斯函數考慮的是像素的像素值分佈,像素值差距較大的像素點所對應的權值較小。
for x in range(window_size): for y in range(window_size): intensity_w[x, y] = np.exp(- ((window[x,y] - center)**2) / (2 * sigma_r ** 2))
4. 計算像素權值,即兩個高斯函數的乘積。
weights = space_w * intensity_w
5. 計算像素點的新像素值,利用所有像素點的權值和像素值的積的加和。
result[i, j] = np.sum(weights * window) / np.sum(weights)
三、雙邊濾波器的應用
雙邊濾波器可以應用於各種圖像處理任務中,包括圖像去噪、圖像增強、圖像分割等。
1. 圖像去噪:雙邊濾波器可以平滑圖像的噪聲,同時不破壞圖像的邊緣信息。
def bilateral_filter(img, window_size, sigma_s, sigma_r): result = np.zeros_like(img) center = window_size // 2 for i in range(center, img.shape[0]-center): for j in range(center, img.shape[1]-center): window = img[i-center:i+center+1, j-center:j+center+1] intensity_w = np.exp(-(window - img[i, j])**2 / (2*sigma_r**2)) space_w = get_space_weight(window_size, sigma_s, center) weights = space_w * intensity_w result[i, j] = np.sum(weights * window) / np.sum(weights) return result
2. 圖像增強:雙邊濾波器可以提高圖像的對比度和清晰度。
def bilateral_filter(img, window_size, sigma_s, sigma_r): result = np.zeros_like(img) center = window_size // 2 for i in range(center, img.shape[0]-center): for j in range(center, img.shape[1]-center): window = img[i-center:i+center+1, j-center:j+center+1] intensity_w = np.exp(-(window - img[i, j])**2 / (2*sigma_r**2)) space_w = get_space_weight(window_size, sigma_s, center) weights = space_w * intensity_w result[i, j] = np.sum(weights * window) / np.sum(weights) return result * 2 - img
3. 圖像分割:雙邊濾波器可以減少圖像的噪點,從而更好地進行圖像分割。
img = cv2.imread('lena.jpg', 0) img = cv2.addWeighted(img, 0.8, img, 0, 70) img = bilateral_filter(img, 3, 10, 10) edges = cv2.Canny(img, 50, 150) cv2.imshow('lena', edges) cv2.waitKey(0)
四、小結
雙邊濾波器算法是一種能夠平滑圖像的同時保留邊緣信息的算法,其核心在於通過空間權值和像素相似度權值計算像素權值,從而得到平滑的圖像。雙邊濾波器算法應用廣泛,常用於圖像去噪、圖像增強、圖像分割等任務中。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/193326.html