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

如何将全彩图像转换为黑-白-红三色抖动图像?

全彩图转黑-白-红三色抖动图实现方案

核心思路

要实现目标效果,确实需要两步:先将全彩像素映射到黑、白、红三色,再通过抖动算法模拟色彩过渡。关键是精准的颜色匹配和合理的误差扩散抖动。


方案一:用GIMP可视化操作(适合非编程用户)

  • 打开原图,确保图像处于RGB模式(图像 > 模式 > RGB)
  • 创建自定义调色板:
    • 打开窗口 > 可停靠对话框 > 调色板,点击调色板菜单选择新建调色板
    • 添加三个颜色:黑(0,0,0)、白(255,255,255)、红(255,0,0),保存调色板
  • 转索引色并应用抖动:
    • 选择图像 > 模式 > 索引,在弹出窗口中:
      • 调色板选择刚创建的三色调色板
      • 勾选抖动选项,选择Floyd-Steinberg算法
      • 点击确定即可生成目标效果

方案二:Python代码实现(适合批量或定制化需求)

用Pillow库完成像素映射和抖动,步骤如下:

  1. 先安装依赖:
pip install pillow
  1. 实现代码:
from PIL import Image
import numpy as np

def closest_color(pixel, target_colors):
    # 计算像素与目标颜色的欧氏距离,返回最近的颜色
    pixel = np.array(pixel)
    target_colors = np.array(target_colors)
    distances = np.sqrt(np.sum((target_colors - pixel)**2, axis=1))
    return target_colors[np.argmin(distances)]

def floyd_steinberg_dither(img, target_colors):
    img_array = np.array(img.convert("RGB"), dtype=np.float32)
    height, width = img_array.shape[:2]

    for y in range(height):
        for x in range(width):
            old_pixel = img_array[y, x].copy()
            new_pixel = closest_color(old_pixel, target_colors)
            img_array[y, x] = new_pixel
            error = old_pixel - new_pixel

            # 误差扩散到相邻像素
            if x + 1 < width:
                img_array[y, x+1] += error * 7/16
            if y + 1 < height:
                if x > 0:
                    img_array[y+1, x-1] += error * 3/16
                img_array[y+1, x] += error * 5/16
                if x + 1 < width:
                    img_array[y+1, x+1] += error * 1/16

    # 转换回图像格式
    img_array = np.clip(img_array, 0, 255).astype(np.uint8)
    return Image.fromarray(img_array)

# 主流程
if __name__ == "__main__":
    # 定义目标三色:黑、白、红
    target_colors = [(0, 0, 0), (255, 255, 255), (255, 0, 0)]
    # 读取原图(替换为你的图像路径)
    original_img = Image.open("vCGrJ.jpg")
    # 应用抖动
    dithered_img = floyd_steinberg_dither(original_img, target_colors)
    # 保存结果
    dithered_img.save("three_color_dither.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:13:16