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

如何用线条勾勒特定颜色区域的轮廓而非填充整个区域?

把颜色区域填充改为轮廓勾勒的实现方案

你当前的代码会将符合颜色范围的区域全部用红色点填满,要实现只勾勒区域轮廓的效果,核心是只绘制区域的边缘像素——也就是当前像素属于目标颜色范围,但它的上下左右四个相邻像素中至少有一个不属于该范围的像素。

修改后的完整代码

private readonly Color _from20 = Color.FromArgb(254, 254, 244);
private readonly Color _to20 = Color.FromArgb(255, 255, 255);//设置颜色范围

for (int i = 0; i < windowOriginal.Width; i++)
{
    for (int j = 0; j < windowOriginal.Height; j++)
    {
        Color c = imageOriginal.GetPixel(i, j);
        // 判断当前像素在颜色范围内,且是边缘像素
        if (ColorWithinRange(c, _from20, _to20) && IsEdgePixel(i, j, imageOriginal, _from20, _to20))
        {
            // 绘制轮廓点(单个点组成线条)
            Drawing.Line(objectsOriginal, new IntPoint(i, j), new IntPoint(i, j), Color.Red);
        }
    }
}

// 判断是否为边缘像素
bool IsEdgePixel(int x, int y, Bitmap image, Color from, Color to)
{
    // 检查上下左右四个相邻像素,只要有一个不在颜色范围内,就是边缘
    // 注意边界判断,避免越界
    if (x > 0 && !ColorWithinRange(image.GetPixel(x - 1, y), from, to))
        return true;
    if (x < image.Width - 1 && !ColorWithinRange(image.GetPixel(x + 1, y), from, to))
        return true;
    if (y > 0 && !ColorWithinRange(image.GetPixel(x, y - 1), from, to))
        return true;
    if (y < image.Height - 1 && !ColorWithinRange(image.GetPixel(x, y + 1), from, to))
        return true;
    return false;
}

// 判断颜色是否在范围内
bool ColorWithinRange(Color c, Color _from, Color _to)
{
    return (_from.R <= c.R && c.R <= _to.R) &&
           (_from.G <= c.G && c.G <= _to.G) &&
           (_from.B <= c.B && c.B <= _to.B);
}

关键修改说明

  1. 新增IsEdgePixel方法:专门判断当前像素是否是区域边缘,通过检查上下左右四个相邻像素是否存在非目标颜色的像素来确定。
  2. 循环中增加边缘判断:只有同时满足“在颜色范围内”和“是边缘像素”的条件,才进行绘制,这样就只会画出区域的轮廓,而不会填充整个区域。
  3. 边界处理:在检查相邻像素时,先判断是否超出图片的宽高范围,避免出现索引越界的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:54:14