Python PIL比较颜色

Python PIL比较颜色,python,python-imaging-library,Python,Python Imaging Library,我有一个像这样嘈杂背景的图像(放大,每个方块都是一个像素)。我正在尝试将黑色背景标准化,以便完全替换颜色 这就是我的想法(psuedo代码): 什么样的函数可以让我比较两个颜色值以在某个阈值内匹配?我最终使用了来自的感知亮度公式。它工作得很好 THRESHOLD = 18 def luminance(pixel): return (0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2]) def is_similar(pixe

我有一个像这样嘈杂背景的图像(放大,每个方块都是一个像素)。我正在尝试将黑色背景标准化,以便完全替换颜色

这就是我的想法(psuedo代码):


什么样的函数可以让我比较两个颜色值以在某个阈值内匹配?

我最终使用了来自的感知亮度公式。它工作得很好

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)
THRESHOLD=18
def亮度(像素):
返回(0.299*像素[0]+0.587*像素[1]+0.114*像素[2])
def相似(像素a、像素b、阈值):
返回abs(亮度(像素a)-亮度(像素b))<阈值
宽度、高度=img.size
像素=img.load()
对于范围内的x(宽度):
对于范围内的y(高度):
如果_相似(像素[x,y],(0,0,0),阈值):
像素[x,y]=(0,0,0)
看一看,使用亮度公式基本上可以得到每个像素的灰度值,这样您就可以在一维中将像素与阈值进行比较。查看维基百科的文章,了解确定两种颜色有多相似的几种方法。最简单的答案是:将每种颜色视为三维坐标,并使用毕达哥拉斯公式计算它们之间的距离。
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)