使用 PIL Python 创建像素噪声

Pab*_*bar 5 python image noise python-imaging-library

我正在尝试生成带有噪声和文本的图像的训练数据,类似于下图:

示例图像

我已经想出了如何使用正确大小的文本生成图像,但无法弄清楚如何生成噪声。起初我认为高斯噪声是正确的方法,但这似乎不是正确的噪声。

from PIL import Image, ImageDraw, ImageFont
import numpy


img = Image.new('RGB', (250, 50), color = 'white')
fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 36)
d = ImageDraw.Draw(img)
d.text((62,5), "3H1339", font=fnt, fill=(0,0,0))
img.save('imagetext.png')
Run Code Online (Sandbox Code Playgroud)

Vic*_*eau 4

我认为您正在寻找椒盐噪音。每个像素都有被破坏的概率(数量)。每个噪声像素都有相同的概率是咸粒(白色)或胡椒粒(黑色)。给定一个 PIL 图像:

def add_salt_and_pepper(image, amount):

    output = np.copy(np.array(image))

    # add salt
    nb_salt = np.ceil(amount * output.size * 0.5)
    coords = [np.random.randint(0, i - 1, int(nb_salt)) for i in output.shape]
    output[coords] = 1

    # add pepper
    nb_pepper = np.ceil(amount* output.size * 0.5)
    coords = [np.random.randint(0, i - 1, int(nb_pepper)) for i in output.shape]
    output[coords] = 0

    return Image.fromarray(output)
Run Code Online (Sandbox Code Playgroud)

可以很容易地将其修改为具有随机颜色的颗粒。