Python PIL比较颜色

nat*_*ill 1 python python-imaging-library

我有一个带有这样嘈杂背景的图像(爆炸,每个正方形都是一个像素)。我正在尝试规范化黑色背景,以便可以完全替换颜色。

这就是我在想的(伪代码):

for pixel in image:
    if is_similar(pixel, (0, 0, 0), threshold):
        pixel = (0, 0, 0)
Run Code Online (Sandbox Code Playgroud)

什么样的功能可以让我比较两个颜色值以匹配某个阈值?

nat*_*ill 5

我最终从这个答案中使用了感知亮度公式。效果很好。

THRESHOLD = 18

def luminance(pixel):
    return (0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2])


def is_similar(pixel_a, pixel_b, threshold):
    return abs(luminance(pixel_a) - luminance(pixel_b)) < threshold


width, height = img.size
pixels = img.load()

for x in range(width):
    for y in range(height):
        if is_similar(pixels[x, y], (0, 0, 0), THRESHOLD):
            pixels[x, y] = (0, 0, 0)
Run Code Online (Sandbox Code Playgroud)