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

C#如何检测Bitmap像素是否接触指定颜色的像素?

检测Bitmap像素是否接触指定颜色的实现方案

首先,你的遍历代码存在变量名错误,这会导致循环逻辑完全失效,先修正这个基础问题:
原代码里for (int x = 0; i < bitmap.Width; ++x)中的i应该是x,for (int y = 0; h < bitmap.Height; ++y)中的h应该是y,否则根本无法正确遍历所有像素。

接下来,检测相邻像素时要注意两个核心问题:

  • 边界判断:不能直接访问x-1、y-1这类可能超出Bitmap范围的坐标,否则会抛出异常或返回错误颜色值
  • 颜色匹配准确性:Color.Blue是纯蓝色(ARGB值为#FF0000FF),若目标蓝色带Alpha通道差异或色调偏差,直接用==判断会失败

实现步骤(四邻接检测:上下左右四个方向)

  1. 修正遍历循环的变量错误
  2. 对每个像素,依次检查上下左右四个方向的相邻像素
  3. 对每个方向的坐标先做边界校验,确保在Bitmap宽高范围内
  4. 若某一方向的像素匹配目标颜色,则标记当前像素“接触指定颜色”

完整代码示例

for (int x = 0; x < bitmap.Width; ++x)
{
    for (int y = 0; y < bitmap.Height; ++y)
    {
        bool isTouchingBlue = false;
        
        // 检测左侧像素
        if (x > 0 && bitmap.GetPixel(x - 1, y) == Color.Blue)
        {
            isTouchingBlue = true;
        }
        // 检测右侧像素
        else if (x < bitmap.Width - 1 && bitmap.GetPixel(x + 1, y) == Color.Blue)
        {
            isTouchingBlue = true;
        }
        // 检测上方像素
        else if (y > 0 && bitmap.GetPixel(x, y - 1) == Color.Blue)
        {
            isTouchingBlue = true;
        }
        // 检测下方像素
        else if (y < bitmap.Height - 1 && bitmap.GetPixel(x, y + 1) == Color.Blue)
        {
            isTouchingBlue = true;
        }
        
        // 根据isTouchingBlue的值执行后续逻辑
        if (isTouchingBlue)
        {
            // 当前像素接触到蓝色,处理逻辑
        }
    }
}

额外优化建议

  • 如果需要检测八邻接(含对角线方向),可在上述基础上增加四个对角线方向的判断(比如x>0 && y>0时检测左上角等)
  • 大尺寸Bitmap使用GetPixel性能较低,建议用Bitmap.LockBits直接操作内存中的像素数据,提升遍历效率
  • 若目标颜色存在Alpha通道差异,可通过比较R、G、B分量匹配,忽略Alpha值:
    Color targetColor = Color.Blue;
    Color adjacentColor = bitmap.GetPixel(x-1, y);
    if (adjacentColor.R == targetColor.R && adjacentColor.G == targetColor.G && adjacentColor.B == targetColor.B)
    {
        // 颜色匹配成功
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:25:21