You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用距离函数识别并替换图像中指定相近颜色的像素?

基于颜色距离的像素替换实现

核心逻辑

通过计算每个像素与红、绿、蓝三种基准色的欧氏距离,判断该像素最接近哪种基准色,再按规则替换:

  • 最接近红色 → 替换为蓝色
  • 最接近蓝色 → 替换为绿色
  • 最接近绿色 → 替换为红色

修正距离计算函数

你提供的GetDistance函数存在参数未正确使用、无返回值、库导入位置错误等问题,修正后如下:

import math

def GetDistance(tuple1, tuple2):
    # tuple1: 当前像素的(r,g,b)值,tuple2: 基准色的(r,g,b)值
    r, g, b = tuple1
    r2, g2, b2 = tuple2
    return math.sqrt(((r - r2)**2) + ((g - g2)**2) + ((b - b2)**2))

完整像素遍历与替换代码

结合图像处理逻辑,完整实现如下(以PIL库为例):

from PIL import Image
import math

def GetDistance(tuple1, tuple2):
    r, g, b = tuple1
    r2, g2, b2 = tuple2
    return math.sqrt(((r - r2)**2) + ((g - g2)**2) + ((b - b2)**2))

# 定义基准色和替换规则
BASE_COLORS = {
    "red": (255, 0, 0),
    "green": (0, 255, 0),
    "blue": (0, 0, 255)
}
REPLACE_RULE = {
    "red": BASE_COLORS["blue"],
    "blue": BASE_COLORS["green"],
    "green": BASE_COLORS["red"]
}

# 加载图像
image = Image.open("your_image_path.jpg").convert("RGB")
pixels = image.load()

# 遍历每个像素并处理
for y in range(image.height):
    for x in range(image.width):
        current_pixel = pixels[x, y]
        # 计算当前像素到三个基准色的距离
        dist_red = GetDistance(current_pixel, BASE_COLORS["red"])
        dist_green = GetDistance(current_pixel, BASE_COLORS["green"])
        dist_blue = GetDistance(current_pixel, BASE_COLORS["blue"])
        
        # 判断最接近的基准色并替换
        min_dist = min(dist_red, dist_green, dist_blue)
        if min_dist == dist_red:
            pixels[x, y] = REPLACE_RULE["red"]
        elif min_dist == dist_blue:
            pixels[x, y] = REPLACE_RULE["blue"]
        else:
            pixels[x, y] = REPLACE_RULE["green"]

# 保存处理后的图像
image.save("processed_image.jpg")

关键步骤说明

  • 基准色锚定:采用标准RGB红、绿、蓝作为颜色判断的基准
  • 距离量化:用欧氏距离衡量像素与基准色的颜色差异,数值越小代表颜色越接近
  • 像素匹配:遍历每个像素时,找到距离最小的基准色,按预设规则完成颜色替换

内容的提问来源于stack exchange,提问作者user20232221

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:05:39