文章目录
- 方法:高斯滤波、双边滤波、小波变换 代码示例(OpenCV): import cv2 import numpy as np # 读取图像并添加高斯噪声 image = cv2.imread(‘noisy_image.jpg’) noise = np.random.normal(0, 25, image.shape).astype(np.uint8) noisy_image = cv2.add(image, noise) # 高斯滤波去噪 gaussian_filtered = cv2.GaussianBlur(noisy_image, (5, 5), 0) # 双边滤波(保留边缘) bilateral_filtered = cv2.bilateralFilter(noisy_image, d=9, sigmaColor=75, sigmaSpace=75) cv2.imshow(‘Original’, image) cv2.imshow(‘Gaussian Filtered’, gaussian_filtered) cv2.imshow(‘Bilateral Filtered’, bilateral_filtered) cv2.waitKey(0)
- 方法:中值滤波 代码示例(OpenCV): # 添加椒盐噪声(示例) x = image.reshape(-1) SNR = 0.85 noise_num = int(x.size * (1 – SNR)) random_indices = np.random.choice(x.size, noise_num, replace=False) x[random_indices] = np.random.choice([0, 255], noise_num) noisy_image = x.reshape(image.shape) # 中值滤波去噪 median_filtered = cv2.medianBlur(noisy_image, 5)
- 方法:非局部均值去噪(NLM) 代码示例(Scikit-image): from skimage import io, img_as_float from skimage.restoration import denoise_nl_means image = img_as_float(io.imread(‘noisy_image.jpg’)) denoised = denoise_nl_means(image, h=0.1, fast_mode=True, patch_size=5, patch_distance=3)
- 方法:二值化 + 邻域分析 代码示例(Pillow): from PIL import Image, ImageFilter def remove_lines(image_path, threshold=128): image = Image.open(image_path).convert(‘L’) # 转为灰度 binarized = image.point(lambda x: 0 if x < threshold else 255, ‘1’) clean = binarized.copy() width, height = binarized.size for y in range(1, height-1): for x in range(1, width-1): if binarized.getpixel((x, y)) == 0: neighbors = [binarized.getpixel((x-1, y)), binarized.getpixel((x+1, y)), binarized.getpixel((x, y-1)), binarized.getpixel((x, y+1))] if neighbors.count(0) >= 2: clean.putpixel((x, y), 255) return clean cleaned_image = remove_lines(‘document.jpg’) cleaned_image.save(‘cleaned_document.jpg’)
- 方法:颜色空间转换 + 阈值调整 代码示例(OpenCV): import cv2 import numpy as np image = cv2.imread(‘overexposed.jpg’) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) lower = np.array([0, 0, 200]) # V通道阈值 upper = np.array([180, 255, 255]) mask = cv2.inRange(hsv, lower, upper) # 降低过曝区域亮度 image[mask != 0] = cv2.add(image[mask != 0], (0, 0, -80)) cv2.imwrite(‘corrected.jpg’, image)
目录
- 一、噪声去除
- 1. 高斯噪声(像素值正态分布扰动)
- 2. 椒盐噪声(随机黑白像素点)
- 3. 复杂噪声(如伪影)
- 二、特定干扰去除
- 1. 干扰线(如扫描文档中的横线)
- 2. 强光干扰(过曝区域)
- 三、深度学习进阶方案
- 四、方法选择建议
在Python中去除图片干扰,需根据干扰类型(如噪声、特定物体、强光等)选择合适的方法。以下是分场景解决方案及代码示例:
- 方法:高斯滤波、双边滤波、小波变换
- 代码示例(OpenCV):
import cv2
import numpy as np
# 读取图像并添加高斯噪声
image = cv2.imread('noisy_image.jpg')
noise = np.random.normal(0, 25, image.shape).astype(np.uint8)
noisy_image = cv2.add(image, noise)
# 高斯滤波去噪
gaussian_filtered = cv2.GaussianBlur(noisy_image, (5, 5), 0)
# 双边滤波(保留边缘)
bilateral_filtered = cv2.bilateralFilter(noisy_image, d=9, sigmaColor=75, sigmaSpace=75)
cv2.imshow('Original', image)
cv2.imshow('Gaussian Filtered', gaussian_filtered)
cv2.imshow('Bilateral Filtered', bilateral_filtered)
cv2.waitKey(0)
import cv2
import numpy as np
# 读取图像并添加高斯噪声
image = cv2.imread('noisy_image.jpg')
noise = np.random.normal(0, 25, image.shape).astype(np.uint8)
noisy_image = cv2.add(image, noise)
# 高斯滤波去噪
gaussian_filtered = cv2.GaussianBlur(noisy_image, (5, 5), 0)
# 双边滤波(保留边缘)
bilateral_filtered = cv2.bilateralFilter(noisy_image, d=9, sigmaColor=75, sigmaSpace=75)
cv2.imshow('Original', image)
cv2.imshow('Gaussian Filtered', gaussian_filtered)
cv2.imshow('Bilateral Filtered', bilateral_filtered)
cv2.waitKey(0)
- 方法:中值滤波
- 代码示例(OpenCV):
# 添加椒盐噪声(示例)
x = image.reshape(-1)
SNR = 0.85
noise_num = int(x.size * (1 - SNR))
random_indices = np.random.choice(x.size, noise_num, replace=False)
x[random_indices] = np.random.choice([0, 255], noise_num)
noisy_image = x.reshape(image.shape)
# 中值滤波去噪
median_filtered = cv2.medianBlur(noisy_image, 5)
# 添加椒盐噪声(示例) x = image.reshape(-1) SNR = 0.85 noise_num = int(x.size * (1 - SNR)) random_indices = np.random.choice(x.size, noise_num, replace=False) x[random_indices] = np.random.choice([0, 255], noise_num) noisy_image = x.reshape(image.shape) # 中值滤波去噪 median_filtered = cv2.medianBlur(noisy_image, 5)
- 方法:非局部均值去噪(NLM)
- 代码示例(Scikit-image):
from skimage import io, img_as_float
from skimage.restoration import denoise_nl_means
image = img_as_float(io.imread('noisy_image.jpg'))
denoised = denoise_nl_means(image, h=0.1, fast_mode=True, patch_size=5, patch_distance=3)
from skimage import io, img_as_float
from skimage.restoration import denoise_nl_means
image = img_as_float(io.imread('noisy_image.jpg'))
denoised = denoise_nl_means(image, h=0.1, fast_mode=True, patch_size=5, patch_distance=3)
- 方法:二值化 + 邻域分析
- 代码示例(Pillow):
from PIL import Image, ImageFilter
def remove_lines(image_path, threshold=128):
image = Image.open(image_path).convert('L') # 转为灰度
binarized = image.point(lambda x: 0 if x < threshold else 255, '1')
clean = binarized.copy()
width, height = binarized.size
for y in range(1, height-1):
for x in range(1, width-1):
if binarized.getpixel((x, y)) == 0:
neighbors = [binarized.getpixel((x-1, y)), binarized.getpixel((x+1, y)),
binarized.getpixel((x, y-1)), binarized.getpixel((x, y+1))]
if neighbors.count(0) >= 2:
clean.putpixel((x, y), 255)
return clean
cleaned_image = remove_lines('document.jpg')
cleaned_image.save('cleaned_document.jpg')
from PIL import Image, ImageFilter
def remove_lines(image_path, threshold=128):
image = Image.open(image_path).convert('L') # 转为灰度
binarized = image.point(lambda x: 0 if x < threshold else 255, '1')
clean = binarized.copy()
width, height = binarized.size
for y in range(1, height-1):
for x in range(1, width-1):
if binarized.getpixel((x, y)) == 0:
neighbors = [binarized.getpixel((x-1, y)), binarized.getpixel((x+1, y)),
binarized.getpixel((x, y-1)), binarized.getpixel((x, y+1))]
if neighbors.count(0) >= 2:
clean.putpixel((x, y), 255)
return clean
cleaned_image = remove_lines('document.jpg')
cleaned_image.save('cleaned_document.jpg')
- 方法:颜色空间转换 + 阈值调整
- 代码示例(OpenCV):
import cv2
import numpy as np
image = cv2.imread('overexposed.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 0, 200]) # V通道阈值
upper = np.array([180, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
# 降低过曝区域亮度
image[mask != 0] = cv2.add(image[mask != 0], (0, 0, -80))
cv2.imwrite('corrected.jpg', image)
import cv2
import numpy as np
image = cv2.imread('overexposed.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 0, 200]) # V通道阈值
upper = np.array([180, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
# 降低过曝区域亮度
image[mask != 0] = cv2.add(image[mask != 0], (0, 0, -80))
cv2.imwrite('corrected.jpg', image)
对于复杂场景(如混合噪声、纹理干扰),可使用预训练模型(如U-Net、DnCNN):
import torch
from torchvision import models
# 加载预训练去噪模型(示例)
model = models.DnCNN().eval()
model.load_state_dict(torch.load('dncnn_pretrained.pth'))
# 预处理输入
input_tensor = preprocess(noisy_image) # 需自定义预处理函数
with torch.no_grad():
output = model(input_tensor)
denoised_image = postprocess(output) # 自定义后处理函数
- 快速去噪:优先使用OpenCV/Pillow的内置滤波器(如
cv2.medianBlur)。
- 保留细节:选择双边滤波或小波变换。
- 复杂噪声:尝试Scikit-image的非局部均值或深度学习模型。
- 特定干扰:结合二值化、形态学操作或自定义像素分析逻辑。
cv2.medianBlur)。通过调整滤波器参数(如核大小、阈值)或模型超参数,可进一步优化去噪效果。
到此这篇关于Python如何去除图片干扰的文章就介绍到这了,更多相关Python去除图片干扰内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- python 使用plt画图,去除图片四周的白边方法
- Python实现去除图片中指定颜色的像素功能示例
- python 基于opencv去除图片阴影
- 使用python去除图片白色像素的实例