Python图像操作1:图像->黑白、高斯噪声、椒盐噪声

发现CSDN上许多代码不适合小白,我来分享!!!

import numpy as np
from PIL import Image

def to_black(image):
    # 将图片转换为灰度图像
    gray_image = image.convert("L")
    return gray_image

def add_salt_and_pepper_noise(image, amount=0.1, salt_vs_pepper=0.5):
    # 将图片转换为数组
    img_array = np.array(image)

    # 创建一个与图片大小相同的随机数组
    noise = np.random.rand(*img_array.shape)

    # 定义噪声的阈值
    salt_threshold = 1 - amount * salt_vs_pepper
    pepper_threshold = amount * salt_vs_pepper

    # 添加盐噪声(白色像素)
    img_array[noise > salt_threshold] = 255

    # 添加椒噪声(黑色像素)
    img_array[noise < pepper_threshold] = 0

    # 将数组转换回图片
    noisy_image = Image.fromarray(img_array)

    return noisy_image


def add_gaussian_noise(image, mean=0, std_dev=25):
    # 将图片转换为数组
    img_array = np.array(image)

    # 生成与图像相同尺寸的高斯噪声
    gaussian_noise = np.random.normal(mean, std_dev, img_array.shape)

    # 将噪声添加到图片中
    noisy_img_array = img_array + gaussian_noise

    # 确保图片像素值在0到255之间
    noisy_img_array = np.clip(noisy_img_array, 0, 255).astype(np.uint8)

    # 将数组转换回图片
    noisy_image = Image.fromarray(noisy_img_array)

    return noisy_image


if __name__=="__main__":
    # 打开图片
    image = Image.open(r"E:\desktop\output\2.png")

    # 添加椒盐噪声
    # image = add_salt_and_pepper_noise(image, amount=0.1, salt_vs_pepper=0.5)
    # 添加高斯噪声
    # image=add_gaussian_noise(image, mean=0, std_dev=25)
    # 变黑白
    image=to_black(image)

    # 保存或显示添加噪声后的图片
    image.save(r"E:\desktop\output\4.png")
    image.show()

修改输入图片路径和保存图片路径即可,可以自选三个功能,变黑白、加高斯噪声、加椒盐噪声。

原图

                            原图                                             黑白图

                            椒盐噪声                                             高斯噪声

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值