Python Pillow - 降噪



降噪,也稱為去噪,是指減少影像中不需要的偽影的過程。影像中的噪點通常表現為亮度或顏色上的隨機變化,這些變化並非原始場景或拍攝物件的一部分。影像去噪的目標是透過消除或減少這些不需要的、分散注意力的偽影來提高影像質量,使影像更清晰、更美觀。

Python Pillow 庫提供了一系列降噪濾鏡,允許使用者去除噪點影像中的噪點並恢復原始影像。在本教程中,我們將探索 GaussianBlur 和 Median 濾鏡作為有效的降噪方法。

使用 GaussianBlur 濾鏡去除噪點

使用高斯模糊濾鏡去除影像噪點是一種廣泛使用的技術。此技術透過對影像應用卷積濾鏡來平滑畫素值。

示例

這是一個使用 ImageFilter.GaussianBlur() 濾鏡去除 RGB 影像噪點的示例。

from PIL import Image, ImageFilter

# Open a Gaussian Noised Image  
input_image = Image.open("Images/GaussianNoisedImage.jpg").convert('RGB')

# Apply Gaussian blur with some radius
blurred_image = input_image.filter(ImageFilter.GaussianBlur(radius=2))

# Display the input and the blurred image
input_image.show()
blurred_image.show()

輸入噪點影像

GaussianNoisedImage

輸出去噪影像

blurred image tp

使用中值濾波器去除噪點

中值濾波器是另一種降噪方法,尤其適用於噪點像小而分散的影像。此函式透過用其區域性鄰域內的中值替換每個畫素值來工作。Pillow 庫為此目的提供了 ImageFilter.MedianFilter() 濾鏡。

示例

下面的示例使用 ImageFilter.MedianFilter() 去除影像噪點。

from PIL import Image, ImageFilter

# Open an image
input_image = Image.open("Images/balloons_noisy.png")

# Apply median filter with a kernel size 
filtered_image = input_image.filter(ImageFilter.MedianFilter(size=3))

# Display the input and the filtered image
input_image.show()
filtered_image.show()

輸入噪點影像

balloons noisy

輸出中值濾波影像

filtered image balloons

示例

此示例演示瞭如何使用中值濾波器減少灰度影像中的椒鹽噪聲。這可以透過使用中值濾波器、增強對比度以提高可見性,然後將影像轉換為二進位制模式以進行顯示來完成。

from PIL import Image, ImageEnhance, ImageFilter, ImageOps

# Open the image and convert it to grayscale
input_image = ImageOps.grayscale(Image.open('Images/salt-and-pepper noise.jpg'))

# Apply a median filter with a kernel size of 5 to reduce noise
filtered_image = input_image.filter(ImageFilter.MedianFilter(5))

# Enhance the contrast of the filtered image
contrast_enhancer = ImageEnhance.Contrast(filtered_image)
high_contrast_image = contrast_enhancer.enhance(3)

# Convert the image to binary
binary_image = high_contrast_image.convert('1')

# Display the input and processed images
input_image.show()
binary_image.show()

輸入噪點影像

salt and pepper noise

輸出中值濾波影像

median filtered
廣告