gpt4 book ai didi

c# - 如果我知道背景颜色,如何创建图像轮廓?

转载 作者:太空狗 更新时间:2023-10-29 21:45:56 24 4
gpt4 key购买 nike

我想创建一个简单的程序,您可以打开任何给定的图像并选择 2 种颜色:BackgroundColorOutlineColor。然后围绕“物体”画出轮廓。

到目前为止,这是我的代码:

        for (int y = 1; y < height - 1; y++) //iterate trough every pixel 
{ //in my bitmap
for (int x = 1; x < width - 1; x++)
{
//i want to put a pixel only if the the curent pixel is background
if (bitmap.GetPixel(x, y) != BackgroundColor)
continue;

var right = bitmap.GetPixel(x + 1, y);
var down = bitmap.GetPixel(x, y + 1);
var up = bitmap.GetPixel(x, y - 1);
var left = bitmap.GetPixel(x - 1, y);
//get the nearby pixels
var neibours = new List<Color> {up, down, left, right};

var nonBackgroundPix = 0;
//then count how many are not outline nor background color
foreach (Color neibour in neibours)
{
if (neibour != BackgroundColor && neibour != OutlineColor)
{
nonBackgroundPix++;
}
}
//finaly put an outline pixel only if there are 1,2 or 3 non bg pixels
if (nonBackgroundPix > 0 && nonBackgroundPix < 4)
{
bitmap.SetPixel(x, y, OutlineColor);
}
}
}

当我运行我的代码并输入时,问题就来了 Before我得到 After

而我想要的是 Want

如果您在我的代码中发现问题,请知道执行此操作的更好算法或设法以某种方式执行此操作,请告诉我。提前谢谢大家!

最佳答案

问题:

您正在将背景颜色更改为非背景颜色,然后由后续像素检查拾取该颜色。

解决方案:

我建议存储一个新数组,其中包含“稍后更改”的像素,然后在映射完整图像后返回并设置这些像素。 (此外,您可以立即更改它,然后向您可以检查的像素添加一个标志,但这是您需要实现的更多逻辑,例如检查 bool 数组)

关于c# - 如果我知道背景颜色,如何创建图像轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com