public static void AverageColor(Bmp bmp, Rectangle r, out double avgRed, out double avgGreen, out double avgBlue) { long redSum = 0, greenSum = 0, blueSum = 0; for (int y = r.Y; y < r.Y + r.Height; y++) { for (int x = r.X; x < r.X + r.Width; x++) { redSum += bmp.GetPixelR(x, y); greenSum += bmp.GetPixelG(x, y); blueSum += bmp.GetPixelB(x, y); } } avgRed = (double)redSum / (r.Width * r.Height); avgGreen = (double)greenSum / (r.Width * r.Height); avgBlue = (double)blueSum / (r.Width * r.Height); }
private static bool BmpSourceFitsBmpTarget(Bmp bmpSource, int xSource, int ySource, Bmp bmpTarget, int minPixelsToMatch, int maxPixelsToMismatch, int maxColorError) { if (xSource + bmpTarget.Width > bmpSource.Width || ySource + bmpTarget.Height > bmpSource.Height) return false; int transparent = 0, pixelsMatched = 0, pixelsMismatched = 0; for (int yTarget = 0; yTarget < bmpTarget.Height; yTarget++) { for (int xTarget = 0; xTarget < bmpTarget.Width; xTarget++) { int colorSourceR = bmpSource.GetPixelR(xSource + xTarget, ySource + yTarget); int colorSourceG = bmpSource.GetPixelG(xSource + xTarget, ySource + yTarget); int colorSourceB = bmpSource.GetPixelB(xSource + xTarget, ySource + yTarget); int colorTargetA = bmpTarget.GetPixelA(xTarget, yTarget); int colorTargetR = bmpTarget.GetPixelR(xTarget, yTarget); int colorTargetG = bmpTarget.GetPixelG(xTarget, yTarget); int colorTargetB = bmpTarget.GetPixelB(xTarget, yTarget); if (colorTargetA == 0) { transparent++; } else if (colorSourceR - maxColorError <= colorTargetR && colorSourceR + maxColorError >= colorTargetR && colorSourceG - maxColorError <= colorTargetG && colorSourceG + maxColorError >= colorTargetG && colorSourceB - maxColorError <= colorTargetB && colorSourceB + maxColorError >= colorTargetB) { pixelsMatched++; } else { pixelsMismatched++; } if (pixelsMismatched > maxPixelsToMismatch) { return false; } if (pixelsMatched + transparent >= minPixelsToMatch) { return true; } } } return false; }