c# - C#,如何获取图像内特定区域的颜色
问题描述
如何获得图像内具有 5x5px 的区域的颜色。
int xPixel = 200; int yPixel = 100;
Bitmap myBitmap = new Bitmap(“C:/Users/admin/Desktop/image.png");
Color pixelColor = myBitmap.GetPixel(xPixel, yPixel, 5, 5);
MessageBox.Show(pixelColor.Name);
解决方案
您可以使用这种扩展方法来获取图像区域中的主色,以防它们不完全相同
public static Color GetDominantColor(this Bitmap bitmap, int startX, int startY, int width, int height) {
var maxWidth = bitmap.Width;
var maxHeight = bitmap.Height;
//TODO: validate the region being requested
//Used for tally
int r = 0;
int g = 0;
int b = 0;
int totalPixels = 0;
for (int x = startX; x < (startX + width); x++) {
for (int y = startY; y < (startY + height); y++) {
Color c = bitmap.GetPixel(x, y);
r += Convert.ToInt32(c.R);
g += Convert.ToInt32(c.G);
b += Convert.ToInt32(c.B);
totalPixels++;
}
}
r /= totalPixels;
g /= totalPixels;
b /= totalPixels;
Color color = Color.FromArgb(255, (byte)r, (byte)g, (byte)b);
return color;
}
然后你可以像这样使用它
Color pixelColor = myBitmap.GetDominantColor(xPixel, yPixel, 5, 5);
有改进的空间,比如使用Point
and Size
,甚至是Rectangle
public static Color GetDominantColor(this Bitmap bitmap, Rectangle area) {
return bitmap.GetDominantColor(area.X, area.Y, area.Width, area.Height);
}
但这应该足以开始。
推荐阅读
- r - 撤消 createDataPartition 排序
- python - scikit 的 cross_val_predict 是否为每个折叠重新计算 tfidf?
- python - 如何根据 Panda 绘制的散点图对数据进行分组
- c - 浮点文字“.1”是否与 C 中的“0.1”相同?
- r - 计算组均值和总体均值
- cmd - 如何将 cmd 输出中的每一行通过管道传输到从 Microsoft SQL 创建的表中的列?
- mongodb - MongoDB 模式:喜欢评论或帖子
- python - 仅替换字符串中完全匹配的单词
- javascript - 在 2 点之间向下滚动将不起作用
- ruby-on-rails - 无法在 Rails 应用程序中刷新 Google API 令牌