python实现去除一张彩色图像的亮度噪声和高斯噪声完整代码
时间: 2023-11-22 09:53:46 浏览: 119
可以使用Pillow库实现去除一张彩色图像的亮度噪声和高斯噪声。以下是完整代码:
```python
from PIL import Image, ImageFilter, ImageStat
import random
# 打开图片
img = Image.open("image.png")
# 添加亮度噪声
def add_brightness_noise(img):
# 获取图片统计信息
stat = ImageStat.Stat(img)
# 获取图片的均值
mean = stat.mean
# 获取图片的标准差
stddev = stat.stddev
# 生成随机数,表示亮度噪声的强度
noise = random.randint(1, 10)
# 生成噪声图像,大小与原图相同
noise_img = Image.new('RGB', img.size)
for x in range(img.width):
for y in range(img.height):
# 获取像素点的RGB值
r, g, b = img.getpixel((x, y))
# 生成对应噪声值
delta = int(random.gauss(noise, noise/3))
# 修改RGB值
r = max(0, min(255, r+delta))
g = max(0, min(255, g+delta))
b = max(0, min(255, b+delta))
# 设置像素点的RGB值
noise_img.putpixel((x, y), (r, g, b))
# 将原图和噪声图像混合
result = Image.blend(img, noise_img, 0.7)
return result
# 添加高斯噪声
def add_gaussian_noise(img):
# 生成随机数,表示高斯噪声的强度
noise = random.randint(1, 10)
# 生成噪声图像,大小与原图相同
noise_img = Image.new('RGB', img.size)
for x in range(img.width):
for y in range(img.height):
# 获取像素点的RGB值
r, g, b = img.getpixel((x, y))
# 生成对应噪声值
delta = int(random.gauss(noise, noise/3))
# 修改RGB值
r = max(0, min(255, r+delta))
g = max(0, min(255, g+delta))
b = max(0, min(255, b+delta))
# 设置像素点的RGB值
noise_img.putpixel((x, y), (r, g, b))
# 将原图和噪声图像混合
result = Image.blend(img, noise_img, 0.7)
return result
# 去除亮度噪声
def remove_brightness_noise(img):
# 获取图片统计信息
stat = ImageStat.Stat(img)
# 获取图片的均值
mean = stat.mean
# 获取图片的标准差
stddev = stat.stddev
# 设置阈值,超过该值的像素点将被认为是噪声
threshold = stddev[0] * 2
# 生成噪声图像,大小与原图相同
noise_img = Image.new('RGB', img.size)
for x in range(img.width):
for y in range(img.height):
# 获取像素点的RGB值
r, g, b = img.getpixel((x, y))
# 判断该像素点是否是噪声
if abs(r - mean[0]) > threshold:
r = int(mean[0])
if abs(g - mean[1]) > threshold:
g = int(mean[1])
if abs(b - mean[2]) > threshold:
b = int(mean[2])
# 设置像素点的RGB值
noise_img.putpixel((x, y), (r, g, b))
return noise_img
# 去除高斯噪声
def remove_gaussian_noise(img):
# 获取图片统计信息
stat = ImageStat.Stat(img)
# 获取图片的均值
mean = stat.mean
# 获取图片的标准差
stddev = stat.stddev
# 设置阈值,超过该值的像素点将被认为是噪声
threshold = stddev[0] * 2
# 生成噪声图像,大小与原图相同
noise_img = Image.new('RGB', img.size)
for x in range(img.width):
for y in range(img.height):
# 获取像素点的RGB值
r, g, b = img.getpixel((x, y))
# 判断该像素点是否是噪声
if abs(r - mean[0]) > threshold:
r = int(mean[0])
if abs(g - mean[1]) > threshold:
g = int(mean[1])
if abs(b - mean[2]) > threshold:
b = int(mean[2])
# 设置像素点的RGB值
noise_img.putpixel((x, y), (r, g, b))
return noise_img
# 添加亮度噪声
img = add_brightness_noise(img)
# 添加高斯噪声
img = add_gaussian_noise(img)
# 去除亮度噪声
img = remove_brightness_noise(img)
# 去除高斯噪声
img = remove_gaussian_noise(img)
# 保存图片
img.save("result.png")
```
代码中,`add_brightness_noise()`和`add_gaussian_noise()`函数分别添加亮度噪声和高斯噪声,`remove_brightness_noise()`和`remove_gaussian_noise()`函数分别去除亮度噪声和高斯噪声。最后将图片保存为`result.png`。
阅读全文