gpt4 book ai didi

c# - 分别获取位图图像中黑白像素的总数

转载 作者:行者123 更新时间:2023-11-30 20:00:17 25 4
gpt4 key购买 nike

我正在尝试编写一个代码来遍历我的图像并逐行计算所有像素并告诉我图像中有多少白色像素和多少黑色像素? (假设我的图像是由白底黑字组成的)

var backgroundPixels = 0;

for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
if (bmp.GetPixel(x, y).Equals(Color.White))
{
backgroundPixels++;
}
}

}
label3.Text = Convert.ToString(backgroundPixels);

我遇到了问题,因为代码由于某种原因不起作用。谁能帮帮我?

最佳答案

当您使用 ==Equals 时,您并不是逐字节比较 ARGB 的值,因为“==”运算符是这样完成的

     public static bool operator ==(Color left, Color right)
{
if (left.value != right.value || (int) left.state != (int) right.state || (int) left.knownColor != (int) right.knownColor)
return false;
if (left.name == right.name)
return true;
if (left.name == null || right.name == null)
return false;
else
return left.name.Equals(right.name);
}

下面是.net中的Equals方法是如何实现的

public override bool Equals(object obj)
{
if (obj is Color)
{
Color color = (Color) obj;
if (this.value == color.value && (int) this.state == (int) color.state && (int) this.knownColor == (int) color.knownColor)
{
if (this.name == color.name)
return true;
if (this.name == null || color.name == null)
return false;
else
return this.name.Equals(this.name);
}
}
return false;
}

要解决您的问题,您应该使用 ToArgb() 转换为 ARGB发送 32 位当前颜色的函数

 private void button1_Click(object sender, EventArgs e)
{

int whiteColor = 0;
int blackColor = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color color = bmp.GetPixel(x, y);

if (color.ToArgb()==Color.White.ToArgb())
{
whiteColor++;
}

else
if (color.ToArgb() == Color.White.ToArgb())
{
blackColor++;
}
}

}
}

关于c# - 分别获取位图图像中黑白像素的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21405811/

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