【发布时间】:2021-02-22 04:07:10
【问题描述】:
我确实尝试在我的应用程序中使用这个代码来解决这个问题:
How to determine the background color of document when there are 3 options, using c# or imagemagick
private System.Drawing.Color CalculateAverageColor(Bitmap bm)
{
int width = bm.Width;
int height = bm.Height;
int red = 0;
int green = 0;
int blue = 0;
int minDiversion = 15; // drop pixels that do not differ by at least minDiversion between color values (white, gray or black)
int dropped = 0; // keep track of dropped pixels
long[] totals = new long[] { 0, 0, 0 };
int bppModifier = bm.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb ? 3 : 4; // cutting corners, will fail on anything else but 32 and 24 bit images
BitmapData srcData = bm.LockBits(new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
int stride = srcData.Stride;
IntPtr Scan0 = srcData.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int idx = (y * stride) + x * bppModifier;
red = p[idx + 2];
green = p[idx + 1];
blue = p[idx];
if (Math.Abs(red - green) > minDiversion || Math.Abs(red - blue) > minDiversion || Math.Abs(green - blue) > minDiversion)
{
totals[2] += red;
totals[1] += green;
totals[0] += blue;
}
else
{
dropped++;
}
}
}
}
int count = width * height - dropped;
int avgR = (int)(totals[2] / count);
int avgG = (int)(totals[1] / count);
int avgB = (int)(totals[0] / count);
return System.Drawing.Color.FromArgb(avgR, avgG, avgB);
}
问题是当我添加位图时,会发生这种情况:
谁能帮我弄清楚到底发生了什么?
【问题讨论】:
-
它总是在 else 里面,所以 drop 的值是 width*height。所以你必须调试为什么它会进入 else。
-
您可能想检查 count 是否为零,然后将所有平均值分配为 0,假设所有像素都应该“丢弃”,就像位图是灰度或黑白一样。或者决定灰度或黑白的“平均”颜色应该是什么。
-
显然
count是0。