【问题标题】:C# How to keep 1 range of colors in a bitmap?C#如何在位图中保留1个颜色范围?
【发布时间】:2019-05-08 14:00:33
【问题描述】:

所以在 c# 中,我在位图中有一个图像,其中有不同的颜色。现在我试图在图像中只保留一个颜色范围,并且可以删除所有其他颜色(将它们变成白色像素)。现在我要提取的颜色是黄色,但只是将像素的颜色与 Color.Yellow 进行比较是不够的,因为像素可以有不同的黄色阴影,所以我猜我有点需要过滤掉所有其他颜色但是我似乎无法弄清楚该怎么做。

我读过一些关于卷积的文章,但我没有看到直接在程序中实现它的方法。

有没有一种方法可以让我只保持黄色并且图像中的颜色不同?

提前致谢。

【问题讨论】:

  • 您可以使用 GetHue 在一定范围内确定黄色。为了提高速度,请使用 LockBits!

标签: c# colors bitmap


【解决方案1】:

这是一个快速简单的解决方案。

它使用一个功能,该功能将插件与您可以找到的帖子here

这是函数:

public Color ToWhiteExceptYellow(Color c, int range)
{
    float hueC = c.GetHue();
    float e = 1.5f * range;   // you can adapt this nuumber
    float hueY = Color.Yellow.GetHue();
    float delta = hueC - hueY;
    bool ok = (Math.Abs(delta) < e);
    //if (!ok) { ok = (Math.Abs(360 + delta) < e); }  // include these lines ..
    //if (!ok) { ok = (Math.Abs(360 - delta) < e); }  // for reddish colors!

    return ok ? c : Color.White;
}

它适用于黄色,但由于色调是一个环绕数字需要更多代码才能使用环绕点颜色(红色)。我已经包含了两行来提供帮助。

要使其正常工作,请更改链接帖子中的这些行:

// pick one of our filter methods
ModifyHue hueChanger = new ModifyHue(ToWhiteExceptYellow);

..和..

// we pull the bitmap from the image
Bitmap bmp = new Bitmap( (Bitmap)pictureBox1.Image);  // create a copy

..和..

c = hueChanger(c, trackBar1.Value);  // insert a number you like, mine go from 1-10

..和..:

// we need to re-assign the changed bitmap
pictureBox2.Image = (Bitmap)bmp;   // show in a 2nd picturebox

不要忘记包含委托:

public delegate Color ModifyHue(Color c, int ch);

和 using 子句:

using System.Drawing.Imaging;

请注意,应该处理旧内容以避免泄漏图像,可能是这样:

Bitmap dummy = (Bitmap )pictureBox2.Image;
pictureBox2.Image = null;
if (dummy != null) dummy.Dispose;
// now assign the new image!

让我们看看它的工作原理:

请随意扩展。您可以更改函数的签名以包含目标颜色并添加亮度和/或饱和度范围..

【讨论】:

  • 谢谢你,这对我帮助很大!
【解决方案2】:

非常模糊的定义, 如果我明白你想做什么,我会这样做:

  1. 遍历位图的每个像素并将其与黄色范围进行比较(如果超出 - 分配白色值)
  2. 将每个像素的 RGB 值转换为 CMYK(在线搜索转换公式)[Y = (1-Blue-Black) / (1-Black)]
  3. 如果 YellowMin 则分配白色值

卷积对你没有帮助,它作用于空间域而不是颜色

【讨论】:

  • 这确实是我想要完成的,我会的,一定要试试这个,谢谢。
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2016-01-21
  • 1970-01-01
相关资源
最近更新 更多